A local-first multi-agent app development platform, built on PenguinHarness
fix(server): 同步预置补上的模型沿用分组那把 key,不再显示未配置
lmliheng0a683980a7d2
diff --git a/changelog/unreleased/2026-10-30-preset-key-follows-the-group.md b/changelog/unreleased/2026-10-30-preset-key-follows-the-group.mdnew file mode 100644index 00000000..0252e2c1--- /dev/null+++ b/changelog/unreleased/2026-10-30-preset-key-follows-the-group.md@@ -0,0 +1,41 @@+# A preset a sync adds now takes the key its group already holds, instead of arriving unconfigured++- **Date:** 2026-10-30+- **Type:** fix+- **Scope:** `server`, `docs`+- **Breaking:** no++[中文版](2026-10-30-preset-key-follows-the-group.zh.md)++**Sync presets** adds the catalog models a Project does not have yet. In a gateway group — TokenDance,+OpenRouter, Fireworks AI, SiliconFlow, the two Qwen gateways, ModelScope — every row is answered by the same+endpoint behind the same login, so a preset that arrived without a key was drawn as having no key configured and+failed its own speed test next to a dozen working rows; the only cure was pasting the same key a thirteenth time.+Saving the model table now fills such a row from the key its group already holds, so the sync finishes the job the+one paste started.++## Details++- `packages/server/src/services/project-config-service.ts`: `groupApiKey(pool, provider, baseUrl)` answers the key+ a keyless row may borrow — the single `api_key` the table holds for that provider **and that base URL**, and+ nothing when those rows disagree. Two keys under one group are two accounts (or a deliberate split), and a+ different base URL is a different service, so in both cases the row stays keyless exactly as before rather than+ picking one.+- The pool a borrow is read from is the stored table **plus the rows the same request brings a key for**, so the+ answer does not depend on where in the table the page put the row it added: the page writes the whole table, and+ the row carrying the key may precede or follow the preset that needs it.+- Only rows the built-in catalog carries borrow. A model added by hand keeps the semantics it had: replacing it+ without its key still means the credential does not migrate.+- An explicit **Clear saved API key** is still an answer: a row a request asks to leave keyless is not filled back+ in by the row beside it.+- Tests: `packages/server/test/models.test.ts` gained four cases — the borrow itself (with the plaintext still+ absent from every response), a group holding two different keys, an explicit clear, and a preset pointed at+ another endpoint or added by hand.+- Docs: `packages/docs/content/models.{en,zh}.md`, "Sync preset models" — the list said syncing never touches API+ keys; it now names the one exception.++## Compatibility++- No breaking change: no protocol, DTO or file-layout change. A row that already had a key keeps it, a group with+ one key is the only shape that fills anything in, and an explicit clear is still respected.+- The key stays on the server: the borrow writes to `.project_config.toml` and a response carries only the mask.diff --git a/changelog/unreleased/2026-10-30-preset-key-follows-the-group.zh.md b/changelog/unreleased/2026-10-30-preset-key-follows-the-group.zh.mdnew file mode 100644index 00000000..74240f3b--- /dev/null+++ b/changelog/unreleased/2026-10-30-preset-key-follows-the-group.zh.md@@ -0,0 +1,34 @@+# 同步预置补上的模型直接沿用分组里已有的 key,不再显示「未配置密钥」++- **Date:** 2026-10-30+- **Type:** fix+- **Scope:** `server`, `docs`+- **Breaking:** no++[English](2026-10-30-preset-key-follows-the-group.md)++**同步预置**会把项目还没有的目录模型补进模型表。网关分组(TokenDance、OpenRouter、Fireworks AI、+SiliconFlow、两个 Qwen 网关、ModelScope)里所有条目都由同一个端点、同一个登录来应答,所以缺 key 的预置+会显示成没配密钥,在一排能用的条目旁边连自己的测速都过不了,唯一的办法是把同一把 key 再粘一遍。现在保存+模型表时,这样的条目会直接沿用分组里已经有的那把 key——一次粘贴就能把整组配好。++## 细节++- `packages/server/src/services/project-config-service.ts`:`groupApiKey(pool, provider, baseUrl)` 给出缺+ key 的条目可以沿用的那把——**同一个分组、同一个 base URL** 下唯一的 `api_key`;组内那把 key 不唯一时+ 返回空。同一分组下有两把不同的 key,说明是两个账号(或有意的拆分);base URL 不同就是另一个服务。这两种+ 情况都维持原样、留空,而不是替你猜一个。+- 判断用的那张「池子」是**已存的表加上这一次请求自己带来的 key**。模型页每次保存都写整张表,带 key 的那条+ 可能在要借的预置之前,也可能在它之后,两边都算进去,结果才与顺序无关。+- 只有内置目录里的条目会借。你自己添加的模型保持原有语义:不带 key 替换它,等于凭证不迁移。+- **清除已存 API key** 仍然有效:明确要求留空的条目不会被旁边的条目填回来。+- 测试:`packages/server/test/models.test.ts` 新增四条——借 key 本身(响应里始终没有明文)、组内两把不同+ 的 key、明确清除、以及指向别的端点或自己添加的条目。+- 文档:`packages/docs/content/models.{en,zh}.md` 的「同步预置模型」原先写「绝不动 API key」,现在把那一处+ 例外写清楚。++## 兼容性++- 无破坏性改动:协议、DTO、文件布局都没变。本来有 key 的条目照旧,只有「组内只有一把 key」这一种情况才会+ 填,明确清除依然生效。+- key 不离开服务端:沿用只写进 `.project_config.toml`,响应里仍然只有打码后的值。diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.mdindex e1d1b7e6..2feab8f8 100644--- a/packages/docs/content/models.en.md+++ b/packages/docs/content/models.en.md@@ -309,7 +309,7 @@ Syncing:- adds catalog models the Project does not have, retired rows excepted: one the Project already has is kept current, but a Project without it never gets it (see [Preset models](#preset-models));- resets each existing catalog model's vision flag, context window, protocol, prices, and base URL to the catalog's values;- fills in an empty display name, but never overwrites one;-- never touches API keys, **Max output tokens**, fast mode, or models and groups you added yourself.+- never touches API keys, **Max output tokens**, fast mode, or models and groups you added yourself. The one exception is a built-in preset row without a key: where its group and endpoint hold exactly one key — the usual shape of a gateway group — it takes that key instead of being drawn as having no key configured. A group holding two different keys leaves it blank, and a model you added yourself is not one of these.**Dismiss** hides the notice until a later catalog change.diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.mdindex 5b7bd2ec..f0301e61 100644--- a/packages/docs/content/models.zh.md+++ b/packages/docs/content/models.zh.md@@ -308,7 +308,7 @@ Adelie 升级可能改变内置的预置模型目录。一旦发生,Project ow- 添加 Project 还没有的目录模型,退役条目除外:Project 已有的退役条目照常更新,没有它的 Project 则不会被补上(见[预置模型](#预置模型));- 把已有目录模型的视觉标记、上下文窗口、协议、价格和 base URL 重置为目录里的值;- 模型名称为空时自动补全,但绝不覆盖已有名称;-- 绝不动 API key、**最大输出长度**、快速模式,以及你自己添加的模型和分组。+- 绝不动 API key、**最大输出长度**、快速模式,以及你自己添加的模型和分组。唯一的例外是缺少 key 的内置预置条目:同组、同端点下只有一把 key 时(网关分组几乎都如此),它会直接沿用那把,而不是以**未配置密钥**的样子出现;组内有两把不同的 key 时留空不动。你自己添加的模型不在其列。点击**忽略**后,通知会隐藏,直到目录再次变化才重新出现。diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.tsindex c8681a14..97df2cab 100644--- a/packages/server/src/services/project-config-service.ts+++ b/packages/server/src/services/project-config-service.ts@@ -82,6 +82,7 @@ import type {ModelRefDto,ModelsResponse,ModelsUpdateRequest,+ ModelUpdateEntry,ModelTestRequest,ModelTestResponse,ModelVisionDetectRequest,@@ -224,6 +225,47 @@ function optStr(v: unknown): string | undefined {return typeof v === "string" && v !== "" ? v : undefined;}+/** One row a keyless entry may borrow a key from: its group and the endpoint it speaks to. */+interface KeyPoolRow {+ provider: string;+ baseUrl: string | undefined;+ apiKey: string | undefined;+}++/**+ * The key a keyless row may borrow from the rows beside it: the single `api_key` the pool+ * holds for the same provider **and the same base URL**, or undefined when there is none or+ * when those rows disagree about it.+ *+ * "Sync presets" adds a catalog entry with no credential. That is right for a model nobody has+ * reached yet, and wrong for the fourteenth row of a gateway group: TokenDance — like every+ * other gateway — is one endpoint behind one key, so a preset the catalog carries later is the+ * same login as the rows beside it. Left keyless it reads "no key configured" and fails its own+ * speed test next to twelve rows that work, and the only cure the user has is pasting the same+ * key a thirteenth time. Borrowing it is what makes the sync finish the job they started when+ * they pasted it once.+ *+ * Borrowing stays inside an unambiguous group. Two different keys under one provider and one+ * base URL are two accounts (or a deliberate split), and picking one of them for a new row+ * would be a guess; a different base URL is a different service, where a shared provider id+ * says nothing about the credential. Both cases leave the row keyless, exactly as it was before+ * this rule existed.+ */+function groupApiKey(+ pool: readonly KeyPoolRow[],+ provider: string,+ baseUrl: string | undefined,+): string | undefined {+ const target = baseUrl ?? "";+ const keys = new Set<string>();+ for (const row of pool) {+ if (row.provider !== provider) continue;+ if ((row.baseUrl ?? "") !== target) continue;+ if (row.apiKey !== undefined) keys.add(row.apiKey);+ }+ return keys.size === 1 ? [...keys][0] : undefined;+}+/** Command-policy rules as DTOs: per-rule `enabled` made explicit (stored absence = on). */function toCommandPolicyRuleDtos(rules: readonly CommandPolicyRule[]): CommandPolicyRuleDto[] {return rules.map((r) => ({@@ -1292,6 +1334,32 @@ export class ProjectConfigService implements ProjectConfigStore {const hadModelScopeGroup = prevModels.some((model) => model.provider === MODELSCOPE_PROVIDER_ID,);+ // Where a keyless preset row may borrow a key from (see groupApiKey): the stored table plus+ // the rows this request itself brings a key for. Both halves are needed, because the models+ // page writes the whole table — the row that carries the key and the preset that needs it+ // arrive together, in an order the page chooses, and borrowing from the stored table alone+ // would make the outcome depend on that order. The endpoint is resolved the way the write+ // below resolves it, so a row is judged under the base URL it is about to have.+ const baseUrlOf = (entry: ModelUpdateEntry): string | undefined => {+ if (entry.baseUrl === null) return undefined;+ if (entry.baseUrl !== undefined) return entry.baseUrl;+ const ref = entry.renamedFrom ?? { provider: entry.provider, modelId: entry.modelId };+ return optStr(prevModels.find((m) => entryMatches(m, ref.provider, ref.modelId))?.base_url);+ };+ const keyPool: KeyPoolRow[] = [+ ...prevModels.map((m) => ({+ provider: optStr(m.provider) ?? "",+ baseUrl: optStr(m.base_url),+ apiKey: optStr(m.api_key),+ })),+ ...req.models+ .filter((entry) => !entry.clearApiKey && entry.apiKey !== undefined)+ .map((entry) => ({+ provider: entry.provider,+ baseUrl: baseUrlOf(entry),+ apiKey: entry.apiKey,+ })),+ ];// A vendor group carries the built-in catalog and nothing else: its entries persist no// client_type, so AgentHub places each one by the spelling of the model id alone, and an@@ -1449,6 +1517,23 @@ export class ProjectConfigService implements ProjectConfigStore {next.api_key = entry.apiKey;next.created_at = new Date().toISOString();if (entry.provider === MODELSCOPE_PROVIDER_ID) clearModelScopeProviderAuthToken = true;+ } else if (+ !entry.clearApiKey &&+ next.api_key === undefined &&+ catalogEntryFor(entry.provider, entry.modelId) !== undefined+ ) {+ // A preset row this request leaves keyless borrows its group's key when the table holds+ // exactly one for that provider + base URL (see groupApiKey). "Sync presets" is what puts+ // a catalog entry here without a credential, and a preset the catalog has carried since+ // before this rule reached the table is still keyless — saving the page is what fills it+ // in. Only the catalog's own rows borrow: a row added by hand is the user's own entry,+ // where replacing it without its key has always meant the credential does not migrate.+ const borrowed = groupApiKey(keyPool, entry.provider, baseUrlOf(entry));+ if (borrowed !== undefined) {+ next.api_key = borrowed;+ next.created_at = new Date().toISOString();+ if (entry.provider === MODELSCOPE_PROVIDER_ID) clearModelScopeProviderAuthToken = true;+ }}if (entry.baseUrl === null) delete next.base_url;else if (entry.baseUrl !== undefined) next.base_url = entry.baseUrl;diff --git a/packages/server/test/models.test.ts b/packages/server/test/models.test.tsindex 4101cca3..47bb1d92 100644--- a/packages/server/test/models.test.ts+++ b/packages/server/test/models.test.ts@@ -156,6 +156,176 @@ describe("models preset & catalog enrichment", () => {await expect(readFile(path.join(projectDir, "project_config.toml"), "utf8")).rejects.toThrow();});+ it("a preset a sync adds to a gateway group borrows the group's key instead of arriving unconfigured", async () => {+ const cfgFile = path.join(t.root, projectId, ".project_config.toml");+ const GATEWAY = "https://tokendance.space/gateway/v1";+ const row = (modelId: string, extra: Record<string, unknown> = {}) => ({+ provider: "tokendance",+ modelId,+ clientType: "openai-chat",+ baseUrl: GATEWAY,+ ...extra,+ });++ // The table before the sync: one TokenDance row, the key pasted once.+ const first = await api.put(url(), {+ defaultModel: { provider: "tokendance", modelId: "deepseek-v4-flash-0731" },+ models: [row("deepseek-v4-flash-0731", { apiKey: "sk-group-gateway-1" })],+ });+ expect(first.status).toBe(200);++ // What "sync presets" sends: the row that was there (restating no key at all) plus a preset+ // the catalog carries and this table does not — the shape that used to land keyless.+ const synced = await api.put(url(), {+ models: [row("deepseek-v4-flash-0731"), row("deepseek-v4-pro")],+ });+ expect(synced.status).toBe(200);+ const body = (await synced.json()) as ModelsResponse;+ const stored = pick(body, "tokendance", "deepseek-v4-flash-0731").credential?.apiKeyMasked;+ expect(stored).toBeTruthy();+ expect(pick(body, "tokendance", "deepseek-v4-pro").credential?.apiKeyMasked).toBe(stored);+ // Borrowed, never echoed: the plaintext stays on disk.+ expect(JSON.stringify(body)).not.toContain("sk-group-gateway-1");++ const cfgRaw = await readFile(cfgFile, "utf8");+ expect(cfgRaw.split('api_key = "sk-group-gateway-1"').length - 1).toBe(2);++ // The shape the rule exists for: a whole gateway group, the key pasted on one row of it.+ // One endpoint behind one login, so every preset the group carries is answered by that key.+ const group = MODEL_CATALOG.filter((m) => m.provider === "tokendance" && m.retired !== true);+ expect(group.length).toBeGreaterThan(4);+ const wholeGroup = await api.put(url(), {+ models: group.map((m, i) => ({+ provider: m.provider,+ modelId: m.modelId,+ ...(m.clientType !== undefined ? { clientType: m.clientType } : {}),+ ...(m.baseUrl !== undefined ? { baseUrl: m.baseUrl } : {}),+ ...(i === 0 ? { apiKey: "sk-group-gateway-1" } : {}),+ })),+ });+ expect(wholeGroup.status).toBe(200);+ const groupBody = (await wholeGroup.json()) as ModelsResponse;+ const firstMask = pick(groupBody, group[0]!.provider, group[0]!.modelId).credential?.apiKeyMasked;+ expect(firstMask).toBeTruthy();+ for (const m of group) {+ expect(pick(groupBody, m.provider, m.modelId).credential?.apiKeyMasked, m.modelId).toBe(+ firstMask,+ );+ }+ const groupRaw = await readFile(cfgFile, "utf8");+ expect(groupRaw.split('api_key = "sk-group-gateway-1"').length - 1).toBe(group.length);+ });++ it("a group holding two different keys is left to decide: the new row arrives keyless", async () => {+ const GATEWAY = "https://tokendance.space/gateway/v1";+ const row = (modelId: string, extra: Record<string, unknown> = {}) => ({+ provider: "tokendance",+ modelId,+ clientType: "openai-chat",+ baseUrl: GATEWAY,+ ...extra,+ });+ const twoKeys = await api.put(url(), {+ models: [+ row("deepseek-v4-flash-0731", { apiKey: "sk-first-account" }),+ row("deepseek-v4-pro", { apiKey: "sk-second-account" }),+ ],+ });+ expect(twoKeys.status).toBe(200);++ const added = await api.put(url(), {+ models: [row("deepseek-v4-flash-0731"), row("deepseek-v4-pro"), row("deepseek-v4.1-flash")],+ });+ expect(added.status).toBe(200);+ // Two accounts under one group is a deliberate state: picking one of them would be a guess.+ expect(+ pick((await added.json()) as ModelsResponse, "tokendance", "deepseek-v4.1-flash").credential+ ?.apiKeyMasked,+ ).toBeUndefined();+ });++ it("a row the request clears stays keyless: a clear is not filled back in by the row beside it", async () => {+ const GATEWAY = "https://tokendance.space/gateway/v1";+ const row = (modelId: string, extra: Record<string, unknown> = {}) => ({+ provider: "tokendance",+ modelId,+ clientType: "openai-chat",+ baseUrl: GATEWAY,+ ...extra,+ });+ await api.put(url(), {+ models: [+ row("deepseek-v4-flash-0731", { apiKey: "sk-group-gateway-1" }),+ row("deepseek-v4-pro"),+ ],+ });+ // Both rows do have the key by now (the second borrowed it) …+ const before = (await (await api.get(url())).json()) as ModelsResponse;+ expect(pick(before, "tokendance", "deepseek-v4-pro").credential?.apiKeyMasked).toBeTruthy();++ // … and taking one of them back is what keeps it keyless.+ const cleared = await api.put(url(), {+ models: [row("deepseek-v4-flash-0731"), row("deepseek-v4-pro", { clearApiKey: true })],+ });+ expect(cleared.status).toBe(200);+ const body = (await cleared.json()) as ModelsResponse;+ expect(pick(body, "tokendance", "deepseek-v4-pro").credential?.apiKeyMasked).toBeUndefined();+ expect(+ pick(body, "tokendance", "deepseek-v4-flash-0731").credential?.apiKeyMasked,+ ).toBeTruthy();+ });++ it("a preset pointed at another endpoint is another service: nothing is borrowed across them", async () => {+ const GATEWAY = "https://tokendance.space/gateway/v1";+ const row = (modelId: string, extra: Record<string, unknown> = {}) => ({+ provider: "tokendance",+ modelId,+ clientType: "openai-chat",+ ...extra,+ });+ await api.put(url(), {+ models: [row("deepseek-v4-flash-0731", { apiKey: "sk-gateway-account", baseUrl: GATEWAY })],+ });++ // The next preset is answered by the user's own relay: the gateway key is not its key.+ const relayed = await api.put(url(), {+ models: [+ row("deepseek-v4-flash-0731", { baseUrl: GATEWAY }),+ row("deepseek-v4-pro", { baseUrl: "https://relay.example/v1" }),+ ],+ });+ expect(relayed.status).toBe(200);+ const body = (await relayed.json()) as ModelsResponse;+ expect(pick(body, "tokendance", "deepseek-v4-pro").credential?.apiKeyMasked).toBeUndefined();+ expect(+ pick(body, "tokendance", "deepseek-v4-flash-0731").credential?.apiKeyMasked,+ ).toBeTruthy();++ // A row added by hand is the user's own entry: replacing it without its key has always meant+ // the credential does not migrate, and the rows beside it do not change that.+ const custom = (modelId: string, baseUrl: string, extra: Record<string, unknown> = {}) => ({+ provider: "custom",+ modelId,+ clientType: "openai-chat",+ baseUrl,+ ...extra,+ });+ await api.put(url(), {+ models: [custom("self-hosted-a", "https://a.example/v1", { apiKey: "sk-service-a" })],+ });+ const plain = await api.put(url(), {+ models: [+ custom("self-hosted-a", "https://a.example/v1"),+ custom("self-hosted-b", "https://a.example/v1"),+ ],+ });+ expect(plain.status).toBe(200);+ const plainBody = (await plain.json()) as ModelsResponse;+ expect(pick(plainBody, "custom", "self-hosted-b").credential?.apiKeyMasked).toBeUndefined();+ // The row that carried the key keeps it on its own account, base URL and all.+ expect(pick(plainBody, "custom", "self-hosted-a").credential?.apiKeyMasked).toBeTruthy();+ });+it("a new Project is preset with every built-in model (provider and model_id as separate fields + catalog info)", async () => {const res = await api.get(url());expect(res.status).toBe(200);