Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(web,server): 模型分组的 key 可以直接从用户密钥分配了

lmliheng80a71c3f8c53
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 3f967d1b..927f706e 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1408,6 +1408,27 @@ export interface UserVaultAssignRequest {
keys: string[];
}
+/**
+ * POST /api/projects/:p/models/assign-user-key body: ONE entry of the caller's own user-level
+ * vault, written as the api_key of every model in a provider group. A copy, not a link: the
+ * group's models keep the value they were given, so a later change to the global entry has to
+ * be assigned again.
+ *
+ * The name, not the value: only the server can read the plaintext (the user vault is masked on
+ * every response), so the browser asks for the copy and the server performs it.
+ */
+export interface ModelUserKeyAssignRequest {
+ /** The provider group whose models take the key — the group's header is where this is asked. */
+ provider: string;
+ /** The user-level entry's key name; it must exist in the caller's own user-level vault. */
+ key: string;
+}
+
+/** …the outcome: how many models of that group took the key (the same count the group-key flow reports). */
+export interface ModelUserKeyAssignResponse {
+ applied: number;
+}
+
// ---------------------------------------------------------------------------
// Agent and its config (system_config.yaml + AGENTS.md)
// ---------------------------------------------------------------------------
diff --git a/packages/server/src/http/routes/models.ts b/packages/server/src/http/routes/models.ts
index d6bbb50d..b71d79a7 100644
--- a/packages/server/src/http/routes/models.ts
+++ b/packages/server/src/http/routes/models.ts
@@ -4,8 +4,9 @@
* POST /api/projects/:p/models/test, POST /api/projects/:p/models/detect,
* POST /api/projects/:p/models/list, POST /api/projects/:p/models/detect-vision (the model
* reference `(provider, modelId)` is sent as a pair in the request body, avoiding
- * URL-encoding issues), GET /api/projects/:p/models/balance. Any member can read (api_key is
- * masked) and read a group's balance; only the owner can modify, test, or detect.
+ * URL-encoding issues), POST /api/projects/:p/models/assign-user-key, GET
+ * /api/projects/:p/models/balance. Any member can read (api_key is masked) and read a group's
+ * balance; only the owner can modify, test, or detect.
*/
import { Hono } from "hono";
import type {
@@ -17,6 +18,7 @@ import type {
ModelsUpdateRequest,
ModelTestRequest,
ModelUpdateEntry,
+ ModelUserKeyAssignResponse,
ModelVisionDetectRequest,
ServerEvent,
} from "../../api/types.js";
@@ -28,6 +30,7 @@ import type { SessionManager } from "../../runtime/session-manager.js";
import type { SessionIndex } from "../../mechanisms/sessions.js";
import type { Access, ProjectConfigStore } from "../../mechanisms/projects.js";
import type { Machines } from "../../machines/service.js";
+import type { UserVault } from "../../mechanisms/vault.js";
import { ModelBalances } from "../../services/model-balance.js";
/** What this route group reaches — bound by its module (src/modules). */
@@ -39,6 +42,8 @@ export interface ModelsRouteDeps {
projectConfigService: ProjectConfigStore;
access: Access;
sessionsRepo: SessionIndex;
+ /** The caller's own user-level vault: the source of an assigned key (assign-user-key). */
+ userVault: UserVault;
}
/**
@@ -229,6 +234,33 @@ export function modelsRoutes(deps: ModelsRouteDeps): Hono<AppEnv> {
return c.json(res);
});
+ // One entry of the caller's own user-level vault, written as this group's api_key. It exists
+ // because the browser cannot do it: every user-vault response is masked, so the value is only
+ // ever read here, server-side, and written straight into the Project's model config — which is
+ // why the request names a key and not a value. Like the Agent-side assign, it is a COPY: the
+ // group keeps what it was given, and a later edit of the global entry has to be assigned again.
+ // Owner-only, like every other write to the model config; the page offers the action only for
+ // groups whose rows share one endpoint (custom's, each reaching its own, is left out).
+ app.post("/assign-user-key", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
+ const body = await readJson(c);
+ const provider = requireString(body, "provider", {
+ minLen: 1,
+ maxLen: 64,
+ label: "provider",
+ });
+ const key = requireString(body, "key", { minLen: 1, maxLen: 128, label: "key" });
+ const value = await deps.userVault.readEntry(c.var.user.userId, key);
+ if (value === undefined) {
+ throw badRequest(`Not in your user vault: ${key}.`);
+ }
+ const applied = await deps.projectConfigService.setGroupApiKey(projectId, provider, value);
+ if (applied > 0) modelConfigChanged(deps, projectId);
+ const res: ModelUserKeyAssignResponse = { applied };
+ return c.json(res);
+ });
+
// A group's account balance (any member, like the table itself): the server asks the
// vendor with the group's stored key, so the key never reaches the browser. A balance that
// cannot be read is an answer (`ok: false` with a code), as a failed connectivity test is.
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index d5d87f56..77855576 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -2151,6 +2151,7 @@ export class SessionApiRoutes {
machines: this.machines,
projectConfigService,
sessionsRepo,
+ userVault: this.userVault,
};
const modelDeps = {
channels,
@@ -2159,6 +2160,7 @@ export class SessionApiRoutes {
projectConfigService,
access,
sessionsRepo,
+ userVault: this.userVault,
};
this.modelOauthCallbackRoutes = modelOAuthCallbackRoutes(modelOAuthDeps);
this.modelsRoutes = modelsRoutes(modelDeps);
diff --git a/packages/server/src/mechanisms/vault.ts b/packages/server/src/mechanisms/vault.ts
index 236504be..65cbe9e0 100644
--- a/packages/server/src/mechanisms/vault.ts
+++ b/packages/server/src/mechanisms/vault.ts
@@ -31,4 +31,11 @@ export abstract class UserVault {
agentId: string,
keys: string[],
): Promise<VaultResponse>;
+ /**
+ * One entry's plaintext, for a copy into something that is not a vault — today a Project's
+ * model credential (POST /api/projects/:p/models/assign-user-key). Nothing that builds a
+ * response calls this: the value must not cross the boundary, so its caller is a route that
+ * writes it into another file on this server. Undefined when the account has no such key.
+ */
+ abstract readEntry(userId: string, key: string): Promise<string | undefined>;
}
diff --git a/packages/server/src/services/user-vault-service.ts b/packages/server/src/services/user-vault-service.ts
index bb930dae..f9029a49 100644
--- a/packages/server/src/services/user-vault-service.ts
+++ b/packages/server/src/services/user-vault-service.ts
@@ -8,12 +8,15 @@
* response carries masked values only — plaintext never leaves the server, the responses of a
* write included.
*
- * "Assign to an Agent" is the one cross-scope operation here, and it is a COPY: the named entries
- * are written into that Agent's own `.vault.toml` by the Agent config service — this service never
- * touches that file, and the Agent vault keeps its single writer. Same key overwrites, the Agent's
+ * "Assign to an Agent" and "assign to a group's models" are the two cross-scope operations here,
+ * and both are a COPY: the named entries are written into that Agent's own `.vault.toml` by the
+ * Agent config service — this service never touches that file, and the Agent vault keeps its
+ * single writer — or, for a model, the named entry's value goes into the Project's model
+ * credential (routes/models.ts reads it through {@link UserVaultService.readEntry}, which is why
+ * that read takes one key and never appears in a response). Same key overwrites, the Agent's
* other entries stay. Nothing reads the user vault at Session time, so a later change to a
- * user-level entry does not reach an Agent that was assigned before it: the Agent keeps what it
- * was given until the user assigns again.
+ * user-level entry does not reach a target that was assigned before it: it keeps what it was
+ * given until the user assigns again.
*
* Lives in the Agents module because assigning reaches the Agent config service (the Agent's own
* vault), whose existence check and masked read both come from there; the API layer reaches the
@@ -118,6 +121,15 @@ export class UserVaultService implements UserVault {
return maskTable(next);
}
+ /**
+ * One entry's plaintext, for a caller that writes it into another file on this server (the
+ * model credential; see the mechanism). A key the account does not have is `undefined` rather
+ * than an empty string, so the caller can name the failure.
+ */
+ async readEntry(userId: string, key: string): Promise<string | undefined> {
+ return (await loadUserVault(this.root, userId))[key];
+ }
+
/** Copy named user-level entries into one Agent's vault (see the module doc: a copy, not a link). */
async assignToAgent(
userId: string,
diff --git a/packages/server/test/models-assign-user-key.test.ts b/packages/server/test/models-assign-user-key.test.ts
new file mode 100644
index 00000000..0d46bb56
--- /dev/null
+++ b/packages/server/test/models-assign-user-key.test.ts
@@ -0,0 +1,176 @@
+/**
+ * `POST /api/projects/:p/models/assign-user-key` — one of the account's own global secrets,
+ * copied onto every model of a provider group as its `api_key`.
+ *
+ * The browser cannot do this itself: every user-vault response is masked, so the request names an
+ * ENTRY and the server reads the plaintext from `<root>/users/<userId>/.vault.toml` and writes it
+ * into the Project's `.project_config.toml`. Hence the cases below:
+ *
+ * - It copies: the value lands on every row of the group, is reported as `applied`, and the mask
+ * every later read shows is the one the browser can see — plaintext in no response.
+ * - It is the CALLER's own table: the same entry name on another account is not the value used.
+ * - A group with no rows writes nothing and says 0; a name the caller does not hold is a 400 that
+ * names it, and so is a body without a provider or a key.
+ * - Owner-only, like the rest of the model config: a member is 403, an outsider 404, no cookie 401.
+ */
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import type {
+ ModelsResponse,
+ ModelUserKeyAssignResponse,
+ ProjectCreateResponse,
+} from "../src/api/types.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+/** The group the cases write a key onto — a gateway group: one endpoint, one key, many rows. */
+const GROUP = "tokendance";
+const GATEWAY = "https://tokendance.space/gateway/v1";
+
+describe("assign a user key to a model group", () => {
+ let t: TestApp;
+ let owner: ReturnType<typeof apiClient>;
+ let member: ReturnType<typeof apiClient>;
+ let outsider: ReturnType<typeof apiClient>;
+ let projectId: string;
+ let configFile: string;
+
+ /** The group's rows, as the whole-table PUT wants them: the key never stated on them. */
+ const rows = (ids: string[]) =>
+ ids.map((modelId) => ({
+ provider: GROUP,
+ modelId,
+ clientType: "openai-chat",
+ baseUrl: GATEWAY,
+ }));
+
+ beforeAll(async () => {
+ t = await createTestApp();
+ const a = await provisionUser(t.app, "owner_a");
+ const b = await provisionUser(t.app, "member_b");
+ const c = await provisionUser(t.app, "outsider_c");
+ owner = apiClient(t.app, a.cookie);
+ member = apiClient(t.app, b.cookie);
+ outsider = apiClient(t.app, c.cookie);
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+
+ let projects = 0;
+ beforeEach(async () => {
+ projects += 1;
+ const created = (await (
+ await owner.post("/api/projects", {
+ projectId: `owner_a-assignkey_${projects}`,
+ name: "Assign key project",
+ })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ configFile = path.join(t.root, projectId, ".project_config.toml");
+ // Three rows of the group and no key anywhere: what the action is for.
+ const put = await owner.put(`/api/projects/${projectId}/models`, {
+ models: rows(["deepseek-v4-flash-0731", "deepseek-v4-pro", "deepseek-v4.1-flash"]),
+ });
+ expect(put.status).toBe(200);
+ expect(
+ (await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,
+ ).toBe(201);
+ expect((await owner.put("/api/me/vault", { entries: [] })).status).toBe(200);
+ expect((await member.put("/api/me/vault", { entries: [] })).status).toBe(200);
+ });
+
+ const assign = (client: ReturnType<typeof apiClient>, body: unknown) =>
+ client.post(`/api/projects/${projectId}/models/assign-user-key`, body);
+
+ it("copies the entry onto every row of the group and leaks no plaintext", async () => {
+ await owner.put("/api/me/vault", {
+ entries: [{ key: "TEAM_KEY", value: "sk-user-team-123456" }],
+ });
+
+ const res = await assign(owner, { provider: GROUP, key: "TEAM_KEY" });
+ expect(res.status).toBe(200);
+ // Neither the outcome nor a later read carries the value: only the mask.
+ const text = await res.text();
+ expect((JSON.parse(text) as ModelUserKeyAssignResponse).applied).toBe(3);
+ expect(text).not.toContain("sk-user-team-123456");
+
+ const body = (await (
+ await owner.get(`/api/projects/${projectId}/models`)
+ ).json()) as ModelsResponse;
+ const masks = body.models
+ .filter((m) => m.provider === GROUP)
+ .map((m) => m.credential?.apiKeyMasked);
+ expect(masks).toEqual(["sk-u…3456", "sk-u…3456", "sk-u…3456"]);
+ expect(JSON.stringify(body)).not.toContain("sk-user-team-123456");
+
+ // On disk it is a real key on every row of the group — and a copy: the user's own table
+ // keeps its entry (there is no link for a later edit to travel along).
+ const raw = await readFile(configFile, "utf8");
+ expect(raw.split('api_key = "sk-user-team-123456"').length - 1).toBe(3);
+ const user = (await (await owner.get("/api/me/vault")).json()) as { entries: unknown[] };
+ expect(user.entries).toEqual([{ key: "TEAM_KEY", valueMasked: "sk-u…3456" }]);
+ });
+
+ it("reads the caller's own table: another account's entry of the same name is not the value", async () => {
+ await owner.put("/api/me/vault", {
+ entries: [{ key: "TEAM_KEY", value: "sk-owner-key-123456" }],
+ });
+ await member.put("/api/me/vault", {
+ entries: [{ key: "TEAM_KEY", value: "sk-member-key-12345" }],
+ });
+
+ expect((await assign(owner, { provider: GROUP, key: "TEAM_KEY" })).status).toBe(200);
+ const raw = await readFile(configFile, "utf8");
+ expect(raw).toContain("sk-owner-key-123456");
+ expect(raw).not.toContain("sk-member-key-12345");
+ });
+
+ it("an empty group writes nothing and says so; an unknown name or a malformed body is a 400", async () => {
+ await owner.put("/api/me/vault", { entries: [{ key: "MINE", value: "mine-secret-123456" }] });
+
+ // A group the table has no rows for: nothing to write, and the count says exactly that.
+ const empty = await assign(owner, { provider: "openai", key: "MINE" });
+ expect(empty.status).toBe(200);
+ expect(((await empty.json()) as ModelUserKeyAssignResponse).applied).toBe(0);
+
+ // A name the caller does not hold is refused, and the refusal names it.
+ const missing = await assign(owner, { provider: GROUP, key: "NOT_IN_MY_VAULT" });
+ expect(missing.status).toBe(400);
+ expect(await missing.text()).toContain("NOT_IN_MY_VAULT");
+
+ for (const body of [
+ { provider: GROUP }, // no key
+ { key: "MINE" }, // no provider
+ { provider: "", key: "MINE" }, // empty provider
+ { provider: GROUP, key: "" }, // empty key
+ { provider: 42, key: "MINE" }, // not a string
+ { provider: GROUP, key: "MINE".repeat(64) }, // over the 128-char cap
+ ]) {
+ expect((await assign(owner, body)).status, JSON.stringify(body)).toBe(400);
+ }
+
+ // None of the refused calls touched the config: the rows still hold no key at all.
+ expect(await readFile(configFile, "utf8")).not.toContain("api_key");
+ });
+
+ it("is owner-only: a member is 403, an outsider 404, no cookie 401", async () => {
+ await owner.put("/api/me/vault", { entries: [{ key: "MINE", value: "mine-secret-123456" }] });
+ await member.put("/api/me/vault", { entries: [{ key: "MINE", value: "theirs-secret-1234" }] });
+
+ expect((await assign(member, { provider: GROUP, key: "MINE" })).status).toBe(403);
+ expect((await assign(outsider, { provider: GROUP, key: "MINE" })).status).toBe(404);
+ expect(
+ (
+ await t.app.request(`/api/projects/${projectId}/models/assign-user-key`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ provider: GROUP, key: "MINE" }),
+ })
+ ).status,
+ ).toBe(401);
+
+ expect(await readFile(configFile, "utf8")).not.toContain("api_key");
+ });
+});
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index d14a9c1c..92925ed3 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -70,6 +70,7 @@ import type {
ModelProtocolDetectResponse,
ModelsResponse,
ModelTestResponse,
+ ModelUserKeyAssignResponse,
ModelVisionDetectResponse,
ImportedThemesResponse,
ThemeRegistryResponse,
@@ -694,6 +695,25 @@ router
.post("/api/projects/:projectId/models/detect-vision", (): ModelVisionDetectResponse => ({
outcome: "unsupported",
}))
+ // One of the account's own global secrets, copied onto a group's models as their key. The
+ // fixture holds no plaintext either, so the rows take the entry's masked value — which is what
+ // the page can see afterwards anyway, the whole point of the flow.
+ .post(
+ "/api/projects/:projectId/models/assign-user-key",
+ ({ store, body }): ModelUserKeyAssignResponse => {
+ const { provider, key } = record(body);
+ const entry = store.f.userVault.entries.find((e) => e.key === key);
+ if (entry === undefined) fail(400, "bad_request", `Not in your user vault: ${str(key)}.`);
+ const createdAt = new Date().toISOString();
+ let applied = 0;
+ for (const m of store.f.models.models) {
+ if (m.provider !== provider) continue;
+ m.credential = { ...(m.credential ?? {}), apiKeyMasked: entry.valueMasked, createdAt };
+ applied += 1;
+ }
+ return { applied };
+ },
+ )
.post("/api/projects/:projectId/model-oauth/start", () =>
readOnly("open a provider authorization flow"),
)
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index e812abc0..97b5f942 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -103,6 +103,8 @@ import type {
ModelsUpdateRequest,
ModelTestRequest,
ModelTestResponse,
+ ModelUserKeyAssignRequest,
+ ModelUserKeyAssignResponse,
ModelVisionDetectRequest,
ModelVisionDetectResponse,
OrganizationCreateRequest,
@@ -522,6 +524,18 @@ export const putDefaultModel = (projectId: string, body: DefaultModelUpdateReque
body,
});
+/**
+ * One of the caller's own global secrets (the account menu's user keys), copied onto every model
+ * of a provider group as its api_key. The request names the entry, never its value: only the
+ * server can read the plaintext, so the copy happens there. A copy, not a link — editing the
+ * global entry afterwards means assigning again.
+ */
+export const assignUserKeyToModels = (projectId: string, body: ModelUserKeyAssignRequest) =>
+ apiFetch<ModelUserKeyAssignResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/models/assign-user-key`,
+ { method: "POST", body },
+ );
+
/**
* A group's account balance, read by the server with the group's stored key (the key never
* comes back). `force` skips the server's 60 s cache — the page's refresh click.
diff --git a/packages/web/src/features/models/group-header.ts b/packages/web/src/features/models/group-header.ts
index 777851ef..859c1e14 100644
--- a/packages/web/src/features/models/group-header.ts
+++ b/packages/web/src/features/models/group-header.ts
@@ -4,9 +4,9 @@
*
* The actions stand in a fixed order: the balance (where the catalog declares one), then a
* divider, Connect with its status (groups whose key comes from an authorization flow), Sync (a
- * connected Penguin Go), Enter key, the speed test, Add model (groups that take hand-added
- * models), Delete group (user-defined groups). A member sees what they can read — the balance
- * and the connection status, without its button; every action that writes is the owner's.
+ * connected Penguin Go), Enter key, Assign a user key, the speed test, Add model (groups that take
+ * hand-added models), Delete group (user-defined groups). A member sees what they can read — the
+ * balance and the connection status, without its button; every action that writes is the owner's.
*/
import {
MODEL_PROVIDERS,
@@ -28,7 +28,14 @@ export const HEADER_TEXT = "flex h-7 shrink-0 items-center px-1.5 text-xs";
export const HEADER_LABEL = "hidden text-xs @3xl:inline";
export type GroupHeaderAction =
- "balance" | "connect" | "platformSync" | "groupKey" | "speedTest" | "addModel" | "deleteGroup";
+ | "balance"
+ | "connect"
+ | "platformSync"
+ | "groupKey"
+ | "assignUserKey"
+ | "speedTest"
+ | "addModel"
+ | "deleteGroup";
/** A row as far as its key is concerned: a stored (masked) key, or one lent by the server's environment. */
export interface KeyedRowLike {
@@ -96,6 +103,8 @@ export function groupHeaderActions(
if (provider.id === PENGUIN_GO_PROVIDER_ID && keyStored) actions.push("platformSync");
// Custom's rows each reach their own endpoint, so one key written across them is never right.
if (provider.id !== "custom") actions.push("groupKey");
+ // Same gate and same reason: what is copied is one key, and this group's models would share it.
+ if (provider.id !== "custom") actions.push("assignUserKey");
actions.push("speedTest");
if (isAddableGroup(provider.id)) actions.push("addModel");
// A built-in group is catalog identity; a user-defined one exists only through its rows.
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index bb55278e..322f1d93 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -42,6 +42,7 @@ import type {
ModelTestRequest,
ModelUpdateEntry,
ModelVisionDetectRequest,
+ VaultEntryInfo,
} from "@adelie/server/api";
import {
Button,
@@ -845,6 +846,8 @@ export function ModelsPage() {
const [groupDropHint, setGroupDropHint] = useState<{ key: string; after: boolean } | null>(null);
/** Vendor group (provider id) currently having its API key configured in bulk. */
const [groupKeyFor, setGroupKeyFor] = useState<string | null>(null);
+ /** Vendor group (provider id) whose API key is being copied from the account's own user keys. */
+ const [assignKeyFor, setAssignKeyFor] = useState<string | null>(null);
/** Vendor group (provider id) whose authorization dialog is open (groups that publish a key-minting flow only). */
const [oauthFor, setOauthFor] = useState<string | null>(null);
/** Whether the open authorization actually wrote a key — see the dialog's `onClose`. */
@@ -1327,6 +1330,24 @@ export function ModelsPage() {
<span className={HEADER_LABEL}>{S.models.groupApiKey}</span>
</Button>
);
+ case "assignUserKey":
+ // The account's own global secrets, copied onto this group as its API key. It stands
+ // beside Enter key because it writes the same field; what differs is where the value comes
+ // from — and only the server can read it, so the copy is made there (see the dialog).
+ return (
+ <Button
+ size="icon"
+ variant="ghost"
+ className={HEADER_BUTTON}
+ disabled={busy}
+ aria-label={`${S.models.assignUserKey} ${provider.label}`}
+ title={S.models.assignUserKey}
+ onClick={() => setAssignKeyFor(group.provider.id)}
+ >
+ <GlyphIcon d={ICONS.user} size={ICON_SIZE.groupHeaderAction} />
+ <span className={HEADER_LABEL}>{S.models.assignUserKey}</span>
+ </Button>
+ );
case "speedTest": {
// One icon for both directions: it starts a run (after the confirmation) and, while
// its own group's run is going, stops it — the gauge turns into the registry's square in
@@ -1676,6 +1697,25 @@ export function ModelsPage() {
/>
)}
+ {/* The group's key copied from the account's own global secrets. Unlike its neighbours this
+ dialog does its own write (the value lives only on the server, so it cannot go through
+ the page's whole-table PUT): it closes on success and the page reloads the table to show
+ the masked key it now holds. */}
+ {projectId && assignKeyFor !== null && (
+ <AssignUserKeyDialog
+ projectId={projectId}
+ provider={assignKeyFor}
+ providerLabel={MODEL_PROVIDERS.find((p) => p.id === assignKeyFor)?.label ?? assignKeyFor}
+ count={rows?.filter((r) => r.provider === assignKeyFor).length ?? 0}
+ onClose={() => setAssignKeyFor(null)}
+ onAssigned={(applied) => {
+ setAssignKeyFor(null);
+ toastSuccess(S.models.groupKeyApplied(applied));
+ void load();
+ }}
+ />
+ )}
+
{/* NOT gated on `rows`, unlike its neighbours. This dialog outlives a table reload: it
stays open after the key lands to report the outcome, and `load()` blanks `rows` on
its first line, so gating it there would unmount it mid-flow — and its mount effect
@@ -4003,6 +4043,134 @@ function GroupKeyDialog({
);
}
+// ---------------------------------------------------------------------------
+// Copy one of the account's global secrets onto a group as its API key
+// ---------------------------------------------------------------------------
+
+/**
+ * The account's own user keys, offered one at a time (a model holds ONE key), plus the copy
+ * itself. The list is a fresh read every time the dialog opens and is read-only: editing the
+ * account's table is the account menu's dialog, and this one copies.
+ *
+ * The write is this dialog's own (POST ···/models/assign-user-key) rather than the page's
+ * whole-table PUT, because the value never reaches the browser: the request names the entry and
+ * the server takes the plaintext from the user vault and writes it into the model config. That is
+ * also why the dialog, not the page, reports a refusal — nothing has changed when one comes back.
+ */
+function AssignUserKeyDialog({
+ projectId,
+ provider,
+ providerLabel,
+ count,
+ onClose,
+ onAssigned,
+}: {
+ projectId: string;
+ /** The group's provider id — what the server writes the key onto. */
+ provider: string;
+ providerLabel: string;
+ /** How many models of the group take it (the count the copy reports). */
+ count: number;
+ onClose: () => void;
+ onAssigned: (applied: number) => void;
+}) {
+ const [entries, setEntries] = useState<VaultEntryInfo[] | null>(null);
+ const [picked, setPicked] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ void (async () => {
+ try {
+ const table = await api.getUserVault();
+ if (!cancelled) setEntries(table.entries);
+ } catch (e) {
+ if (!cancelled) setError(apiErrorText(e));
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const confirm = async () => {
+ if (picked === null) return;
+ setBusy(true);
+ setError(null);
+ try {
+ const res = await api.assignUserKeyToModels(projectId, { provider, key: picked });
+ if (res.applied === 0) {
+ // Nothing was written, so nothing is reported as written: a group with no rows is the
+ // only way here, and it closes nothing.
+ setError(S.models.assignUserKeyMissing);
+ setBusy(false);
+ return;
+ }
+ onAssigned(res.applied);
+ } catch (e) {
+ setError(apiErrorText(e));
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Modal
+ open
+ title={S.models.assignUserKeyTitle(providerLabel)}
+ onClose={onClose}
+ widthClass="sm:max-w-lg"
+ footer={
+ <>
+ <Button size="sm" onClick={onClose}>
+ {S.common.cancel}
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy || picked === null}
+ onClick={() => void confirm()}
+ >
+ {S.common.confirm}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <p className="text-xs leading-relaxed text-gray-500 dark:text-gray-400">
+ {S.models.assignUserKeyHint(count)}
+ </p>
+ {error !== null ? (
+ <p className="text-xs text-red-600 dark:text-red-400">{error}</p>
+ ) : entries === null ? (
+ <SkeletonList rows={3} />
+ ) : entries.length === 0 ? (
+ <EmptyState dashed title={S.models.assignUserKeyEmpty} />
+ ) : (
+ <div className="overflow-y-auto rounded-md border border-gray-200 dark:border-gray-800">
+ {entries.map((entry) => (
+ <div
+ key={entry.key}
+ className="flex items-center justify-between gap-3 border-b border-gray-100 px-3 py-2 last:border-b-0 dark:border-gray-800/60"
+ >
+ <Checkbox
+ checked={picked === entry.key}
+ // One key per model: picking a second replaces the first, the way a radio would.
+ onChange={(on) => setPicked(on ? entry.key : null)}
+ label={<span className="font-mono text-xs">{entry.key}</span>}
+ />
+ <span className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400">
+ {entry.valueMasked}
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </Modal>
+ );
+}
+
// ---------------------------------------------------------------------------
// Authorize a new API key for a provider group
// ---------------------------------------------------------------------------
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index a21e1e9a..7799974b 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -2158,6 +2158,19 @@ export const en: Strings = {
groupApiKeyHint: (n: number): string =>
`Applies to all ${n} models in this group; leave empty to keep them unchanged.`,
getApiKey: "Manage keys",
+ /**
+ * Copying one of the account's own global secrets onto a group as its API key (the group
+ * header's action beside Enter key). The value never comes back from the server, so the person
+ * picks an ENTRY and the server performs the copy — the copy wording matches the Agent vault's
+ * own assign dialog, because it is the same kind of operation.
+ */
+ assignUserKey: "Assign a user key",
+ assignUserKeyTitle: (label: string): string => `Assign one of your user keys to ${label}`,
+ assignUserKeyHint: (n: number): string =>
+ `Pick one of your global secrets; it is copied onto all ${n} models in this group as their API key. A later edit of the global entry has to be assigned again.`,
+ assignUserKeyEmpty:
+ "Your user keys table is empty — add one from the account menu's User keys row first, then come back here.",
+ assignUserKeyMissing: "This group has no models to write the key to",
getModelIds: "Get model IDs",
groupKeyApplied: (n: number): string => `API key set for ${n} models`,
oauthKey: "Connect",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 70a0b2b8..8cce291d 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -2205,6 +2205,19 @@ export const zh = {
groupApiKeyTitle: (label: string): string => `为「${label}」统一配置 API key`,
groupApiKeyHint: (n: number): string => `将写入该分组下全部 ${n} 个模型;留空不改动。`,
getApiKey: "前往密钥管理",
+ /**
+ * Copying one of the account's own global secrets onto a group as its API key (the group
+ * header's action beside 填写密钥). The value never comes back from the server, so the person
+ * picks an ENTRY and the server performs the copy — the copy wording matches the Agent vault's
+ * own assign dialog, because it is the same kind of operation.
+ */
+ assignUserKey: "从用户密钥分配",
+ assignUserKeyTitle: (label: string): string => `给「${label}」分配一条全局密钥`,
+ assignUserKeyHint: (n: number): string =>
+ `选一条你的全局密钥,拷贝给该分组下全部 ${n} 个模型作为 API key;之后全局那条改了,要重新分配才会同步。`,
+ assignUserKeyEmpty:
+ "你的用户密钥里还没有条目——先在左下角账号菜单 ›「用户密钥」里添加,再回到这里分配。",
+ assignUserKeyMissing: "这个分组里没有模型,没有可写入的对象",
getModelIds: "获取模型 id",
groupKeyApplied: (n: number): string => `已为 ${n} 个模型配置 API key`,
// 供应商授权取 key(模型分组头部动作):整个 PKCE 流程都在服务端跑,前端只拿到一个
diff --git a/packages/web/test/model-group-header.test.ts b/packages/web/test/model-group-header.test.ts
index 4153ad65..c2cf829d 100644
--- a/packages/web/test/model-group-header.test.ts
+++ b/packages/web/test/model-group-header.test.ts
@@ -5,10 +5,11 @@
*
* The matrix, per group kind: the balance where the catalog declares one (TokenDance, DeepSeek)
* and the group holds a key; Connect with its status on the three groups with a flow; Enter key
- * everywhere but custom; the speed test everywhere; Add model only where hand-added models are
- * taken (custom, vLLM, user-defined); Delete group only on a user-defined group. A member keeps
- * the two read-only parts and nothing that writes. A divider follows the balance wherever
- * something comes after it.
+ * and Assign a user key everywhere but custom (whose rows each reach their own endpoint, so one
+ * key written across them is never right); the speed test everywhere; Add model only where
+ * hand-added models are taken (custom, vLLM, user-defined); Delete group only on a user-defined
+ * group. A member keeps the two read-only parts and nothing that writes. A divider follows the
+ * balance wherever something comes after it.
*/
import { describe, expect, it } from "vitest";
import { MODEL_PROVIDERS, providerInfo } from "@adelie/core/model-catalog";
@@ -33,20 +34,32 @@ const keyed = [{ credential: { apiKeyMasked: "sk-t…1234" } }, {}];
const keyless = [{}, { credential: {} }];
describe("the group header's actions, in order, by group kind", () => {
- it("TokenDance: balance once a key is stored, Connect, Enter key, speed test — no Add model", () => {
- expect(owner("tokendance", true)).toEqual(["balance", "connect", "groupKey", "speedTest"]);
+ it("TokenDance: balance once a key is stored, Connect, Enter key, Assign a user key, speed test — no Add model", () => {
+ expect(owner("tokendance", true)).toEqual([
+ "balance",
+ "connect",
+ "groupKey",
+ "assignUserKey",
+ "speedTest",
+ ]);
// Without a key there is nothing to ask the vendor with.
- expect(owner("tokendance", false)).toEqual(["connect", "groupKey", "speedTest"]);
+ expect(owner("tokendance", false)).toEqual([
+ "connect",
+ "groupKey",
+ "assignUserKey",
+ "speedTest",
+ ]);
});
it("Penguin Go and ModelScope connect; a connected Penguin Go also syncs its catalog", () => {
- expect(owner("penguin-go", false)).toEqual(["connect", "groupKey", "speedTest"]);
- expect(owner("penguin-go", true)).toEqual(["connect", "platformSync", "groupKey", "speedTest"]);
- expect(owner("modelscope", true)).toEqual(["connect", "groupKey", "speedTest"]);
+ const tail = ["groupKey", "assignUserKey", "speedTest"];
+ expect(owner("penguin-go", false)).toEqual(["connect", ...tail]);
+ expect(owner("penguin-go", true)).toEqual(["connect", "platformSync", ...tail]);
+ expect(owner("modelscope", true)).toEqual(["connect", ...tail]);
});
it("DeepSeek shows its balance and connects nowhere; the other vendors and gateways key and test only", () => {
- expect(owner("deepseek", true)).toEqual(["balance", "groupKey", "speedTest"]);
+ expect(owner("deepseek", true)).toEqual(["balance", "groupKey", "assignUserKey", "speedTest"]);
for (const id of [
"openrouter",
"siliconflow",
@@ -55,15 +68,21 @@ describe("the group header's actions, in order, by group kind", () => {
"openai",
"google",
]) {
- expect(owner(id, true), id).toEqual(["groupKey", "speedTest"]);
+ expect(owner(id, true), id).toEqual(["groupKey", "assignUserKey", "speedTest"]);
}
});
it("vLLM, custom and user-defined groups take hand-added models; only a user-defined group deletes", () => {
- expect(owner("vllm")).toEqual(["groupKey", "speedTest", "addModel"]);
- // Custom's rows each reach their own endpoint: no key written across them.
+ expect(owner("vllm")).toEqual(["groupKey", "assignUserKey", "speedTest", "addModel"]);
+ // Custom's rows each reach their own endpoint: no key written across them, by either action.
expect(owner("custom")).toEqual(["speedTest", "addModel"]);
- expect(owner("my-own-group")).toEqual(["groupKey", "speedTest", "addModel", "deleteGroup"]);
+ expect(owner("my-own-group")).toEqual([
+ "groupKey",
+ "assignUserKey",
+ "speedTest",
+ "addModel",
+ "deleteGroup",
+ ]);
});
it("Add model appears on no built-in group but custom and vLLM", () => {
@@ -81,9 +100,14 @@ describe("the group header's actions, in order, by group kind", () => {
});
it("a pinned balance stays in its header after the key is gone, so the pin can come off there", () => {
- expect(owner("deepseek", false, true)).toEqual(["balance", "groupKey", "speedTest"]);
+ expect(owner("deepseek", false, true)).toEqual([
+ "balance",
+ "groupKey",
+ "assignUserKey",
+ "speedTest",
+ ]);
// Only where the catalog declares a balance at all.
- expect(owner("openrouter", false, true)).toEqual(["groupKey", "speedTest"]);
+ expect(owner("openrouter", false, true)).toEqual(["groupKey", "assignUserKey", "speedTest"]);
});
});
@@ -93,6 +117,7 @@ describe("a key lent by the server's environment", () => {
expect(groupHeaderActions(group("deepseek"), facts)).toEqual([
"balance",
"groupKey",
+ "assignUserKey",
"speedTest",
]);
expect(groupHeaderActions(group("deepseek"), { ...facts, isOwner: false })).toEqual([