A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server,cli,core): the models page's group headers — Connect, Enter key, balances and a TokenDance banner (#914)
Yaowei Zheng3c4943a33aff
diff --git a/changelog/unreleased/2026-09-30-backward-compatibility.md b/changelog/unreleased/2026-09-30-backward-compatibility.mdnew file mode 100644index 00000000..9cfaf333--- /dev/null+++ b/changelog/unreleased/2026-09-30-backward-compatibility.md@@ -0,0 +1,27 @@+# Backward compatibility++- **Date:** 2026-09-30+- **Type:** process+- **Scope:** `server`, `cli`, `web`, `model-catalog`+- **PR:** [#914](https://github.com/Prism-Shadow/penguin-harness/pull/914)+- **Breaking:** yes — a models PUT, or `penguin config model add`, that adds a model which is not one of the group's presets to any built-in group but custom and vLLM is refused (`400 model_not_addable` / exit code 1); entries already stored keep working and are never rewritten++[中文版](2026-09-30-backward-compatibility.zh.md)++[The models page lines up with the model picker](2026-09-30-models-page-refresh.md) takes the add-model entry point away from every built-in group but custom and vLLM, and the server and the CLI refuse the same additions. One thing outlives the release: the models users already added to those groups.++## The old shape: a hand-added model in a gateway group++Up to this release the gateway groups — TokenDance, OpenRouter, Fireworks AI, SiliconFlow, OpenCode Go, the two Qwen groups, ModelScope — took models added by hand, from the models page, the API and `penguin config model add`. A `.project_config.toml` may therefore hold a `[[models]]` entry in one of those groups whose `(provider, model_id)` pair is not in the built-in catalog. Such an entry works: it carries the gateway's endpoint and protocol like the presets beside it.++Chosen: **keep it, as it is, with no migration.** The refusal applies only to an entry a request introduces. One already stored under the same `(provider, model_id)` key passes through untouched, and so does a rename inside its own group, whose `renamedFrom` names a stored row of that group. A move into such a group from another one is judged as a new entry, because that is the act of adding it there. The same holds for a first-party vendor group, where a routable id that is not a preset used to be accepted.++**A user is not required to do anything.** The entry stays in its group, keeps working, and can be edited, renamed within the group or deleted from the models page. Models to add from now on go into custom or a group of the user's own.++## Nothing is scheduled for removal++This is a validation rule rather than a shim: there is no second code path reading an old format, and nothing here expires. A preset the Project deleted may always be added back to its own group, which is what "Sync presets" does.++## Compatibility++Upgrading asks nothing of anyone. Configurations written before this release load and save as they did. What changes is what may be written from here on: a models PUT introducing a model that is not a preset into any built-in group but custom and vLLM answers `400 model_not_addable`, and `penguin config model add` refuses with exit code 1. Scripts that add such a model move it to `--provider custom` or a group name of their own, with `--client-type` and `--base-url`.diff --git a/changelog/unreleased/2026-09-30-backward-compatibility.zh.md b/changelog/unreleased/2026-09-30-backward-compatibility.zh.mdnew file mode 100644index 00000000..c08daf27--- /dev/null+++ b/changelog/unreleased/2026-09-30-backward-compatibility.zh.md@@ -0,0 +1,27 @@+# 向后兼容++- **Date:** 2026-09-30+- **Type:** process+- **Scope:** `server`, `cli`, `web`, `model-catalog`+- **PR:** [#914](https://github.com/Prism-Shadow/penguin-harness/pull/914)+- **Breaking:** yes — 模型表 PUT 与 `penguin config model add` 若要往 custom、vLLM 以外的内置分组新增不属于该分组预置的模型,一律拒绝(`400 model_not_addable` / 退出码 1);已存的条目照常工作,也从不被改写++[English](2026-09-30-backward-compatibility.md)++[模型配置页对齐模型选择器](2026-09-30-models-page-refresh.zh.md)收回了 custom、vLLM 以外所有内置分组的「添加模型」入口,服务端和 CLI 也拒绝同样的新增。跨版本存活的只有一样:用户已经加进这些分组的模型。++## 旧形态:网关分组里手动添加的模型++在这一版之前,网关分组——TokenDance、OpenRouter、Fireworks AI、SiliconFlow、OpenCode Go、两个 Qwen 分组、ModelScope——都接受手动添加模型,无论来自模型配置页、API 还是 `penguin config model add`。因此 `.project_config.toml` 里可能有这些分组的 `[[models]]` 条目,其 `(provider, model_id)` 不在内置目录里。这样的条目是能用的:它和旁边的预置一样带着网关的端点和协议。++选择:**原样保留,不做迁移。** 拒绝只针对本次请求新引入的条目。同一 `(provider, model_id)` 键下已存的条目原样通过;在本组内改名也通过,此时 `renamedFrom` 指向本组一条已存的行。从别的分组移入则视同新增,因为那正是把它加进这个分组的动作。一方厂商分组同理:此前可路由、但不属于预置的 id 也曾被接受。++**用户无需做任何事。** 条目留在原分组,照常可用,也可以在模型配置页编辑、在组内改名或删除。以后要添加的模型放进 custom 或自己创建的分组。++## 没有计划移除的内容++这是一条校验规则而不是兼容垫片:没有读取旧格式的第二条代码路径,也没有会到期的东西。Project 删掉的预置模型随时可以加回它自己的分组,「同步预置」做的就是这件事。++## 兼容性++升级无需任何操作。这一版之前写下的配置照常加载和保存。变化的是今后能写入什么:往 custom、vLLM 以外的内置分组新增不属于预置的模型,模型表 PUT 返回 `400 model_not_addable`,`penguin config model add` 以退出码 1 拒绝。添加这类模型的脚本改用 `--provider custom` 或自己的分组名,并附上 `--client-type` 与 `--base-url`。diff --git a/changelog/unreleased/2026-09-30-models-page-refresh.md b/changelog/unreleased/2026-09-30-models-page-refresh.mdnew file mode 100644index 00000000..20bbe3c7--- /dev/null+++ b/changelog/unreleased/2026-09-30-models-page-refresh.md@@ -0,0 +1,41 @@+# The models page: group headers, Connect and account balances++- **Date:** 2026-09-30+- **Type:** feature+- **Scope:** `web`, `server`, `cli`, `model-catalog`, `docs`+- **PR:** [#914](https://github.com/Prism-Shadow/penguin-harness/pull/914)++[中文版](2026-09-30-models-page-refresh.zh.md)++The models page's group headers were reworked: a group's key is managed from its header; the three groups whose key comes from an authorization flow connect rather than "authorize a key"; the two vendors that publish an account balance show it; and a banner above the groups offers TokenDance's wallet. The model cards are unchanged.++## Group headers++- The collapse chevron follows the group's name and model count instead of standing at the header's far edge. The count is a bare number, as on the picker's rail.+- Every item on the right shares one box: the same height, the same inset and one gap between them, with the divider as tall as the buttons, so the header reads on one centre line.+- The actions on the right stand in a fixed order, decided in one place (`groupHeaderActions`, `group-header.ts`): balance, a divider, **Connect** with its status, **Sync** (a connected Penguin Go), **Enter key**, the speed test, **Add model**, **Delete group**. The divider is drawn only where something follows the balance. A member sees the balance and the connection status and none of the rest.+- "Set key" became **Enter key** (填写密钥). It and **Connect** are flat buttons, a glyph and a label like the header's other actions, which keep the glyph and drop the label on a narrow header. **Enter key** still writes one key to every row of the group, and custom still has none.+- The provider's key console link left the header. It stays in the **Enter key** dialog and in **Model settings**.+- The speed test is one icon that starts a run, after the same confirmation, and stops it. A stop lets the probe in flight finish and starts no other; results already measured stay.++## Connect++- TokenDance, Penguin Go and ModelScope's "Authorize key" became **Connect** (连接, a chain-link glyph), with **Not connected** / **Connected** (未连接 / 连接成功) before it. Connected means the group stores a key, whichever way it got there. Once connected, the button reads **Reconnect**. The flows themselves were not changed; the status flips when the dialog is closed and the table reloads.+- A banner above every group, for the owner while the TokenDance group has models and no key, offers TokenDance's connect flow. A slow highlight sweeps across the word TokenDance alone every 6 s, a gradient clipped to the letters; the rest of the banner stands still, and so does the word under `prefers-reduced-motion`. **×** hides it in the browser (`penguin.tokenDanceBannerDismissed`).++## Balances++- `ModelProviderInfo.balance` declares a vendor's account-balance endpoint and the reader for its reply: TokenDance (`https://tokendance.space/portal/api/v1/user/balance`, `balance.balance` in micro-yuan) and DeepSeek (`https://api.deepseek.com/user/balance`, one entry per currency).+- `GET /api/projects/:projectId/models/balance?provider=<group>[&force=1]`, for any Project member, reads it with the group's stored key or, without one, the environment key a Session on the group's rows would use, provided that variable's official endpoint is the balance endpoint's host: DeepSeek's `DEEPSEEK_API_KEY` qualifies, while TokenDance, a gateway, gets none. The key never leaves the server. It uses a 5 s limit and the outbound proxy settings, and caches for 60 s per Project and group for as long as the key is the same (`force=1` skips the cache). It answers `{ ok: true, provider, amount, currency, available?, others?, fetchedAt }`, or `{ ok: false, error, status?, message }` with `error` one of `unsupported`, `no_key` and `upstream_failed`; the vendor's own text is not relayed.+- The header shows the balance muted, in the display currency the cost center and the model prices use: converted at the app's fixed rate (1 USD = 7 CNY) and summed across the currencies an account holds, so ¥110 and $5 read `¥145`. Two icons stand before it, the pin (常驻) and the refresh (同步); the refresh icon's tooltip gives the vendor's own figures and the read time. A balance that cannot be read is a muted "—", with the reason in the refresh icon's tooltip (the shared tooltip speaks only for an element with no words of its own).+- The pin, the session list's group pin drawn filled while on, keeps one balance beside the user name at the bottom of the sidebar, in the same currency. It is stored per account in `ui_prefs.pinnedBalance`; pinning another replaces it. The pinned balance is read on page load and every five minutes after.++## Adding models++- Add model is offered on custom, vLLM and user-defined groups only (`ModelProviderInfo.addable`, `isAddableGroup`), and the model dialog's group list holds those groups plus the row's own. The server and `penguin config model add` refuse a new model that is no preset in any other built-in group (`400 model_not_addable`); rows already stored are kept. See [backward compatibility](2026-09-30-backward-compatibility.md).+- The "OpenRouter's popular models" example of **Create with AI** adds them as a group of the user's own.++## Docs++- The models, quickstart (desktop), configuration and CLI pages describe the new header, **Connect**, **Enter key**, the speed-test toggle, account balances and the built-in-models-only rule, in both languages.+- The `penguin-config` skill (plugin `agent-development` `2026.09.30.2`) states which groups take hand-added models, so an agent does not send `penguin config model add` into the refusal.diff --git a/changelog/unreleased/2026-09-30-models-page-refresh.zh.md b/changelog/unreleased/2026-09-30-models-page-refresh.zh.mdnew file mode 100644index 00000000..b6a98406--- /dev/null+++ b/changelog/unreleased/2026-09-30-models-page-refresh.zh.md@@ -0,0 +1,41 @@+# 模型配置页:分组标题栏、连接与账户余额++- **Date:** 2026-09-30+- **Type:** feature+- **Scope:** `web`, `server`, `cli`, `model-catalog`, `docs`+- **PR:** [#914](https://github.com/Prism-Shadow/penguin-harness/pull/914)++[English](2026-09-30-models-page-refresh.md)++模型配置页的分组标题栏重做:分组的 key 在分组标题栏统一管理;三个由授权流程取得 key 的分组从「自动获取密钥」改为「连接」;两个提供账户余额查询的厂商显示余额;所有分组上方加一条推荐 TokenDance 钱包的横幅。模型卡片不变。++## 分组标题栏++- 展开/收起的箭头紧跟在分组名和模型数后面,不再放在标题栏最右侧。模型数改为和选择器分组栏一样的纯数字。+- 右侧所有元素同高、同样的内边距、彼此同一间距,分隔线与按钮等高,整行落在同一条中线上。+- 右侧操作按固定顺序排列,由一处决定(`groupHeaderActions`,`group-header.ts`):余额、分隔线、**连接**及其状态、**同步**(已连接的 Penguin Go)、**填写密钥**、测速、**添加模型**、**删除分组**。余额后面还有内容时才画分隔线。成员只看到余额和连接状态。+- 「手动设置密钥」改为**填写密钥**。它和**连接**都是无底色的图标加文字按钮,与标题栏上其他操作一样,标题栏变窄时只留图标。**填写密钥**仍把同一把 key 写进分组里的每个模型,custom 分组仍然没有这个操作。+- 供应商密钥控制台的链接移出标题栏,只留在**填写密钥**弹窗和**模型配置**弹窗里。+- 测速是一个图标按钮,确认后开始,测速中再按即停止。停止时正在进行的那次探测照常完成,不再发起后续请求;已测出的结果保留。++## 连接++- TokenDance、Penguin Go 和 ModelScope 的「自动获取密钥」改为**连接**(链环图标),前面显示**未连接** / **连接成功**。连接成功指分组里存有 key,与 key 从哪条路径写入无关。连接成功后按钮显示**重新连接**。授权流程本身没有改动;关闭弹窗、重新加载模型表后状态随之翻转。+- 所有分组上方加一条横幅:对 owner 显示,条件是 TokenDance 分组有模型但没有 key,提供 TokenDance 的连接流程。每 6 秒一道缓慢的高光只扫过「TokenDance」这个词,渐变裁切在文字上;横幅其余部分静止,`prefers-reduced-motion` 下这个词也静止。**×** 在当前浏览器里隐藏它(`penguin.tokenDanceBannerDismissed`)。++## 余额++- `ModelProviderInfo.balance` 声明厂商的账户余额接口及其答复的读法:TokenDance(`https://tokendance.space/portal/api/v1/user/balance`,`balance.balance`,单位微元)与 DeepSeek(`https://api.deepseek.com/user/balance`,每种货币一项)。+- 新增 `GET /api/projects/:projectId/models/balance?provider=<分组>[&force=1]`,Project 成员均可调用:服务端用分组已存的 key 查询,没有已存的 key 时,用会话在该分组的模型上会用的环境变量,前提是该变量的官方端点就是余额接口所在的主机:DeepSeek 的 `DEEPSEEK_API_KEY` 符合,TokenDance 是网关,没有环境变量可用。key 不离开服务端;5 秒超时,走出网代理设置;按 Project × 分组缓存 60 秒,换了 key 即不命中(`force=1` 跳过缓存)。答复为 `{ ok: true, provider, amount, currency, available?, others?, fetchedAt }`,或 `{ ok: false, error, status?, message }`,`error` 为 `unsupported`、`no_key` 或 `upstream_failed`;厂商原文不回传。+- 标题栏以灰色小字显示余额,币种跟随成本中心和模型价格所用的显示币种:按应用的固定汇率(1 美元 = 7 元)换算,账户持有多种货币时合计,¥110 加 $5 显示为 `¥145`。余额前面是两个图标:常驻(图钉)和同步(刷新),刷新图标的悬停提示给出服务商的原始金额和查询时间。查不到时显示灰色「—」,原因在刷新图标的悬停提示里(共享提示只为没有文字的元素显示)。+- 图钉(即会话列表的分组图钉,常驻时画成实心)把一个余额常驻到侧栏底部的用户名旁,币种相同。常驻按账户记在 `ui_prefs.pinnedBalance`,常驻另一个即替换;常驻的余额在页面加载时查询一次,此后每五分钟一次。++## 添加模型++- **添加模型**只出现在 custom、vLLM 和自建分组(`ModelProviderInfo.addable`,`isAddableGroup`),模型配置弹窗的分组下拉只列这些分组和该行自己所在的分组。服务端与 `penguin config model add` 拒绝在其余内置分组新增不属于预置的模型(`400 model_not_addable`);已存的行保留。见[向后兼容](2026-09-30-backward-compatibility.zh.md)。+- **用 AI 创建**的「OpenRouter 热门模型」示例改为加成一个自建分组。++## 文档++- 模型、快速上手(桌面端)、配置与 CLI 文档按新的标题栏、**连接**、**填写密钥**、测速开关、账户余额和「只承载内置模型」规则更新,中英文同步。+- `penguin-config` 技能(`agent-development` 插件 `2026.09.30.2`)写明哪些分组可以手动添加模型,免得 Agent 用 `penguin config model add` 撞上拒绝。diff --git a/packages/cli/src/commands/config.ts b/packages/cli/src/commands/config.tsindex beb736a8..ac378508 100644--- a/packages/cli/src/commands/config.ts+++ b/packages/cli/src/commands/config.ts@@ -23,7 +23,8 @@* pins one, and otherwise openai-chat for custom / self-hosted groups / gateways, with the* gateway's endpoint base URL pre-filled); adding a NEW entry to a first-party vendor group* under a model id AgentHub cannot route is refused, since nothing there would carry a- * protocol for it. For `model default` / `model vision`, core+ * protocol for it, and so is adding one that is not a preset to any built-in group but custom+ * and vLLM. For `model default` / `model vision`, core* validation raises an error when the reference is not* found in models; `model remove` reports the same condition itself, since removal is* idempotent in core, and clears the default / vision pointers that named the removed entry.@@ -59,6 +60,7 @@ import {setDefaultModel,setVaultEntry,setVisionModel,+ unaddableModel,unroutableVendorModel,} from "@prismshadow/penguin-core";import { parseApprovalAnswer } from "../approval.js";@@ -201,6 +203,16 @@ export function registerConfigCommand(program: Command, t: Messages): void {process.exitCode = 1;return;}+ // The route's second rule, enforced here for the same reason: only custom, vLLM and+ // user-defined groups take models added by hand, and every other built-in group carries+ // its catalog presets. A preset may be added back; an entry already stored is left alone.+ if (!existed && unaddableModel(provider, modelId)) {+ process.stderr.write(+ `${t.error(t.modelNotAddable(formatModelRef(ref), pInfo?.label ?? provider))}\n`,+ );+ process.exitCode = 1;+ return;+ }// Only collect explicitly given price fields, letting addModel merge them with the existing pricing per-field.const pricing: Partial<ModelPricing> = {};if (opts.priceCacheRead !== undefined) pricing.cache_read = opts.priceCacheRead;diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.tsindex 6812ff64..90123ef2 100644--- a/packages/cli/src/i18n.ts+++ b/packages/cli/src/i18n.ts@@ -941,6 +941,8 @@ export interface Messages {modelNotConfigured(model: string): string;/** `model add` refused: a new entry in a first-party vendor group under a model id AgentHub cannot route. */modelNotRoutable(model: string): string;+ /** A new entry in a built-in group that takes no hand-added models (everything but custom and vLLM). */+ modelNotAddable(model: string, group: string): string;/** Follows modelRemoved when the removed entry was also the vision model. */visionModelCleared(): string;modelListTitle(): string;@@ -1899,6 +1901,10 @@ const en: Messages = {`Model ${model} cannot be routed: a vendor group carries built-in models only. ` +`Add it under a custom group (--provider custom) with --client-type and --base-url, ` +`or pass --client-type to pin the protocol this model speaks.`,+ modelNotAddable: (model, group) =>+ `Model ${model} cannot be added: the ${group} group carries its built-in models only. ` ++ `Add it under a custom group (--provider custom, or a group name of your own) ` ++ `with --client-type and --base-url.`,visionModelCleared: () => "It was also the vision model; that setting is now unset.",modelListTitle: () => "Configured models:",modelListEmpty: () => "No models configured yet. Add one with `penguin config model add`.",@@ -2774,6 +2780,9 @@ const zh: Messages = {`模型 ${model} 无法路由:厂商分组只承载内置模型。` +`请改用自定义分组(--provider custom)并附上 --client-type 与 --base-url,` +`或用 --client-type 指定该模型所用的协议。`,+ modelNotAddable: (model, group) =>+ `模型 ${model} 无法添加:${group} 分组只承载内置模型。` ++ `请改用自定义分组(--provider custom,或自己命名的分组)并附上 --client-type 与 --base-url。`,visionModelCleared: () => "它同时是视觉模型,该设置已一并清空。",modelListTitle: () => "已配置的模型:",modelListEmpty: () => "尚未配置任何模型。用 `penguin config model add` 添加。",diff --git a/packages/cli/test/config-model.test.ts b/packages/cli/test/config-model.test.tsindex 476f922e..2fa7f670 100644--- a/packages/cli/test/config-model.test.ts+++ b/packages/cli/test/config-model.test.ts@@ -175,7 +175,7 @@ describe("penguin config model add/list (--root plus provider / model_id storedexpect(list.out.split("\n").some((l) => /anthropic\s+claude-sonnet-4-6/.test(l))).toBe(true);});- it("client_type defaults by grouping semantics (PRN-021): custom / self-hosted / gateway get openai-chat unless the group pins another protocol, first-party providers get none", async () => {+ it("client_type defaults by grouping semantics (PRN-021): custom and self-built groups get openai-chat, a group that pins a protocol hands it over", async () => {// The custom group and self-hosted groups (--provider not a catalog value): default to client_type=openai.await runModel(["add",@@ -187,27 +187,14 @@ describe("penguin config model add/list (--root plus provider / model_id storedtmpRoot,]);await runModel(["add", "--model-id", "in-house-1", "--provider", "mylab", "--root", tmpRoot]);- // A non-catalog id under a first-party vendor group: client_type is not set (AgentHub- // auto-routes by upstream id). The id has to be one that routing places — the group- // carries nothing else that could name a protocol for it (see the refusal test below).+ // vLLM pins its adapter on every entry, the models a user serves included, and has no+ // endpoint to preset: the entry carries none until the user names their own server.await runModel(["add","--model-id",- "deepseek-v4-my-tune",+ "my-served-model","--provider",- "deepseek",- "--root",- tmpRoot,- ]);- // Gateway group: the gateway's endpoint base URL pre-filled, and the protocol the group- // pins — OpenRouter speaks the Responses API for every model it serves, so an id added by- // hand gets openai-responses rather than the openai-chat the other gateways default to.- await runModel([- "add",- "--model-id",- "acme/some-model",- "--provider",- "openrouter",+ "vllm","--root",tmpRoot,]);@@ -231,9 +218,8 @@ describe("penguin config model add/list (--root plus provider / model_id storedparsed.models.find((m) => m.provider === p && m.model_id === id)!;expect(by("custom", "my-openai-proxy").client_type).toBe("openai-chat");expect(by("mylab", "in-house-1").client_type).toBe("openai-chat");- expect(by("deepseek", "deepseek-v4-my-tune").client_type).toBeUndefined();- expect(by("openrouter", "acme/some-model").client_type).toBe("openai-responses");- expect(by("openrouter", "acme/some-model").base_url).toBe("https://openrouter.ai/api/v1");+ expect(by("vllm", "my-served-model").client_type).toBe("openai-chat-vllm-adapter");+ expect(by("vllm", "my-served-model").base_url).toBeUndefined();expect(by("mylab", "special-1").client_type).toBe("verbatim-type");});@@ -277,8 +263,9 @@ describe("penguin config model add/list (--root plus provider / model_id stored]);expect(custom.code).toBe(0);- // And inside a vendor group once the entry names its own protocol, which is what the two- // presets whose ids do not route rely on.+ // Naming its own protocol makes the id routable inside a vendor group, which is what the+ // two presets whose ids do not route rely on; but a model that is no preset is not added+ // there by hand at all.const pinned = await runModel(["add","--model-id",@@ -290,9 +277,63 @@ describe("penguin config model add/list (--root plus provider / model_id stored"--root",tmpRoot,]);- expect(pinned.code).toBe(0);- const entry = await stored("deepseek", "qwen/qwen3.8-flash-next");- expect(entry?.client_type).toBe("openai-chat");+ expect(pinned.code).toBe(1);+ expect(pinned.err).toContain("cannot be added");+ expect(await stored("deepseek", "qwen/qwen3.8-flash-next")).toBeUndefined();+ });++ it("refuses a NEW entry that is no preset in any built-in group but custom and vLLM, and takes a preset back", async () => {+ // The models PUT refuses the same rows; this command writes the file without the server,+ // so it enforces the rule again rather than leave a second door open.+ const file = projectConfigPath(tmpRoot, DEFAULT_PROJECT_ID);+ const stored = async (p: string, id: string) => {+ const parsed = parseToml(await fs.readFile(file, "utf8")) as {+ models: Array<Record<string, unknown>>;+ };+ return parsed.models.find((m) => m.provider === p && m.model_id === id);+ };+ await runModel(["add", "--model-id", "seed", "--provider", "custom", "--root", tmpRoot]);+ // Two gateways and a vendor group, with ids each one's client would happily serve.+ for (const [provider, id] of [+ ["openrouter", "acme/some-model"],+ ["tokendance", "acme/some-model"],+ ["deepseek", "deepseek-v4-my-tune"],+ ] as const) {+ const refused = await runModel([+ "add",+ "--model-id",+ id,+ "--provider",+ provider,+ "--root",+ tmpRoot,+ ]);+ expect(refused.code, provider).toBe(1);+ expect(refused.err, provider).toContain("cannot be added");+ expect(refused.err, provider).toContain("custom group");+ expect(await stored(provider, id), provider).toBeUndefined();+ }+ // A preset the Project removed is the group's own model, and may come back.+ await runModel([+ "remove",+ "--model-id",+ "deepseek-v4-pro",+ "--provider",+ "deepseek",+ "--root",+ tmpRoot,+ ]);+ const back = await runModel([+ "add",+ "--model-id",+ "deepseek-v4-pro",+ "--provider",+ "deepseek",+ "--root",+ tmpRoot,+ ]);+ expect(back.code).toBe(0);+ expect(await stored("deepseek", "deepseek-v4-pro")).toBeDefined();});it("an entry already stored in a vendor group still updates, however its id routes", async () => {@@ -302,7 +343,8 @@ describe("penguin config model add/list (--root plus provider / model_id storedawait runModel(["add", "--model-id", "seed", "--provider", "custom", "--root", tmpRoot]);await fs.appendFile(file,- '\n[[models]]\nprovider = "deepseek"\nmodel_id = "legacy-fine-tune"\n',+ '\n[[models]]\nprovider = "deepseek"\nmodel_id = "legacy-fine-tune"\n' ++ '\n[[models]]\nprovider = "openrouter"\nmodel_id = "acme/legacy-pick"\n',"utf8",);@@ -323,6 +365,19 @@ describe("penguin config model add/list (--root plus provider / model_id stored};const entry = parsed.models.find((m) => m.model_id === "legacy-fine-tune");expect(entry?.context_window).toBe(65536);+ // A row added to a gateway before gateways stopped taking them updates the same way.+ const gateway = await runModel([+ "add",+ "--model-id",+ "acme/legacy-pick",+ "--provider",+ "openrouter",+ "--api-key",+ "sk-or-legacy",+ "--root",+ tmpRoot,+ ]);+ expect(gateway.code).toBe(0);});it("a new entry naming a catalog row inherits that row's pinned client_type and base_url; --client-type still wins", async () => {@@ -348,10 +403,9 @@ describe("penguin config model add/list (--root plus provider / model_id stored"--root",tmpRoot,]);- // The same id under a group that does not sell it has no catalog row, so the group rule- // still decides: OpenRouter gives it the openai-responses its group pins and its own- // endpoint, not DeepSeek's client and vendor endpoint.- await runModel([+ // The same id under a group that does not sell it is no preset there, and a gateway takes+ // no hand-added models: refused, and nothing is written.+ const elsewhere = await runModel(["add","--model-id","deepseek-flash",@@ -360,6 +414,7 @@ describe("penguin config model add/list (--root plus provider / model_id stored"--root",tmpRoot,]);+ expect(elsewhere.code).toBe(1);// An explicit --client-type outranks the inherited pin, and so does --base-url.await runModel(["remove",@@ -391,8 +446,7 @@ describe("penguin config model add/list (--root plus provider / model_id storedparsed.models.find((m) => m.provider === p && m.model_id === id)!;expect(by("deepseek", "deepseek-flash").client_type).toBe("deepseek-v4");expect(by("deepseek", "deepseek-flash").base_url).toBe("https://api.deepseek.com");- expect(by("openrouter", "deepseek-flash").client_type).toBe("openai-responses");- expect(by("openrouter", "deepseek-flash").base_url).toBe("https://openrouter.ai/api/v1");+ expect(by("openrouter", "deepseek-flash")).toBeUndefined();expect(by("minimax", "MiniMax-M3").client_type).toBe("openai-chat");expect(by("minimax", "MiniMax-M3").base_url).toBe("https://proxy.example/v1");});diff --git a/packages/core/src/state/model-catalog.ts b/packages/core/src/state/model-catalog.tsindex 4a29d42f..a39a98bd 100644--- a/packages/core/src/state/model-catalog.ts+++ b/packages/core/src/state/model-catalog.ts@@ -120,6 +120,24 @@ export interface ModelProviderBridgeAuth {flow: "penguin-go" | "modelscope";}+/**+ * An account-balance endpoint the vendor publishes, called with the group's own API key as a+ * Bearer token. The server makes that call (the key never reaches the browser); the endpoint+ * is the vendor's, like the OAuth one above, so it can live in this browser-bundled file.+ */+export interface ModelProviderBalance {+ /** GET endpoint answering the balance of the account the key belongs to. */+ url: string;+ /**+ * How to read the answer, one reader per published response shape:+ * - `tokendance`: `{ balance: { credits, credits_used, balance } }`, integers in micro-yuan+ * (1 CNY = 1,000,000);+ * - `deepseek`: `{ is_available, balance_infos: [{ currency, total_balance, … }] }`, one entry+ * per currency the account holds.+ */+ format: "tokendance" | "deepseek";+}+export interface ModelProviderInfo {id: string;/** Display name (brand name, shared by Chinese and English UI). */@@ -133,7 +151,7 @@ export interface ModelProviderInfo {envKey: string;/** base URL env var name. */envBaseUrlKey: string;- /** Console URL for obtaining an API key (frontend links this in the group header); none for custom. */+ /** Console URL for obtaining an API key (frontend links it beside the API key field of the group key dialog and the model dialog); none for custom. */apiKeyUrl?: string;/** Vendor's model list / docs page URL (frontend's "add model" dialog links this as "get model id"); none for custom. */modelsUrl?: string;@@ -155,6 +173,18 @@ export interface ModelProviderInfo {* group in the Web App.*/bridgeAuth?: ModelProviderBridgeAuth;+ /**+ * The vendor's account-balance endpoint (see ModelProviderBalance); absent for every group+ * whose vendor publishes none. Declaring it is what puts the balance in the group's header.+ */+ balance?: ModelProviderBalance;+ /**+ * The group takes models the user adds by hand: `custom` and vLLM, whose rows point at an+ * endpoint the catalog cannot know. Every other built-in group carries its catalog presets+ * and the rows it already stores, and nothing else. Read it through isAddableGroup, which+ * also answers for user-defined groups.+ */+ addable?: boolean;/*** The AgentHub protocol EVERY entry in this group speaks, models the user adds included.*@@ -307,6 +337,11 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [exchangeUrl: "https://tokendance.space/portal/api/v1/auth/keys",keyName: "PenguinHarness",},+ // https://tokendance.space/docs/open-api (the account's wallet, in micro-yuan)+ balance: {+ url: "https://tokendance.space/portal/api/v1/user/balance",+ format: "tokendance",+ },},{id: PENGUIN_GO_PROVIDER_ID,@@ -340,6 +375,8 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [envBaseUrlKey: "DEEPSEEK_BASE_URL",apiKeyUrl: "https://platform.deepseek.com/api_keys",modelsUrl: "https://api-docs.deepseek.com/quick_start/pricing",+ // https://api-docs.deepseek.com/api/get-user-balance+ balance: { url: `${DEEPSEEK_BASE_URL}/user/balance`, format: "deepseek" },},{id: "openrouter",@@ -472,8 +509,16 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [envBaseUrlKey: "OPENAI_BASE_URL",modelsUrl: "https://recipes.vllm.ai/",clientType: VLLM_CLIENT_TYPE,+ // The served ids are the user's own, so this group keeps taking models added by hand.+ addable: true,+ },+ {+ id: "custom",+ label: "Custom",+ envKey: "OPENAI_API_KEY",+ envBaseUrlKey: "OPENAI_BASE_URL",+ addable: true,},- { id: "custom", label: "Custom", envKey: "OPENAI_API_KEY", envBaseUrlKey: "OPENAI_BASE_URL" },];/** Three-bucket price literal (unit fixed to usd_per_mtok). */@@ -2889,11 +2934,12 @@ export function providerClientType(providerId: string): string | undefined {* id alone. That makes the group's contents a closed set — the ids this catalog ships, plus* the few whose preset pins a protocol because their own id would not route — and an id* outside it cannot be started at all, whatever else is configured on the entry. Every- * surface that has to answer "may a model be added here, and is this one routable?" reads- * the group's shape through this one predicate rather than re-deriving it: the models page's- * group actions and its config dialog, the models PUT, and the CLI's `config model add`.+ * surface that has to answer "is this one routable?" reads the group's shape through this one+ * predicate rather than re-deriving it: the models page's cards and its config dialog, the+ * models PUT, and the CLI's `config model add`. Whether a model may be added to the group at+ * all is a separate, wider rule: isAddableGroup.*- * Every other group answers the protocol question by itself and therefore takes any id the+ * Every other group answers the protocol question by itself and therefore routes any id the* endpoint serves: `custom` and user-defined groups detect or pick it, a gateway inherits its* preset's, and a group-level pin (OpenRouter, vLLM) hands it to every entry.*/@@ -2928,6 +2974,28 @@ export function unroutableVendorModel(return resolveModelEnv(id, pinned === "" ? undefined : pinned) === undefined;}+/**+ * Whether models may be added to this group by hand: `custom`, vLLM (ModelProviderInfo.addable)+ * and every user-defined group, i.e. an id this catalog does not know. Every other built-in+ * group — the first-party vendors and the gateways — carries its catalog presets and the rows+ * it already stores: the models page offers no add-model entry point there, and the models PUT+ * and the CLI's `config model add` refuse a new row that is not a preset (unaddableModel).+ */+export function isAddableGroup(providerId: string): boolean {+ const info = providerInfo(providerId);+ return info === undefined || info.addable === true;+}++/**+ * Whether writing this pair as a NEW row of its group would add a model by hand where the group+ * takes none: a group isAddableGroup refuses, and a `(provider, model_id)` pair that is not one+ * of the catalog's rows for it. A preset passes, so "Sync presets" can put a deleted one back;+ * a row the table already stores is not a new one, and the callers never ask about it.+ */+export function unaddableModel(provider: string, modelId: string): boolean {+ return !isAddableGroup(provider) && catalogEntryFor(provider, modelId.trim()) === undefined;+}+/** Env var fallback for a single model (the var names AgentHub's client actually reads when api_key / base_url is blank). */export interface ModelEnvInfo {envKey: string;diff --git a/packages/core/test/model-catalog.test.ts b/packages/core/test/model-catalog.test.tsindex ec3f0cae..8d0af8e3 100644--- a/packages/core/test/model-catalog.test.ts+++ b/packages/core/test/model-catalog.test.ts@@ -23,6 +23,7 @@ import {providerClientType,providerInfo,fastModeProtocol,+ isAddableGroup,isVendorGroup,resolveModelEnv,resolveProviderModelEnv,@@ -34,6 +35,7 @@ import {providerEnvFallbackKey,resolveModelCredential,sameEndpoint,+ unaddableModel,unroutableVendorModel,} from "../src/state/index.js";@@ -154,6 +156,25 @@ describe("model-catalog", () => {}});+ it("exactly TokenDance and DeepSeek publish a balance endpoint, on the host their keys already go to", () => {+ // The descriptor is what puts a balance in a group's header, so the Web App never names a+ // group; each one names the reader for its vendor's response shape.+ const withBalance = MODEL_PROVIDERS.filter((p) => p.balance !== undefined).map((p) => [+ p.id,+ p.balance!.format,+ ]);+ expect(withBalance).toEqual([+ ["tokendance", "tokendance"],+ ["deepseek", "deepseek"],+ ]);+ // The server sends the group's stored key to this URL, so it is the vendor's own https+ // endpoint and nothing else.+ expect(providerInfo("tokendance")!.balance!.url).toBe(+ "https://tokendance.space/portal/api/v1/user/balance",+ );+ expect(providerInfo("deepseek")!.balance!.url).toBe("https://api.deepseek.com/user/balance");+ });+it("prebuilds Penguin Go with fixed relay routes and list prices, leaving promotions to the platform", () => {const penguinGoModels = MODEL_CATALOG.filter((model) => model.provider === "penguin-go");// The DeepSeek rows follow DeepSeek's own lineup: V4.1 Flash and V4 Pro 0813. The two@@ -1604,6 +1625,38 @@ describe("resolveModelEnv (PRN-021: env fallback resolved by AgentHub routing ruexpect(isVendorGroup("my-own-group")).toBe(false);});+ it("isAddableGroup: custom, vLLM and user-defined groups take hand-added models, no other built-in group does", () => {+ for (const id of ["custom", "vllm", "my-own-group"]) {+ expect(isAddableGroup(id), id).toBe(true);+ }+ // Every first-party vendor and every gateway, the relays included.+ const closed = MODEL_PROVIDERS.map((p) => p.id).filter(+ (id) => id !== "custom" && id !== "vllm",+ );+ expect(closed).toContain("openrouter");+ expect(closed).toContain("penguin-go");+ expect(closed).toContain("deepseek");+ for (const id of closed) {+ expect(isAddableGroup(id), id).toBe(false);+ }+ });++ it("unaddableModel: a closed group still takes its own presets, an addable group takes anything", () => {+ expect(unaddableModel("openrouter", "someone/new-model")).toBe(true);+ // Routable is not enough: the DeepSeek client would place this id, but it is no preset.+ expect(unaddableModel("deepseek", "deepseek-v4-pro-next")).toBe(true);+ // The pair is the key: DeepSeek's own id is not one of OpenRouter's presets.+ expect(unaddableModel("openrouter", "deepseek-flash")).toBe(true);+ // Every catalog row may be written back into its own group — that is what "Sync presets"+ // does for a row the Project deleted.+ for (const m of MODEL_CATALOG) {+ expect(unaddableModel(m.provider, m.modelId), `${m.provider}/${m.modelId}`).toBe(false);+ }+ for (const id of ["custom", "vllm", "my-own-group"]) {+ expect(unaddableModel(id, "someone/new-model"), id).toBe(false);+ }+ });+it("modelHomepageUrl: gateway per-model pages, vendor docs fallback, none for custom groups", () => {// Gateway URL patterns work for user-added ids in those groups too (not catalog-gated).expect(modelHomepageUrl("openrouter", "anthropic/claude-fable-5")).toBe(diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.mdindex 53c576c8..36fba6ff 100644--- a/packages/docs/content/cli.en.md+++ b/packages/docs/content/cli.en.md@@ -566,7 +566,8 @@ penguin config model add --provider deepseek --model-id deepseek-v4-pro --api-ke| `--set-default` | Also sets the entry as the Project's default model. | — |- The CLI never derives `--provider` from the model id. Gateways resell vendor models under their upstream ids, so a guessed group could write the credential onto another vendor's endpoint. Use `custom` for any endpoint outside the built-in groups.-- For a new entry, `--client-type` and `--base-url` default to what the built-in catalog sets for that exact `(provider, model_id)` pair. Without a catalog row, the group decides: a group that pins a protocol uses it; `custom`, user-defined and gateway groups get `openai-chat`, with a gateway's endpoint filled in as the base URL; and first-party vendor groups leave both unset. Updating an existing entry changes them only when you pass the flags.+- For a new entry, `--client-type` and `--base-url` default to what the built-in catalog sets for that exact `(provider, model_id)` pair. Without a catalog row, the group decides: a group that pins a protocol uses it (`vllm`), and `custom` and user-defined groups get `openai-chat`. Updating an existing entry changes them only when you pass the flags.+- Only `custom`, `vllm` and user-defined groups take models added by hand. In every other built-in group a new entry must be one of that group's catalog rows; anything else is refused with "cannot be added", as the Models page and its API refuse it. Entries a group already holds update as usual.- Turning on `--fast-mode` for a model whose AgentHub client rejects the parameter still writes the entry, but prints a warning on stderr.### model default / model vision / model list / model removediff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.mdindex e8a45ba9..b8eba5df 100644--- a/packages/docs/content/cli.zh.md+++ b/packages/docs/content/cli.zh.md@@ -566,7 +566,8 @@ penguin config model add --provider deepseek --model-id deepseek-v4-pro --api-ke| `--set-default` | 同时把这条条目设为 Project 的默认模型。 | — |- CLI 绝不会从模型 id 推断 `--provider`。网关会按上游模型 id 转售厂商模型,靠猜测分组可能把凭证写到另一家厂商的端点上。内置分组之外的端点一律用 `custom`。-- 新建条目时,`--client-type` 和 `--base-url` 默认取内置模型目录为对应 `(provider, model_id)` 组合设置的值。模型目录里没有这一条时由分组决定:指定了协议的分组就用它指定的协议;`custom`、用户自定义和网关分组用 `openai-chat`,网关分组的端点会自动填成 base URL;第一方厂商分组则两项都不设置。更新已有条目时,只有显式传入这两个选项才会改动。+- 新建条目时,`--client-type` 和 `--base-url` 默认取内置模型目录为对应 `(provider, model_id)` 组合设置的值。模型目录里没有这一条时由分组决定:指定了协议的分组就用它指定的协议(`vllm`),`custom` 和用户自定义分组用 `openai-chat`。更新已有条目时,只有显式传入这两个选项才会改动。+- 只有 `custom`、`vllm` 和用户自定义分组可以手动添加模型。其余内置分组里,新条目必须是该分组在模型目录里的条目,否则以「无法添加」拒绝,与模型库页面及其 API 的规则一致。分组里已有的条目照常更新。- 如果模型的 AgentHub 客户端不接受这个参数,开启 `--fast-mode` 仍会写入条目,但会在 stderr 上打印警告。### model default / model vision / model list / model removediff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.mdindex 0ce73c51..6fb4b223 100644--- a/packages/docs/content/configuration.en.md+++ b/packages/docs/content/configuration.en.md@@ -31,8 +31,8 @@ Notes:- `PENGUIN_TRUST_PROXY`: set it behind a reverse proxy that terminates TLS and sets or strips the header itself. Session cookies are then marked `Secure`, and the hot-update network gate sees HTTPS.- `PENGUIN_SEED_ADMIN_PASSWORD`: without it, the seed generates a random password that is hashed and discarded unseen, and you claim the account through the first-login link.-- `PENGUIN_GO_ORIGIN`: server configuration, not an endpoint the browser can name. It must be a bare HTTPS origin; plain HTTP is accepted only for `localhost`, `127.0.0.1` and `[::1]`, for integration environments. A path, credentials, a query string or a fragment is rejected at startup. See [Authorize a new API key](/models#authorize-a-new-api-key).-- `MODELSCOPE_BRIDGE_URL`: server configuration like `PENGUIN_GO_ORIGIN`, not an endpoint the browser can name. It must be an HTTPS address with no credentials, query string or fragment. Unlike `PENGUIN_GO_ORIGIN`, a path prefix **is** allowed, because the production bridge lives under `https://go.penguin.ooo/modelscope`. See [Authorize a new API key](/models#authorize-a-new-api-key).+- `PENGUIN_GO_ORIGIN`: server configuration, not an endpoint the browser can name. It must be a bare HTTPS origin; plain HTTP is accepted only for `localhost`, `127.0.0.1` and `[::1]`, for integration environments. A path, credentials, a query string or a fragment is rejected at startup. See [Connect an account](/models#connect-an-account).+- `MODELSCOPE_BRIDGE_URL`: server configuration like `PENGUIN_GO_ORIGIN`, not an endpoint the browser can name. It must be an HTTPS address with no credentials, query string or fragment. Unlike `PENGUIN_GO_ORIGIN`, a path prefix **is** allowed, because the production bridge lives under `https://go.penguin.ooo/modelscope`. See [Connect an account](/models#connect-an-account).- `PENGUIN_UPDATE_CHECK`: `off` turns off the automatic release check, nothing else. Model requests, an enabled remote-control connection, provider key authorization and the proxy test still reach the network.- `PENGUIN_NO_LOGIN_SHELL_ENV`: without it, the import fills only variables the launch left unset. See [Desktop quickstart](/quickstart-desktop).- `PENGUIN_CLI_ENTRY`: when the server was started from a source checkout, it falls back to that checkout's `packages/cli/dist/penguin.js`.diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.mdindex d4b6aadf..2d51b3f9 100644--- a/packages/docs/content/configuration.zh.md+++ b/packages/docs/content/configuration.zh.md@@ -31,8 +31,8 @@ CLI 和服务器启动时会从工作目录加载 `.env` 文件。- `PENGUIN_TRUST_PROXY`:只在反向代理终结 TLS、并由代理自己设置或清除这个请求头时启用。启用后,会话 Cookie 会带上 `Secure` 标记,热更新的网络检查也能识别出 HTTPS。- `PENGUIN_SEED_ADMIN_PASSWORD`:不设置时,预置管理员时会生成一个随机密码,哈希后立即丢弃,没有人见过;账号通过首次登录链接认领。-- `PENGUIN_GO_ORIGIN`:它是服务端配置,不接受浏览器指定的端点。取值必须是不带路径的 HTTPS 源;只有 `localhost`、`127.0.0.1` 和 `[::1]` 这类集成环境可以用明文 HTTP。带路径、凭据、查询参数或 fragment 的取值会在启动时被拒绝。见[授权获取新 API key](/models#授权获取新-api-key)。-- `MODELSCOPE_BRIDGE_URL`:与 `PENGUIN_GO_ORIGIN` 一样是服务端配置,不接受浏览器指定的端点。它必须是不带凭据、查询参数或 fragment 的 HTTPS 地址。不同之处是**它允许带路径前缀**,因为生产环境的中转层就挂在 `https://go.penguin.ooo/modelscope` 下。见[授权获取新 API key](/models#授权获取新-api-key)。+- `PENGUIN_GO_ORIGIN`:它是服务端配置,不接受浏览器指定的端点。取值必须是不带路径的 HTTPS 源;只有 `localhost`、`127.0.0.1` 和 `[::1]` 这类集成环境可以用明文 HTTP。带路径、凭据、查询参数或 fragment 的取值会在启动时被拒绝。见[连接账户](/models#连接账户)。+- `MODELSCOPE_BRIDGE_URL`:与 `PENGUIN_GO_ORIGIN` 一样是服务端配置,不接受浏览器指定的端点。它必须是不带凭据、查询参数或 fragment 的 HTTPS 地址。不同之处是**它允许带路径前缀**,因为生产环境的中转层就挂在 `https://go.penguin.ooo/modelscope` 下。见[连接账户](/models#连接账户)。- `PENGUIN_UPDATE_CHECK`:设为 `off` 只关闭自动的版本检查,不影响其他对外请求:模型请求、已启用的远程控制连接、Key 授权和代理测试照常联网。- `PENGUIN_NO_LOGIN_SHELL_ENV`:不设置时,导入只填补启动过程没有设置的变量。见[桌面应用快速开始](/quickstart-desktop)。- `PENGUIN_CLI_ENTRY`:服务器从源码检出启动时,会回退到检出目录中的 `packages/cli/dist/penguin.js`。diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.mdindex e5ba8335..4ecc306e 100644--- a/packages/docs/content/models.en.md+++ b/packages/docs/content/models.en.md@@ -34,9 +34,19 @@ Each model card shows the model's display name, tags, context window, prices, kePrices are shown per million Tokens, in the order cache read / cache write / output. The currency is the one chosen under **Currency** in the settings: **USD $** or **CNY ¥**, converted at a fixed rate of 7.-Select a card to open **Model settings**. Links next to a group open the provider's key console (**Manage keys**). The model dialog links to the provider's model list (**Get model IDs**) and to the model's own page (**Model page**).+Select a card to open **Model settings**. It links to the provider's model list (**Get model IDs**), to the model's own page (**Model page**) and, like the **Enter key** dialog, to the provider's key console (**Manage keys**).-Only the Project owner can change models and credentials. Members can search, open and close groups, reorder them in their own browser, and open **Model settings** read-only.+A group's header shows the provider's logo, the group's name, its model count and an arrow that turns when the group opens. On the right it holds, from left to right:++- the group's balance, for TokenDance and DeepSeek once the group has a key, with a pin and a refresh icon before it and a divider after it; see [Account balances](#account-balances);+- whether the group is connected, and **Connect**, for TokenDance, Penguin Go and ModelScope; see [Connect an account](#connect-an-account);+- **Enter key**, on every group but **Custom**; see [Set API keys](#set-api-keys);+- the speed test; see [Measure speed](#measure-speed);+- **Add model**, on **Custom**, **vLLM** and groups you created; see [Add a model](#add-a-model).++While the TokenDance group has no key, a banner above the groups offers to connect your TokenDance wallet, so the models there need no key set by hand. Its **Connect** runs the same flow as the group's. Select × to hide the banner in this browser.++Only the Project owner can change models and credentials. Members can search, open and close groups, reorder them in their own browser, see balances and connection status, and open **Model settings** read-only.## Add a model group@@ -84,27 +94,37 @@ All of the group's models and their API keys are removed. Built-in groups cannot## Add a model+**Add model** is on the headers of **Custom**, **vLLM** and the groups you created. The other built-in groups — the vendors and the gateways — carry their built-in models only; see [Built-in models only](#built-in-models-only).+1. On the group's header, select **Add model**.-2. In **Model ID**, enter the model id exactly as the provider's API expects it, for example `gpt-5.5`. **Get model IDs** opens the provider's model list.+2. In **Model ID**, enter the model id exactly as the provider's API expects it, for example `qwen3-32b`. **Get model IDs** opens the provider's model list.3. Optional: in **Display name**, enter a display name. An empty display name shows the model id.4. Fill in the credentials and endpoint:- - **API key**: in a vendor group, leave it empty to use the provider's environment variable; the field names the variable when it is set on the server. In a gateway group, in **Custom** and in groups you created, the key is required — no environment variable is used for an endpoint that is not the vendor's own.- - **Custom base URL**: required in **Custom** and in groups you created. In gateway groups it is filled in for you.+ - **API key**: required — these groups point at endpoints that are not a vendor's own, and no environment variable is used for such an endpoint.+ - **Custom base URL**: required. Enter your server's or gateway's endpoint.5. Optional: fill in the limits and prices:- **Context window**: the model's context window in Tokens. For a model that is not in the built-in catalog, an empty field saves as 1000000.- **Max output tokens**: the most output Tokens per request. Leave it empty to use the agent's setting; lower it for models with a small context.- **Cache read price**, **Cache write price**, and **Output price**: per million Tokens, in the display currency; they are stored in USD. Fill in all three or none.-6. Optional: turn on **Vision support** if the model accepts images, or select **Detect**; see [Detect vision support](#detect-vision-support). New models in **Custom** and in groups you created start with vision off; models you add to other groups start with it on.+6. Optional: turn on **Vision support** if the model accepts images, or select **Detect**; see [Detect vision support](#detect-vision-support). New models in **Custom** and in groups you created start with vision off; models you add to **vLLM** start with it on.7. Optional: turn on **Fast mode**; see [Fast mode](#fast-mode).8. Select **Confirm**.Which protocol a new model uses depends on its group:-- **Vendor groups** (DeepSeek, Google Gemini, OpenAI, Anthropic, Z.AI, Moonshot, MiniMax) support only the vendor's own API. If a model id cannot be routed that way, the dialog warns you and offers **Move to Custom**. Use Custom for OpenAI-compatible endpoints.-- **OpenRouter** always uses `openai-responses`, and **vLLM** always uses `openai-chat-vllm-adapter`.-- **OpenAI-compatible gateway groups** use OpenAI Chat Completions, except for aggregate presets that pin a model-specific protocol.+- **vLLM** always uses `openai-chat-vllm-adapter`.- **Custom** and groups you created: pick the protocol from the base URL field, or detect it. See [Detect a custom model's protocol](#detect-a-custom-models-protocol).+### Built-in models only++Every built-in group except **Custom** and **vLLM** carries the models in PenguinHarness's built-in catalog and nothing else. Their keys are managed per group, and which models they hold is the catalog's to decide.++- These groups have no **Add model**, and **Model settings** does not offer them as a group to move a model into.+- The server refuses a new model in one of these groups unless it is one of the group's built-in models: saving it fails with "This group carries its built-in models only". `penguin config model add` refuses it the same way. A built-in model you deleted can be added back, which is what **Sync presets** does.+- Models already in these groups stay where they are, including ones you added to a gateway group before this rule. They keep working, and you can edit them, rename them within the group, or delete them.+- A vendor group (DeepSeek, Google Gemini, OpenAI, Anthropic, Z.AI, Moonshot, MiniMax) supports only the vendor's own API. If one of its models has an id that cannot be routed that way, the model is marked and offers **Move to Custom**. Use **Custom** for OpenAI-compatible endpoints.+- The gateway groups keep the protocol their built-in models pin: OpenRouter uses `openai-responses`, and the other OpenAI-compatible gateways use OpenAI Chat Completions, except for aggregate presets that pin a model-specific protocol.+### Edit or delete a modelSelect the model's card to open **Model settings**. Change the fields, select **Confirm**, and confirm the save. From the same dialog you can **Test connection**, **Set as default model**, **Set as proxy vision model**, or **Delete model**.@@ -113,7 +133,7 @@ Changing **Model ID** or **Group** renames the entry; its credential and its def## Create a model group with AI-**Create with AI** covers what an import cannot read: a model listing page that is not an OpenAI-compatible `/models` endpoint, a service described in words, or vendor models to add to an existing group.+**Create with AI** covers what an import cannot read: a model listing page that is not an OpenAI-compatible `/models` endpoint, a service described in words, or a built-in model to put back into its group.> [!TIP]> For an OpenAI-compatible endpoint that lists its own models, **Import models** in the **Add group** dialog is faster.@@ -187,16 +207,16 @@ The credential comes from the same chain as the connection test: the key typed iEach model carries its own API key, or none.- **One model.** In **Model settings**, enter the key in **API key**. Once saved, the key is shown masked; leave the field empty to keep it, or select **Clear stored API key** to remove it.-- **A whole group.** On a group's header, select **Set key** and enter the key. It applies to every model in the group.+- **A whole group.** On a group's header, select **Enter key** and enter the key. It is written to every model in the group, replacing the key each one had. **Custom** has no **Enter key**: its models each reach their own endpoint.- **No key.** A model without a key uses the provider's environment variable on the server **only when its requests go to that provider's official endpoint**: the entry has no base URL (AgentHub's own `*_API_KEY` / `*_BASE_URL` pairing then applies), or its base URL is the vendor's own endpoint. A row with its own base URL is never covered by the environment, not even when `OPENAI_BASE_URL` names the same server. Gateway groups (TokenDance, OpenRouter, Fireworks AI, SiliconFlow, the Qwen gateways, ModelScope), **Custom**, **vLLM** and groups you created point at other endpoints, so their models need their own key: a Session, a connection test or a group speed test on a keyless row there fails with "has no API key" instead of borrowing `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`. The Penguin Go group is the exception that proves the rule — its rows fall back to its own `PENGUIN_GO_API_KEY`, never to a vendor's variable. The card and the dialog show when a key is read from an environment variable; see [Built-in provider groups](#built-in-provider-groups).A key you type is stored in the hidden Project config file, which has mode 0600. The Web App always masks it.-### Authorize a new API key+### Connect an account-A provider that supports automatic key authorization adds **Authorize key** to its group header. Three built-in groups do: TokenDance, Penguin Go and ModelScope. The key is written to every model in the group, replacing the key those models use now.+Three built-in groups can get their key for you: TokenDance, Penguin Go and ModelScope. Their header shows **Connect** with a status beside it: **Not connected**, or **Connected** once the group holds a key, however the key got there. Once connected, the button reads **Reconnect**, which gets a fresh key or switches to another account. The key is written to every model in the group, replacing the key those models use now.-1. On the group's header, select **Authorize key**.+1. On the group's header, select **Connect**.2. Select **Open authorization page**. The provider's authorization page opens in a new tab.3. Authorize there. The dialog, which shows "Waiting for the authorization to finish in the other tab…", reports the result on its own.@@ -208,7 +228,7 @@ TokenDance creates a **new** key on your account; it does not read a key you alrPenguin Go differs in four ways:- The server polls Penguin Go for the result, so this group has no manual-code mode.-- Once the group has a key, a **Sync** action sits on the header just before **Add model** and reads the platform's catalog again; see [The Penguin Go group](#the-penguin-go-group). **Authorize key** stays available, so you can switch to another platform account.+- Once the group is connected, a **Sync** action sits on the header right after **Reconnect** and reads the platform's catalog again; see [The Penguin Go group](#the-penguin-go-group). **Reconnect** stays available, so you can switch to another platform account.- A key the platform reports as invalid or revoked reopens authorization on the **Models** page.- If writing the delivered key locally fails, the server keeps that one delivery for a short while, so the write can be retried without authorizing again.@@ -216,17 +236,27 @@ ModelScope differs in three ways:- Authorization does not go through ModelScope's own pages but through an **authorization bridge**. The bridge holds ModelScope's client secret, runs the OAuth exchange on PenguinHarness's behalf, and hands back an access token that calls api-inference directly. The bridge's address comes from the server-side `MODELSCOPE_BRIDGE_URL` environment variable; see [Environment variables](/configuration#environment-variables).- The authorization page's address is the bridge's, opened as given, rather than assembled here the way Penguin Go's is. This group likewise has no manual-code mode.-- The access token **expires**; PenguinHarness stores the refresh credential on the server and silently renews before model requests. Re-authorize with **Authorize key** only when the refresh credential is missing or no longer valid.+- The access token **expires**; PenguinHarness stores the refresh credential on the server and silently renews before model requests. Select **Reconnect** only when the refresh credential is missing or no longer valid.Keep in mind:-- Only the Project owner can start an authorization. With TokenDance, only their own signed-in session can finish it, which in practice is the tab the dialog is open in. The redirect itself is received without a session, because the browser the provider sends back is not always the one you started in, but it only hands the code over: nothing is exchanged and no key is saved until the dialog asks for the result.+- Only the Project owner can connect. With TokenDance, only their own signed-in session can finish it, which in practice is the tab the dialog is open in. The redirect itself is received without a session, because the browser the provider sends back is not always the one you started in, but it only hands the code over: nothing is exchanged and no key is saved until the dialog asks for the result.- The whole exchange runs on the server. Neither TokenDance's PKCE verifier, Penguin Go's device secret, nor ModelScope's code and device secret ever reaches the browser, and the new key goes straight into the model table without passing through it. ModelScope's client secret is never in PenguinHarness at all; only the bridge holds it.- An authorization flow waits for at most ten minutes. ModelScope delivers an access token / refresh token pair: the access token is written to the model table, while the refresh token stays only in the server DB and is never returned to the frontend or written to the Project config.- A delivered key is handed over only once. Penguin Go and ModelScope both keep that one delivery briefly if saving it locally fails, so the write can be retried without authorizing again. ModelScope leaves nothing to clean up in ModelScope's console — what it returns is a token for your own account, not a newly minted key.- TokenDance hands over the new key only once. If saving it fails, authorize again and delete the unused key in the provider's console.- A TokenDance key carries PenguinHarness's app URL from the [App attribution](#app-attribution) table, so calls made with it stay attributed even from another tool.+### Account balances++TokenDance and DeepSeek report the balance of the account a key belongs to. Once one of these groups has a key, its header shows the balance in the currency chosen under **Currency** in the settings, converted at the same fixed rate of 7 as prices. For DeepSeek the key may also be the server's `DEEPSEEK_API_KEY`, which its models already fall back to (see [Set API keys](#set-api-keys)); TokenDance is a gateway, so its key must be stored on the group. An account holding several currencies shows their sum: ¥110 and $5 read `¥145`, or `$20.71`. The server asks the provider with the stored key, so the key never reaches the browser.++- Two icons stand before the balance. The refresh icon reads it again; point at it to see the provider's own figures and when they were read. Answers are kept on the server for a minute; the refresh icon skips that.+- A balance that cannot be read shows "—"; point at the refresh icon for the reason.+- The pin keeps the balance next to your name at the bottom of the sidebar, in the same currency. One balance can be pinned at a time: pinning another replaces it. The pin is saved with your account, not in the browser. The pinned balance is read when the app loads and every five minutes after that.++The balance is read with `GET /api/projects/:id/models/balance?provider=<group>`, which every member of the Project may call.+## Set the default modelNew conversations use the Project's default model unless you pick another one. A new Project's default is `deepseek-flash` (DeepSeek V4.1 Flash), which reads images itself.@@ -253,7 +283,7 @@ In **Model settings**, select **Test connection** (owner only). The test uses whTo compare the models in a group:-1. On the group's header, select **Speed test**.+1. On the group's header, select the speed test icon (**Speed test**).2. Select **Start**.PenguinHarness sends one real request to each model in turn, which uses a small amount of your API quota, and shows on each card:@@ -261,7 +291,7 @@ PenguinHarness sends one real request to each model in turn, which uses a small- the time to first token, in milliseconds: green under 1000, yellow up to 3000, red above;- the output rate, in Tokens per second: green at 40 or more, yellow at 15 or more, red below.-Results stay only on the page and are gone after a reload.+While the test runs, the same icon stops it (**Stop speed test**): the model being measured finishes, no further request is sent, and the results so far stay. Results stay only on the page and are gone after a reload.## Sync preset models@@ -404,7 +434,7 @@ The table below lists the built-in groups and the environment variables their mo| Provider | API key env var | Notes || --- | --- | --- || tokendance | `OPENAI_API_KEY` | The recommended group. OpenAI-compatible gateway, preset base URL `https://tokendance.space/gateway/v1`; model ids are bare, with no vendor prefix (e.g. `glm-5.3`, `kimi-k3`); pricing is the gateway's own CNY rates, several of them currently discounted |-| penguin-go | `PENGUIN_GO_API_KEY` | Preset relay group, fixed base URL `https://token.penguin.ooo/api`; its header authorizes a key for you or takes one you set by hand. See [The Penguin Go group](#the-penguin-go-group) |+| penguin-go | `PENGUIN_GO_API_KEY` | Preset relay group, fixed base URL `https://token.penguin.ooo/api`; its header connects for you or takes a key you enter by hand. See [The Penguin Go group](#the-penguin-go-group) || opencode-go | `OPENAI_API_KEY` | OpenCode Go subscription gateway. Each model pins its own protocol: Chat Completions or Responses at `https://opencode.ai/zen/go/v1`, Anthropic Messages at `https://opencode.ai/zen/go` (that client's variable is `ANTHROPIC_API_KEY`). See [The OpenCode Go group](#the-opencode-go-group) || deepseek | `DEEPSEEK_API_KEY` | Group of the default model || openrouter | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://openrouter.ai/api/v1` |@@ -436,7 +466,7 @@ The direct MiniMax M3 client reads `MINIMAX_API_KEY`. The built-in MiniMax prese`penguin-go` is a built-in group like TokenDance: a relay behind the fixed base URL `https://token.penguin.ooo/api`. A new Project gets the group's catalog models right away; a Project created before the group adds them with **Sync presets**.-The group's key comes from its header; see [Authorize a new API key](#authorize-a-new-api-key). Authorization, and the **Sync** action that follows it, also read the platform's own model catalog:+The group's key comes from its header; see [Connect an account](#connect-an-account). Connecting, and the **Sync** action that follows it, also read the platform's own model catalog:- Models the platform offers and the Project does not have are added, with their protocol, endpoint, display name, context window, vision flag and list price. Pure embedding models are left out.- Models the Project already has keep their endpoint and everything else you configured. Only their three prices and their client protocol are refreshed, `max_tokens` stays unset so the agent's setting applies, and nothing is ever deleted.@@ -446,7 +476,7 @@ The platform quotes peak rates in USD per million Tokens. The group's DeepSeek r### The OpenCode Go group-`opencode-go` holds the 27 models OpenCode lists for its Go subscription. One key serves all of them: set it once with **Set key** on the group header.+`opencode-go` holds the 27 models OpenCode lists for its Go subscription. One key serves all of them: set it once with **Enter key** on the group header.- **Protocols.** OpenCode serves each model on one of three endpoints, so each row pins its own `client_type` and base URL. Chat Completions (`openai-chat`) and Responses (`openai-responses`) models use `https://opencode.ai/zen/go/v1`. Anthropic Messages (`ant-messages`) models use `https://opencode.ai/zen/go`, because the client adds `/v1/messages` itself. Like every gateway's rows, none of them falls back to `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`: the key goes on the group. A model you add to the group yourself gets `openai-chat` and the `/v1` base URL.- **Prices.** Go is a monthly subscription whose usage limits are dollar amounts per model: a monthly allowance, of which at most 20% can be used in five hours and 50% in a week. The rows record the per-token rates a request draws from that allowance, so for this group the cost center shows how much of it you used, not a bill. `gpt-5.6-luna`, `grok-4.6`, `qwen3.7-plus` and `qwen3.6-plus` record their base tier, which covers up to 272K, 200K, 256K and 256K input tokens respectively. The four DeepSeek models follow DeepSeek's off-peak schedule; see [Prices and promotions](#prices-and-promotions).@@ -457,7 +487,7 @@ The platform quotes peak rates in USD per million Tokens. The group's DeepSeek r`modelscope` is an aggregate gateway group: one ModelScope api-inference endpoint behind the preset base URL `https://api-inference.modelscope.cn/v1`. Model ids are upstream repo names, so they keep their vendor prefix (`deepseek-ai/DeepSeek-V4.1-Flash`, `Qwen/Qwen3.8-27B`). All three preset rows pin AgentHub's generic Responses client (`client_type = "openai-responses"`) and send inference requests to `{base_url}/responses`. A new Project gets these presets right away; an existing Project updates its stored protocol with **Sync presets** or the next ModelScope authorization.-The group's key comes from its header; see [Authorize a new API key](#authorize-a-new-api-key). Authorization goes through an authorization bridge, which holds the ModelScope client secret and returns an api-inference access token / refresh token pair, rather than through ModelScope's own pages. Nothing else about the group is special: inference requests go straight to `https://api-inference.modelscope.cn/v1` and never through the bridge. The access token is written into `.project_config.toml` like any other group key, while the refresh token stays only in the server DB. The access token expires, and PenguinHarness silently renews it before model requests; re-authorize from the header only when the refresh token is missing or no longer valid.+The group's key comes from its header; see [Connect an account](#connect-an-account). Connecting goes through an authorization bridge, which holds the ModelScope client secret and returns an api-inference access token / refresh token pair, rather than through ModelScope's own pages. Nothing else about the group is special: inference requests go straight to `https://api-inference.modelscope.cn/v1` and never through the bridge. The access token is written into `.project_config.toml` like any other group key, while the refresh token stays only in the server DB. The access token expires, and PenguinHarness silently renews it before model requests; reconnect from the header only when the refresh token is missing or no longer valid.The preset rows carry no price. ModelScope bills for api-inference and its model pages publish no read-able rate, so the rows are left unpriced: the models page shows no price badge on them and the cost center reports their usage as uncosted. That is the catalog's way of recording "nobody has looked this up" — see [Prices and promotions](#prices-and-promotions).diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.mdindex 2ee2e83b..2206f2ad 100644--- a/packages/docs/content/models.zh.md+++ b/packages/docs/content/models.zh.md@@ -34,9 +34,19 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择价格按每百万 Token 显示,顺序为缓存命中 / 缓存未命中 / 输出。币种在设置里**币种**下选择:**美元 $** 或 **人民币 ¥**,按固定汇率 7 换算。-点击卡片即可打开**模型配置**。分组旁边的链接会打开供应商的密钥控制台(**前往密钥管理**)。模型弹窗里还有两个链接,分别打开供应商的模型列表(**获取模型 id**)和模型的主页(**模型主页**)。+点击卡片即可打开**模型配置**。其中的链接分别打开供应商的模型列表(**获取模型 id**)、模型的主页(**模型主页**),以及和**填写密钥**弹窗一样,打开供应商的密钥控制台(**前往密钥管理**)。-只有 Project owner 能修改模型和凭证。成员可以搜索、展开和收起分组,在自己浏览器里调整顺序,也能以只读方式打开**模型配置**。+分组标题栏左侧是供应商 logo、分组名、模型数,以及随分组展开而转向的箭头。右侧从左到右依次是:++- 分组的余额:TokenDance 和 DeepSeek 分组有 key 之后显示,前面是图钉和刷新图标,后面有一条分隔线,见[账户余额](#账户余额);+- 连接状态和**连接**:TokenDance、Penguin Go 和 ModelScope,见[连接账户](#连接账户);+- **填写密钥**:除 **Custom** 以外的每个分组,见[设置 API key](#设置-api-key);+- 测速,见[测速](#测速);+- **添加模型**:只在 **Custom**、**vLLM** 和你创建的分组,见[添加模型](#添加模型)。++TokenDance 分组还没有 key 时,所有分组上方会有一条横幅,推荐连接 TokenDance 钱包,这样分组里的模型不用手动配置密钥。横幅上的**连接**与分组标题栏上的是同一个流程。点击 × 可以在当前浏览器里隐藏横幅。++只有 Project owner 能修改模型和凭证。成员可以搜索、展开和收起分组,在自己浏览器里调整顺序,查看余额和连接状态,也能以只读方式打开**模型配置**。## 新增模型分组@@ -84,27 +94,37 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择## 添加模型+**添加模型**只在 **Custom**、**vLLM** 和你创建的分组的标题栏上。其余内置分组(厂商分组与网关分组)只承载内置模型,见[只承载内置模型](#只承载内置模型)。+1. 在分组标题上,点击**添加模型**。-2. 在**模型 ID** 里输入模型 id,必须与供应商 API 要求的完全一致,例如 `gpt-5.5`。**获取模型 id** 会打开供应商的模型列表。+2. 在**模型 ID** 里输入模型 id,必须与供应商 API 要求的完全一致,例如 `qwen3-32b`。**获取模型 id** 会打开供应商的模型列表。3. 可选:在**模型名称**里输入显示名。显示名为空时直接显示模型 id。4. 填写凭证和端点:- - **API key**:在厂商分组里留空则使用供应商的环境变量,服务端设置了这个变量时输入框会显示变量名。在网关分组、**Custom** 分组和你创建的分组里 key 必填——端点不是厂商自己的地址时,不会使用任何环境变量。- - **自定义 base URL**:在 **Custom** 分组和你创建的分组里必填。网关分组会自动填好。+ - **API key**:必填——这些分组指向的都不是厂商自己的端点,这样的端点不会使用任何环境变量。+ - **自定义 base URL**:必填,填你自己的服务或网关的端点。5. 可选:填写限制和价格:- **上下文窗口**:模型的上下文窗口大小,单位是 Token。模型不在内置模型目录里时,留空会保存为 1000000。- **最大输出长度**:每次请求最多输出的 Token 数。留空则使用 Agent 的设置;上下文较小的模型建议调低这个值。- **缓存命中价格**、**缓存未命中价格**和**输出价格**:按每百万 Token 填写,用页面上显示的币种;存储时统一换算成美元。三项要么全填,要么全不填。-6. 可选:如果模型能接收图片,打开**支持视觉**,或者点击**检测**;见[检测视觉支持](#检测视觉支持)。在 **Custom** 分组和你创建的分组里,新添加的模型默认关闭视觉;加到其他分组的模型默认开启视觉。+6. 可选:如果模型能接收图片,打开**支持视觉**,或者点击**检测**;见[检测视觉支持](#检测视觉支持)。在 **Custom** 分组和你创建的分组里,新添加的模型默认关闭视觉;加到 **vLLM** 分组的模型默认开启视觉。7. 可选:打开**快速模式**;见[快速模式](#快速模式)。8. 点击**确认**。新模型使用哪种协议,取决于所在的分组:-- **厂商分组**(DeepSeek、Google Gemini、OpenAI、Anthropic、Z.AI、Moonshot、MiniMax)只支持厂商自己的 API。如果模型 id 无法按这种方式路由,弹窗会警告你,并提供**转为自定义模型**。OpenAI 兼容的端点请放进 **Custom** 分组。-- **OpenRouter** 总是使用 `openai-responses`,**vLLM** 总是使用 `openai-chat-vllm-adapter`。-- **OpenAI 兼容网关分组**使用 OpenAI Chat Completions,但聚合分组的预置条目可以逐条固定模型专属协议。+- **vLLM** 总是使用 `openai-chat-vllm-adapter`。- **Custom** 和你创建的分组:在 base URL 字段里选择协议,或者检测协议。见[检测自定义模型的协议](#检测自定义模型的协议)。+### 只承载内置模型++除 **Custom** 和 **vLLM** 以外,每个内置分组只承载 PenguinHarness 内置模型目录里的模型。这些分组的 key 按分组统一管理,组里有哪些模型由目录决定。++- 这些分组没有**添加模型**,**模型配置**的分组下拉里也不提供把模型移进这些分组。+- 服务端会拒绝往这些分组新增不属于该分组内置模型的条目:保存时提示「该分组只承载内置模型」。`penguin config model add` 同样拒绝。删掉的内置模型可以重新加回来,**同步预置**做的就是这件事。+- 这些分组里已有的模型原样保留,包括此前你在网关分组里自行添加的。它们照常可用,可以编辑、在本组内改名或删除。+- 厂商分组(DeepSeek、Google Gemini、OpenAI、Anthropic、Z.AI、Moonshot、MiniMax)只支持厂商自己的 API。如果其中某个模型的 id 无法按这种方式路由,它会带上警示,并提供**移到自定义分组**。OpenAI 兼容的端点请放进 **Custom** 分组。+- 网关分组沿用内置模型固定的协议:OpenRouter 使用 `openai-responses`,其余 OpenAI 兼容网关使用 OpenAI Chat Completions,但聚合分组的预置条目可以逐条固定模型专属协议。+### 编辑或删除模型点击模型卡片,打开**模型配置**。修改字段,点击**确认**,再确认保存。在同一个弹窗里,你还可以**测试连通性**、**设为默认模型**、**设为视觉代理模型**或**删除模型**。@@ -113,7 +133,7 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择## 用 AI 创建模型分组-**用 AI 创建**用来处理导入读不了的情况:模型列表页面不是 OpenAI 兼容的 `/models` 端点、只有文字描述的服务,或者要把厂商模型加进已有分组。+**用 AI 创建**用来处理导入读不了的情况:模型列表页面不是 OpenAI 兼容的 `/models` 端点、只有文字描述的服务,或者要把内置模型加回它所在的分组。> [!TIP]> 如果 OpenAI 兼容端点能自己列出模型,**新增分组**弹窗里的**导入模型**更快。@@ -187,16 +207,16 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择每个模型都可以配自己的 API key,也可以不配。- **单个模型。** 在**模型配置**里,把 key 填入 **API key**。保存后 key 会打码显示;输入框留空即保留原 key,点击**清除已存 API key** 可删除它。-- **整个分组。** 在分组标题栏上点击**手动设置密钥**并输入 key,组内所有模型都会使用它。+- **整个分组。** 在分组标题栏上点击**填写密钥**并输入 key,它会写入组内每个模型,覆盖各自原有的 key。**Custom** 分组没有**填写密钥**:其中的模型各自连接自己的端点。- **不配 key。** 没配 key 的模型**只在请求确实发往该供应商的官方端点时**使用服务端上供应商的环境变量:条目没有 base URL(此时按 AgentHub 自己的 `*_API_KEY` / `*_BASE_URL` 配对),或 base URL 是厂商自己的端点。自带 base URL 的条目一律不由环境变量覆盖,即使 `OPENAI_BASE_URL` 指向同一台服务器也不例外。网关分组(TokenDance、OpenRouter、Fireworks AI、SiliconFlow、两个 Qwen 网关、ModelScope)、**Custom**、**vLLM** 和你创建的分组指向别的端点,其中的模型必须配自己的 key:在这些分组里对没有 key 的模型发起会话、连通性测试或分组测速,会以「has no API key」失败,而不是借用 `OPENAI_API_KEY` 或 `ANTHROPIC_API_KEY`。Penguin Go 分组是唯一的例外,它回退到自己的 `PENGUIN_GO_API_KEY`,从不使用厂商变量。key 来自环境变量时,卡片和弹窗都会显示这一点;参见[内置供应商分组](#内置供应商分组)。你填写的 key 存在 Project 的隐藏配置文件里,文件权限为 0600。Web App 里它始终打码显示。-### 授权获取新 API key+### 连接账户-支持自动授权取 key 的供应商,会在分组标题栏上加上**自动获取密钥**。内置分组里有三个提供了这个流程:TokenDance、Penguin Go 和 ModelScope。取得的 key 会写入分组里的每个模型,替换它们现在使用的 key。+内置分组里有三个可以替你取得 key:TokenDance、Penguin Go 和 ModelScope。它们的标题栏上有**连接**按钮,旁边显示状态:**未连接**,或者分组里已存有 key 时显示**连接成功**,不论这把 key 是怎么写进来的。连接成功后按钮变为**重新连接**,用来换一把新 key 或换一个账户。取得的 key 会写入分组里的每个模型,替换它们现在使用的 key。-1. 在分组的标题栏上,点击**自动获取密钥**。+1. 在分组的标题栏上,点击**连接**。2. 点击**打开授权页**。供应商的授权页会在新标签页中打开。3. 在授权页完成授权。弹窗显示「等待在新标签页中完成授权…」,并自动报告结果。@@ -208,7 +228,7 @@ TokenDance 会为你的账号创建一把**新** key,不会读取你已有的Penguin Go 有四处不同:- 结果由服务端向 Penguin Go 轮询获取,因此这个分组没有手动填写授权码的方式。-- 分组有 key 之后,标题栏上**添加模型**之前会出现**同步**,用它再次读取平台的模型目录,见 [Penguin Go 分组](#penguin-go-分组)。**自动获取密钥**依然保留,可以换成另一个平台账号的 key。+- 连接成功后,标题栏上**重新连接**之后会出现**同步**,用它再次读取平台的模型目录,见 [Penguin Go 分组](#penguin-go-分组)。**重新连接**依然保留,可以换成另一个平台账号的 key。- 平台报告 key 失效或被吊销时,**模型库**页面会重新打开授权。- 取到的 key 写入本地失败时,服务端会把这一次交付短暂保留,可以直接重试写入,不必再次授权。@@ -216,16 +236,26 @@ ModelScope 有三处不同:- 授权不经过魔搭自己的页面,而是经过一台**授权中转层**。中转层持有魔搭的 client secret,代 PenguinHarness 走完 OAuth,再把一把可直接调用 api-inference 的 access token 交回来。中转层的地址来自服务端环境变量 `MODELSCOPE_BRIDGE_URL`,见[环境变量](/configuration#环境变量)。- 授权页的地址由中转层给出,PenguinHarness 原样打开,不像 Penguin Go 那样自己拼。同样没有手动填写授权码的方式。-- 拿到的 access token 是**会过期**的;PenguinHarness 会在服务端保存刷新凭据,并在模型请求前静默续期。刷新凭据失效或缺失时,才需要重新点一次**自动获取密钥**。+- 拿到的 access token 是**会过期**的;PenguinHarness 会在服务端保存刷新凭据,并在模型请求前静默续期。刷新凭据失效或缺失时,才需要点一次**重新连接**。注意事项:-- 只有 Project owner 能发起授权。TokenDance 还要求由他本人已登录的会话完成授权,实际上就是打开着弹窗的那个标签页。重定向本身不要求会话就能接收,因为供应商带回的浏览器未必是你发起授权时用的那个;但它只交回授权码:在弹窗来取结果之前,不会发生任何换取,也不会保存任何 key。+- 只有 Project owner 能发起连接。TokenDance 还要求由他本人已登录的会话完成授权,实际上就是打开着弹窗的那个标签页。重定向本身不要求会话就能接收,因为供应商带回的浏览器未必是你发起授权时用的那个;但它只交回授权码:在弹窗来取结果之前,不会发生任何换取,也不会保存任何 key。- 整个换取过程都在服务端完成。TokenDance 的 PKCE verifier、Penguin Go 的设备密钥、以及 ModelScope 的授权码和设备密钥都不会进入浏览器;新 key 直接写入模型表,同样不经过浏览器。ModelScope 的 client secret 从头到尾都不在 PenguinHarness 里,只有中转层持有。- 一次授权流程最多等待十分钟。ModelScope 交付的是一组 access token / refresh token:access token 写入模型表,refresh token 只保存在服务端 DB,不返回给前端,也不写入 Project 配置。- 交付回来的 key 只交一次。Penguin Go 和 ModelScope 都会在本地保存失败时短暂保留这一次交付,因此可以直接重试写入,不必再次授权。ModelScope 下无需去魔搭控制台清理——它交回的是你自己账号的 token,不是新造的 key。- TokenDance 的 key 携带[应用归因](#应用归因)表中 PenguinHarness 的应用 URL,所以即使用其他工具发起调用,用量也仍会归到 PenguinHarness 名下。+### 账户余额++TokenDance 和 DeepSeek 可以查询 key 所属账户的余额。这两个分组有 key 之后,标题栏上会显示余额,币种跟随设置里的**币种**,与价格一样按固定汇率 7 换算。DeepSeek 的 key 也可以是服务端的 `DEEPSEEK_API_KEY`,即它的模型本来就会使用的环境变量(见[设置 API key](#设置-api-key));TokenDance 是网关,key 必须存到分组上。账户持有多种货币时显示合计:¥110 加 $5 显示为 `¥145`,或 `$20.71`。查询由服务端用已存的 key 发起,key 不会到达浏览器。++- 余额前面有两个图标。刷新图标(同步)用来重新查询;鼠标指向它可以看到服务商给出的原始金额和查询时间。服务端会把查询结果保留一分钟;点击刷新图标时跳过这一分钟的缓存。+- 查询不到余额时显示「—」;鼠标指向刷新图标可以看到原因。+- 图钉(常驻)把余额常驻到侧边栏底部你的名字旁边,币种相同。同一时间只能常驻一个余额,常驻另一个即替换。常驻记在你的账户上,而不是浏览器里。常驻的余额在应用加载时查询一次,此后每五分钟刷新一次。++余额通过 `GET /api/projects/:id/models/balance?provider=<分组>` 查询,Project 的所有成员都可以调用。+## 设置默认模型新对话使用 Project 的默认模型,除非你选了别的。新建 Project 的默认模型是 `deepseek-flash`(DeepSeek V4.1 Flash),它自己就能读图。@@ -252,7 +282,7 @@ ModelScope 有三处不同:要比较一个分组里的模型:-1. 在分组标题栏上点击**测速**。+1. 在分组标题栏上点击测速图标(**测速**)。2. 点击**开始测速**。PenguinHarness 依次向每个模型发送一个真实请求,这会消耗少量 API 配额,然后在每张卡片上显示:@@ -260,7 +290,7 @@ PenguinHarness 依次向每个模型发送一个真实请求,这会消耗少- 首个 Token 的延迟,单位毫秒:低于 1000 显示绿色,1000 到 3000 显示黄色,3000 以上显示红色;- 输出速率,单位 Token/秒:40 及以上显示绿色,15 及以上显示黄色,15 以下显示红色。-结果只留在当前页面,刷新后就消失。+测速进行中,同一个图标用来停止(**停止测速**):正在测的那个模型测完后停止,不再发起后续请求,已有的结果保留。结果只留在当前页面,刷新后就消失。## 同步预置模型@@ -403,7 +433,7 @@ PenguinHarness 升级可能改变内置的预置模型目录。一旦发生,Pr| 供应商 | API key 环境变量 | 说明 || --- | --- | --- || tokendance | `OPENAI_API_KEY` | 推荐分组。OpenAI 兼容网关,预置 base URL `https://tokendance.space/gateway/v1`;模型 id 为裸名称,不带供应商前缀(如 `glm-5.3`、`kimi-k3`);价格采用网关自己的人民币费率,目前有几项在打折 |-| penguin-go | `PENGUIN_GO_API_KEY` | 预置的中转分组,固定 base URL `https://token.penguin.ooo/api`;分组标题栏可以为你自动授权一把 key,也可以手动设置。见 [Penguin Go 分组](#penguin-go-分组) |+| penguin-go | `PENGUIN_GO_API_KEY` | 预置的中转分组,固定 base URL `https://token.penguin.ooo/api`;分组标题栏可以为你连接取得 key,也可以手动填写。见 [Penguin Go 分组](#penguin-go-分组) || opencode-go | `OPENAI_API_KEY` | OpenCode Go 订阅网关。每个模型各自固定协议:Chat Completions 或 Responses 走 `https://opencode.ai/zen/go/v1`,Anthropic Messages 走 `https://opencode.ai/zen/go`(该客户端的变量是 `ANTHROPIC_API_KEY`)。见 [OpenCode Go 分组](#opencode-go-分组) || deepseek | `DEEPSEEK_API_KEY` | 默认模型所在的分组 || openrouter | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://openrouter.ai/api/v1` |@@ -435,7 +465,7 @@ OpenAI 兼容网关分组(openrouter / fireworks / siliconflow / tokendance /`penguin-go` 和 TokenDance 一样是内置分组:一个中转服务,base URL 固定为 `https://token.penguin.ooo/api`。新建的 Project 立即带上这个分组的目录模型;在该分组之前创建的 Project,用**同步预置**把它们补上。-分组的 key 从标题栏取得,见[授权获取新 API key](#授权获取新-api-key)。授权以及随后的**同步**还会读取平台自己的模型目录:+分组的 key 从标题栏取得,见[连接账户](#连接账户)。连接以及随后的**同步**还会读取平台自己的模型目录:- 平台提供而 Project 没有的模型会被添加进来,连同协议、端点、显示名、上下文窗口、视觉能力和牌价。纯向量(embedding)模型不收录。- Project 已有的模型保留自己的端点和你配置过的其他内容。只刷新三项价格和客户端协议,`max_tokens` 保持未设置,沿用 Agent 的设定;任何模型都不会被删除。@@ -445,7 +475,7 @@ OpenAI 兼容网关分组(openrouter / fireworks / siliconflow / tokendance /### OpenCode Go 分组-`opencode-go` 收录 OpenCode 为 Go 订阅列出的 27 个模型。它们共用一把 key:在分组标题栏用**手动设置密钥**设置一次即可。+`opencode-go` 收录 OpenCode 为 Go 订阅列出的 27 个模型。它们共用一把 key:在分组标题栏用**填写密钥**设置一次即可。- **协议。** OpenCode 把每个模型放在三个端点之一上,因此每个条目各自固定 `client_type` 与 base URL。Chat Completions(`openai-chat`)和 Responses(`openai-responses`)模型使用 `https://opencode.ai/zen/go/v1`;Anthropic Messages(`ant-messages`)模型使用 `https://opencode.ai/zen/go`,因为客户端会自行加上 `/v1/messages`。与所有网关的条目一样,它们都不会回退到 `OPENAI_API_KEY` 或 `ANTHROPIC_API_KEY`:key 要设在分组上。你自己添加到该分组的模型使用 `openai-chat` 和带 `/v1` 的 base URL。- **价格。** Go 按月订阅,用量上限是按模型计的美元额度:每月一份额度,每 5 小时最多用掉其中 20%,每周最多 50%。条目记录的是每次请求从额度中扣除的每 Token 价格,因此对这个分组而言,成本中心显示的是你用掉了多少额度,而不是一张账单。`gpt-5.6-luna`、`grok-4.6`、`qwen3.7-plus` 和 `qwen3.6-plus` 记录基础档,分别覆盖 272K、200K、256K 和 256K 输入 Token 以内。四个 DeepSeek 模型遵循 DeepSeek 的空闲时段,见[价格与促销](#价格与促销)。@@ -456,7 +486,7 @@ OpenAI 兼容网关分组(openrouter / fireworks / siliconflow / tokendance /`modelscope` 是聚合网关分组:三条预置共用魔搭 api-inference 端点,预置 base URL 为 `https://api-inference.modelscope.cn/v1`。模型 id 就是上游仓库名,因此保留供应商前缀(`deepseek-ai/DeepSeek-V4.1-Flash`、`Qwen/Qwen3.8-27B`)。三条预置都固定使用 AgentHub 通用 Responses 客户端(`client_type = "openai-responses"`),推理请求发往 `{base_url}/responses`。新建的 Project 立即带上这些预置;既有 Project 可通过**同步预置**或下一次 ModelScope 授权更新已存的协议。-分组的 key 从标题栏取得,见[授权获取新 API key](#授权获取新-api-key)。授权走一台授权中转层,由中转层持有魔搭的 client secret 并交回一组 api-inference access token / refresh token,而不是经过魔搭自己的页面。除此之外这个分组没有特别之处:推理请求直接发给 `https://api-inference.modelscope.cn/v1`,从不经过中转层;access token 和其他分组的 key 一样写进 `.project_config.toml`,refresh token 只保存在服务端 DB。access token 会过期,PenguinHarness 会在模型请求前静默续期;refresh token 缺失或失效时,才需要从标题栏重新授权一次。+分组的 key 从标题栏取得,见[连接账户](#连接账户)。连接走一台授权中转层,由中转层持有魔搭的 client secret 并交回一组 api-inference access token / refresh token,而不是经过魔搭自己的页面。除此之外这个分组没有特别之处:推理请求直接发给 `https://api-inference.modelscope.cn/v1`,从不经过中转层;access token 和其他分组的 key 一样写进 `.project_config.toml`,refresh token 只保存在服务端 DB。access token 会过期,PenguinHarness 会在模型请求前静默续期;refresh token 缺失或失效时,才需要从标题栏重新连接一次。预置条目不带价格。魔搭的 api-inference 是计费的,但它的模型页面读不到费率,所以这些条目按未定价处理:模型页在它们上面不显示价格徽标,成本中心把它们的用量报为未计价。这是目录记录「没人查过这个价格」的方式,见[价格与促销](#价格与促销)。diff --git a/packages/docs/content/quickstart-desktop.en.md b/packages/docs/content/quickstart-desktop.en.mdindex 474bd8bf..14ee9d7b 100644--- a/packages/docs/content/quickstart-desktop.en.md+++ b/packages/docs/content/quickstart-desktop.en.md@@ -39,10 +39,10 @@ The app opens signed in. The window signs itself in, so there is no password toPenguinHarness ships with no model credentials. Give it an API key for the model you want to use:1. In the sidebar, select **Models**. Models are listed in one group per provider, and the default model is marked **Default**.-2. In your provider's group, click **Set key**, enter the API key, and click **Confirm**. The key is written to every model in that group.+2. In your provider's group, click **Enter key**, enter the API key, and click **Confirm**. The key is written to every model in that group. TokenDance, Penguin Go and ModelScope can also get a key for you: click **Connect** on their group.3. If you want a model other than the default, open that model and click **Set as default model**.-To add a model that is not listed, click **Add model** in its provider's group and fill in the **Model ID** and **API key**.+To add a model that is not listed, click **Add model** in the **Custom** group (or a group you create) and fill in the **Model ID**, **Custom base URL** and **API key**. The other built-in groups hold their built-in models only.A model is always referenced as a `(provider, model_id)` pair: the provider is never inferred from the model id. See [Models & Providers](/models) for the built-in groups.diff --git a/packages/docs/content/quickstart-desktop.zh.md b/packages/docs/content/quickstart-desktop.zh.mdindex 1b472f74..771a3a6e 100644--- a/packages/docs/content/quickstart-desktop.zh.md+++ b/packages/docs/content/quickstart-desktop.zh.md@@ -39,10 +39,10 @@ macOS 安装包已经过 Developer ID 签名和公证,Windows 安装程序已PenguinHarness 不内置任何模型凭据。为要使用的模型配置 API Key:1. 在侧边栏选择**模型库**。模型按供应商分组列出,默认模型带有**默认**标记。-2. 在你所用供应商的分组里点击**手动设置密钥**,输入 API Key,然后点击**确认**。这个 Key 会写入分组里的每个模型。+2. 在你所用供应商的分组里点击**填写密钥**,输入 API Key,然后点击**确认**。这个 Key 会写入分组里的每个模型。TokenDance、Penguin Go 和 ModelScope 还可以替你取得 key:在它们的分组上点击**连接**。3. 如果要使用默认模型以外的模型,打开那个模型,点击**设为默认模型**。-要添加列表里没有的模型,在对应供应商的分组里点击**添加模型**,填写**模型 ID** 和 **API key**。+要添加列表里没有的模型,在 **Custom** 分组(或你创建的分组)里点击**添加模型**,填写**模型 ID**、**自定义 base URL** 和 **API key**。其余内置分组只承载内置模型。模型始终以 `(provider, model_id)` 二元组引用,供应商绝不会由模型 id 推断。内置分组见[模型与 Provider](/models)。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 6afd4b70..d0abada6 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -403,9 +403,17 @@ export interface UiPrefs {workMode?: "dev" | "company";/** The organization last opened in company mode, as `<projectId>/<orgId>`. */lastOrgKey?: string;+ /** The one group balance shown beside the user name (pinned on the models page); null when unpinned. */+ pinnedBalance?: PinnedBalance | null;[key: string]: unknown;}+/** A group balance pinned beside the user name: which Project's key reads which group's balance. */+export interface PinnedBalance {+ projectId: string;+ provider: string;+}+export interface PrefsResponse {prefs: UiPrefs;}@@ -815,6 +823,59 @@ export interface DefaultModelResponse {defaultModel: ModelRefDto;}+/** One balance in one currency. */+export interface ModelBalanceAmount {+ /** Decimal string in `currency`'s major unit, as the vendor states it (TokenDance's micro-yuan are converted to yuan). */+ amount: string;+ /** ISO 4217 code: `CNY`, `USD`, … */+ currency: string;+}++/**+ * Why a group's balance could not be read:+ * - `unsupported`: the group publishes no balance endpoint (no `balance` descriptor in the catalog);+ * - `no_key`: the group has no API key to ask with — none stored, and no environment variable+ * the credential rule lends its rows for the balance endpoint's host;+ * - `upstream_failed`: the vendor could not be reached in time, refused the request, or answered+ * without a readable balance.+ */+export type ModelBalanceErrorCode = "unsupported" | "no_key" | "upstream_failed";++/**+ * GET /api/projects/:p/models/balance?provider=<group>[&force=1] (Project member): the account+ * balance behind the group's API key — the stored one, or else the environment key its rows+ * fall back to under the credential rule (DeepSeek's DEEPSEEK_API_KEY) — read server-side from+ * the endpoint the catalog's `balance` descriptor names. The key never reaches the browser, and+ * neither does the vendor's own text. Like the connectivity test, a balance that cannot be read is an answer+ * (`ok: false` with a code), not a failed request. Readings and vendor failures are cached for+ * 60 s per Project and group, for as long as the group's key is the same; `force=1` skips the+ * cache and refreshes it.+ */+export type ModelBalanceResponse = ModelBalanceReading | ModelBalanceFailure;++export interface ModelBalanceReading extends ModelBalanceAmount {+ ok: true;+ provider: string;+ /** Whether the account can make requests right now (DeepSeek's `is_available`); absent when the vendor does not say. */+ available?: boolean;+ /** Further currencies the account holds, after the one in `amount` / `currency`; absent when there is only one. */+ others?: ModelBalanceAmount[];+ /** When the server read it from the vendor (ISO 8601); a cached answer keeps its original time. */+ fetchedAt: string;+}++export interface ModelBalanceFailure {+ ok: false;+ provider: string;+ error: ModelBalanceErrorCode;+ /** The vendor's HTTP status, when it answered with an error. */+ status?: number;+ /** English detail for logs and bug reports; the Web App words each code itself. */+ message: string;+ /** When the answer was settled (ISO 8601). */+ fetchedAt: string;+}+// ---------------------------------------------------------------------------// Provider key-minting flows (/api/projects/:p/model-oauth, owner)// ---------------------------------------------------------------------------diff --git a/packages/server/src/http/routes/models.ts b/packages/server/src/http/routes/models.tsindex 89695222..d6bbb50d 100644--- a/packages/server/src/http/routes/models.ts+++ b/packages/server/src/http/routes/models.ts@@ -4,13 +4,14 @@* 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). Any member can read (api_key is masked); only the owner can- * modify, test, or detect.+ * 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.*/import { Hono } from "hono";import type {DefaultModelResponse,EndpointModelListRequest,+ ModelBalanceResponse,ModelProtocolDetectRequest,ModelRefDto,ModelsUpdateRequest,@@ -27,6 +28,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 { ModelBalances } from "../../services/model-balance.js";/** What this route group reaches — bound by its module (src/modules). */export interface ModelsRouteDeps {@@ -205,6 +207,11 @@ function parseModelsUpdate(body: Record<string, unknown>): ModelsUpdateRequest {export function modelsRoutes(deps: ModelsRouteDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();+ /** The balance reader and its 60 s cache, one per route group. */+ const balances = new ModelBalances({+ groupKey: (projectId, provider) =>+ deps.projectConfigService.getGroupBalanceKey(projectId, provider),+ });app.get("/", async (c) => {// Defensive id validation.@@ -222,6 +229,25 @@ export function modelsRoutes(deps: ModelsRouteDeps): Hono<AppEnv> {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.+ // `force=1` is the page's refresh click and skips the 60 s cache.+ app.get("/balance", async (c) => {+ const projectId = requireValidId(c, "projectId");+ deps.access.requireProjectAccess(c.var.user.userId, projectId);+ const provider = c.req.query("provider") ?? "";+ if (provider === "" || provider.length > 64) {+ throw badRequest("provider must name a model group.");+ }+ const answer: ModelBalanceResponse = await balances.read(+ projectId,+ provider,+ c.req.query("force") === "1",+ );+ return c.json(answer);+ });+// Narrow default-model switch (owner): flips the same top-level `default_model` the// whole-table PUT above maintains, without resending the table — project settings can// change the default without carrying credentials. The pair must name a configureddiff --git a/packages/server/src/mechanisms/projects.ts b/packages/server/src/mechanisms/projects.tsindex 9b420f22..1a049388 100644--- a/packages/server/src/mechanisms/projects.ts+++ b/packages/server/src/mechanisms/projects.ts@@ -169,6 +169,12 @@ export abstract class ProjectConfigStore {options?: { expectedRefreshToken?: string },): Promise<number>;abstract getGroupApiKey(projectId: string, provider: string): Promise<string | undefined>;+ /**+ * The key a group's account balance is read with: the stored group key, or else the+ * environment key a Session on one of the group's rows would use, when that variable's+ * official endpoint is the balance endpoint's own host. Server-side only.+ */+ abstract getGroupBalanceKey(projectId: string, provider: string): Promise<string | undefined>;abstract setModelApiKeyResolver(resolver: (context: ModelRequestContext) => Promise<string | undefined>,): void;diff --git a/packages/server/src/services/model-balance.ts b/packages/server/src/services/model-balance.tsnew file mode 100644index 00000000..528cd1ae--- /dev/null+++ b/packages/server/src/services/model-balance.ts@@ -0,0 +1,253 @@+/**+ * Group account balances (GET /api/projects/:p/models/balance).+ *+ * A group whose catalog entry carries a `balance` descriptor publishes an endpoint that+ * answers the balance of the account an API key belongs to. The server makes that call with+ * the group's stored key, so the key never leaves this process, and hands the page a small+ * reading in place of the vendor's own reply: an amount as a decimal string, its currency,+ * and when it was read.+ *+ * - **Readers.** One per published response shape (`ModelProviderBalance.format`), each strict+ * about what it accepts: an answer that does not carry a number where the vendor documents+ * one is a failure, never a zero.+ * - **Outbound.** The global `fetch`, which the server routes through the admin proxy+ * settings (net/proxy.ts), with a 5 s limit.+ * - **Cache.** 60 s per Project and group, keyed on a digest of the key as well, so a key+ * written by a new authorization misses it instead of serving the old account's balance.+ * Vendor failures are cached too: a page load and a pinned balance asking at once must not+ * become two calls to a vendor that is already failing. `force` skips the cache and+ * refreshes it; two callers asking at once share one call.+ * - **Failures are answers** (`ok: false`), as the connectivity test's are: nothing here+ * throws, so an unreadable balance never lands in the error center, and no vendor text is+ * relayed — only its HTTP status.+ */+import { createHash } from "node:crypto";+import { providerInfo } from "@prismshadow/penguin-core/model-catalog";+import type { ModelProviderBalance } from "@prismshadow/penguin-core/model-catalog";+import type {+ ModelBalanceAmount,+ ModelBalanceFailure,+ ModelBalanceReading,+ ModelBalanceResponse,+} from "../api/types.js";++/** How long a vendor may take to answer a balance request. */+export const BALANCE_TIMEOUT_MS = 5_000;++/** How long an answer is reused for the same Project, group and key. */+export const BALANCE_CACHE_MS = 60_000;++/** What a reader takes out of a vendor's reply. */+export type BalanceFigures = Omit<ModelBalanceReading, "ok" | "provider" | "fetchedAt">;++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/** A plain decimal as a vendor writes it: optional minus, digits, optional fraction. */+const DECIMAL = /^-?\d+(\.\d+)?$/;++/**+ * Micro-units (an integer) as a decimal string in the major unit, with at least two decimals+ * and no trailing zeros beyond them: 162811 → "0.162811", 110000000 → "110.00". Integer+ * arithmetic, so no binary rounding creeps into a figure the vendor states exactly.+ */+export function microToDecimal(micro: number): string {+ const whole = Math.round(Math.abs(micro));+ const sign = micro < 0 && whole !== 0 ? "-" : "";+ const units = Math.floor(whole / 1_000_000);+ const fraction = String(whole % 1_000_000)+ .padStart(6, "0")+ .replace(/0+$/, "")+ .padEnd(2, "0");+ return `${sign}${units}.${fraction}`;+}++/**+ * TokenDance (https://tokendance.space/docs/open-api): `{ balance: { credits, credits_used,+ * balance } }`, every figure in micro-yuan. The remaining balance is `balance.balance`; an+ * envelope around it (`{ data: { balance: … } }`) is read the same way.+ */+function readTokenDance(body: unknown): BalanceFigures | undefined {+ const holder = isRecord(body) && isRecord(body.data) ? body.data : body;+ const wallet = isRecord(holder) ? holder.balance : undefined;+ const raw = isRecord(wallet) ? wallet.balance : undefined;+ const micro =+ typeof raw === "number"+ ? raw+ : typeof raw === "string" && DECIMAL.test(raw)+ ? Number(raw)+ : NaN;+ if (!Number.isFinite(micro)) return undefined;+ return { amount: microToDecimal(micro), currency: "CNY" };+}++/**+ * DeepSeek (https://api-docs.deepseek.com/api/get-user-balance): `{ is_available,+ * balance_infos: [{ currency, total_balance, granted_balance, topped_up_balance }] }`, one+ * entry per currency, amounts as decimal strings. The first entry is the headline; entries+ * that are not a currency code with a decimal amount are skipped rather than guessed at.+ */+function readDeepSeek(body: unknown): BalanceFigures | undefined {+ if (!isRecord(body) || !Array.isArray(body.balance_infos)) return undefined;+ const amounts: ModelBalanceAmount[] = [];+ for (const info of body.balance_infos) {+ if (!isRecord(info)) continue;+ const currency = info.currency;+ const total =+ typeof info.total_balance === "number" ? String(info.total_balance) : info.total_balance;+ if (typeof currency !== "string" || !/^[A-Z]{3}$/.test(currency)) continue;+ if (typeof total !== "string" || !DECIMAL.test(total)) continue;+ amounts.push({ amount: total, currency });+ }+ const [first, ...others] = amounts;+ if (first === undefined) return undefined;+ return {+ ...first,+ ...(typeof body.is_available === "boolean" ? { available: body.is_available } : {}),+ ...(others.length > 0 ? { others } : {}),+ };+}++const READERS: Record<+ ModelProviderBalance["format"],+ (body: unknown) => BalanceFigures | undefined+> = {+ tokendance: readTokenDance,+ deepseek: readDeepSeek,+};++/** Reads one vendor reply; undefined when it carries no balance the reader can vouch for. */+export function readBalance(+ format: ModelProviderBalance["format"],+ body: unknown,+): BalanceFigures | undefined {+ return READERS[format](body);+}++interface CacheEntry {+ /** Digest of the key the answer was read with. */+ keyDigest: string;+ at: number;+ answer: ModelBalanceResponse;+}++export interface ModelBalanceDeps {+ /** The group's stored API key (the first of its rows that carries one), or undefined. */+ groupKey(projectId: string, provider: string): Promise<string | undefined>;+ /** Replaced in tests; defaults to the global fetch at call time, which carries the proxy settings. */+ fetchImpl?: typeof fetch;+ now?: () => number;+}++/** Reads group balances for the models routes; one instance per route group holds the cache. */+export class ModelBalances {+ private readonly cache = new Map<string, CacheEntry>();+ private readonly inflight = new Map<string, Promise<ModelBalanceResponse>>();++ constructor(private readonly deps: ModelBalanceDeps) {}++ async read(projectId: string, provider: string, force = false): Promise<ModelBalanceResponse> {+ const info = providerInfo(provider);+ const descriptor = info?.balance;+ if (info === undefined || descriptor === undefined) {+ return this.failure(provider, "unsupported", `The ${provider} group publishes no balance.`);+ }+ const key = await this.deps.groupKey(projectId, provider);+ if (key === undefined) {+ return this.failure(+ provider,+ "no_key",+ `The ${info.label} group has no API key to ask with.`,+ );+ }+ const slot = `${projectId}\u0000${provider}`;+ const keyDigest = createHash("sha256").update(key).digest("hex");+ const cached = this.cache.get(slot);+ if (+ !force &&+ cached !== undefined &&+ cached.keyDigest === keyDigest &&+ this.now() - cached.at < BALANCE_CACHE_MS+ ) {+ return cached.answer;+ }+ const flight = `${slot}\u0000${keyDigest}`;+ const pending = this.inflight.get(flight);+ if (pending !== undefined) return pending;+ const call = this.ask(provider, info.label, descriptor, key)+ .then((answer) => {+ this.cache.set(slot, { keyDigest, at: this.now(), answer });+ return answer;+ })+ .finally(() => this.inflight.delete(flight));+ this.inflight.set(flight, call);+ return call;+ }++ /** One vendor call, settled into an answer: never throws, never relays the vendor's text. */+ private async ask(+ provider: string,+ label: string,+ descriptor: ModelProviderBalance,+ key: string,+ ): Promise<ModelBalanceResponse> {+ const fetchImpl: typeof fetch = this.deps.fetchImpl ?? ((...args) => fetch(...args));+ let res: Response;+ try {+ res = await fetchImpl(descriptor.url, {+ headers: { authorization: `Bearer ${key}`, accept: "application/json" },+ signal: AbortSignal.timeout(BALANCE_TIMEOUT_MS),+ });+ } catch (err) {+ const timedOut = err instanceof Error && err.name === "TimeoutError";+ return this.failure(+ provider,+ "upstream_failed",+ timedOut+ ? `${label} did not answer the balance request within ${BALANCE_TIMEOUT_MS / 1000} s.`+ : `${label} could not be reached for its balance.`,+ );+ }+ if (!res.ok) {+ void res.body?.cancel().catch(() => undefined);+ return this.failure(+ provider,+ "upstream_failed",+ `${label} answered the balance request with HTTP ${res.status}.`,+ res.status,+ );+ }+ let body: unknown;+ try {+ body = await res.json();+ } catch {+ return this.failure(provider, "upstream_failed", `${label} answered with no JSON balance.`);+ }+ const figures = readBalance(descriptor.format, body);+ if (figures === undefined) {+ return this.failure(provider, "upstream_failed", `${label}'s answer carries no balance.`);+ }+ return { ok: true, provider, ...figures, fetchedAt: new Date(this.now()).toISOString() };+ }++ private failure(+ provider: string,+ error: ModelBalanceFailure["error"],+ message: string,+ status?: number,+ ): ModelBalanceFailure {+ return {+ ok: false,+ provider,+ error,+ ...(status !== undefined ? { status } : {}),+ message,+ fetchedAt: new Date(this.now()).toISOString(),+ };+ }++ private now(): number {+ return this.deps.now?.() ?? Date.now();+ }+}diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.tsindex b13cf117..a11f13d1 100644--- a/packages/server/src/services/project-config-service.ts+++ b/packages/server/src/services/project-config-service.ts@@ -52,7 +52,12 @@ import {resolveModelCredential,userText,} from "@prismshadow/penguin-core";-import { unroutableVendorModel } from "@prismshadow/penguin-core/model-catalog";+import {+ VENDOR_ENDPOINTS,+ providerInfo,+ unaddableModel,+ unroutableVendorModel,+} from "@prismshadow/penguin-core/model-catalog";import type {PluginTables,CommandPolicyRule,@@ -1245,8 +1250,10 @@ export class ProjectConfigService implements ProjectConfigStore {* promotion with it. A `discount` outside (0, 1) rejects the request before any write.** An entry the request adds to a first-party vendor group under a model id AgentHub cannot- * route is rejected as well (`model_not_routable`); one already stored under that key is- * written as it stands. See the loop below for why the two differ.+ * route is rejected as well (`model_not_routable`), and so is one it adds to any built-in+ * group but custom and vLLM when it is not one of that group's presets+ * (`model_not_addable`); one already stored under that key is written as it stands. See+ * the loops below for why the two differ.*/async updateModels(projectId: string, req: ModelsUpdateRequest): Promise<ModelsResponse> {return this.withProviderCredentialLock(projectId, MODELSCOPE_PROVIDER_ID, () =>@@ -1291,6 +1298,31 @@ export class ProjectConfigService implements ProjectConfigStore {);}+ // Only custom, vLLM and user-defined groups take models added by hand; every other+ // built-in group, gateways included, carries its catalog presets and the rows it already+ // stores. The same grandfathering as above: a stored row is written as it stands, hand-added+ // ones from before this rule included, and so is a row renamed inside its own group. A row+ // moved in from another group is being added here, and a preset is always welcome back+ // (the preset sync writes a deleted one again).+ for (const entry of req.models) {+ if (!unaddableModel(entry.provider, entry.modelId)) continue;+ if (prevModels.some((m) => entryMatches(m, entry.provider, entry.modelId))) continue;+ const from = entry.renamedFrom;+ if (+ from !== undefined &&+ from.provider === entry.provider &&+ prevModels.some((m) => entryMatches(m, from.provider, from.modelId))+ ) {+ continue;+ }+ const group = providerInfo(entry.provider)?.label ?? entry.provider;+ throw new HttpError(+ 400,+ "model_not_addable",+ `Model ${showRef(entry.provider, entry.modelId)} cannot be added: the ${group} group carries its built-in models only. Add it under a custom group.`,+ );+ }+const seen = new Set<string>();const nextModels: RawTable[] = [];let keepModelScopeGroup = false;@@ -1566,6 +1598,50 @@ export class ProjectConfigService implements ProjectConfigStore {return undefined;}+ /**+ * The key a group's account balance is read with (the catalog's `balance` descriptor names+ * the endpoint). The stored group key comes first. Without one, the environment key a+ * Session on one of the group's rows would use: core's modelEnvFallback decides, the rule+ * resolveModelCredential applies, and its variable is read from this process's env as the+ * routed client itself would read it. One more condition, because the balance request is+ * the server's own rather than the routed client's: the variable's official endpoint must+ * be the balance endpoint's host, so a vendor key never reaches another vendor. A DeepSeek+ * row keyed by DEEPSEEK_API_KEY qualifies; a gateway's rows (TokenDance) get no fallback at+ * all. Never returned to the browser.+ */+ async getGroupBalanceKey(projectId: string, provider: string): Promise<string | undefined> {+ const stored = await this.getGroupApiKey(projectId, provider);+ if (stored !== undefined) return stored;+ const balanceUrl = providerInfo(provider)?.balance?.url;+ if (balanceUrl === undefined) return undefined;+ const origin = (url: string): string | undefined => {+ try {+ return new URL(url).origin;+ } catch {+ return undefined;+ }+ };+ const balanceOrigin = origin(balanceUrl);+ const raw = await this.readRaw(projectId);+ for (const model of asArray(raw.models)) {+ if (model.provider !== provider) continue;+ const modelId = optStr(model.model_id);+ if (modelId === undefined) continue;+ const fallback = modelEnvFallback({+ provider,+ modelId,+ clientType: canonicalClientType(optStr(model.client_type)),+ baseUrl: optStr(model.base_url),+ });+ if (fallback === undefined) continue;+ const endpoints = VENDOR_ENDPOINTS[fallback.envKey] ?? [];+ if (!endpoints.some((own) => origin(own) === balanceOrigin)) continue;+ const value = process.env[fallback.envKey]?.trim();+ if (value) return value;+ }+ return undefined;+ }+/*** Adds newly advertised models and refreshes platform-owned routing and list price on* existing rows, then replaces this group's promotions (web.db) with the platform's. Projectdiff --git a/packages/server/test/models-balance.test.ts b/packages/server/test/models-balance.test.tsnew file mode 100644index 00000000..70e900ba--- /dev/null+++ b/packages/server/test/models-balance.test.ts@@ -0,0 +1,384 @@+/**+ * Group balances (GET /api/projects/:p/models/balance): the server asks the vendor endpoint+ * the catalog's `balance` descriptor names, with the group's stored key — or, without one, the+ * environment key a Session on the group's rows would use on that vendor's own host — and+ * answers with a small reading or a typed failure — never the key, never the vendor's own text.+ *+ * The vendors are stood in for at the wire: `fetch` is stubbed globally, which is the call the+ * reader really makes (the server routes it through the proxy dispatcher in production), so+ * the URL, the Bearer header and each vendor's documented reply shape are all exercised.+ */+import { writeFile } from "node:fs/promises";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { MODEL_CATALOG } from "@prismshadow/penguin-core";+import type { ModelBalanceResponse, ProjectCreateResponse } from "../src/api/types.js";+import {+ BALANCE_CACHE_MS,+ ModelBalances,+ microToDecimal,+ readBalance,+} from "../src/services/model-balance.js";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const TOKENDANCE_URL = "https://tokendance.space/portal/api/v1/user/balance";+const DEEPSEEK_URL = "https://api.deepseek.com/user/balance";++const json = (status: number, body: unknown): Response =>+ new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });++/** TokenDance's documented reply (https://tokendance.space/docs/open-api), in micro-yuan. */+const TOKENDANCE_REPLY = {+ balance: { credits: 58000000, credits_used: 57837189, balance: 162811 },+};++/** DeepSeek's documented reply, with a second currency riding along. */+const DEEPSEEK_REPLY = {+ is_available: true,+ balance_infos: [+ {+ currency: "CNY",+ total_balance: "110.00",+ granted_balance: "10.00",+ topped_up_balance: "100.00",+ },+ { currency: "USD", total_balance: "5.00", granted_balance: "0.00", topped_up_balance: "5.00" },+ ],+};++interface VendorCall {+ url: string;+ authorization: string | null;+}++/**+ * Stubs the global fetch with a stand-in for the two vendors: every call to a balance URL is+ * recorded, and `answer` decides the reply. Anything else the app fetches meanwhile is+ * refused and left out of the record.+ */+function stubVendors(answer: (url: string) => Response | Promise<Response>): VendorCall[] {+ const calls: VendorCall[] = [];+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ if (url !== TOKENDANCE_URL && url !== DEEPSEEK_URL) throw new Error(`unexpected fetch ${url}`);+ calls.push({ url, authorization: new Headers(init?.headers).get("authorization") });+ return answer(url);+ });+ return calls;+}++describe("GET /api/projects/:p/models/balance", () => {+ let t: TestApp;+ let owner: ReturnType<typeof apiClient>;+ let projectId: string;+ const tokenDanceRow = MODEL_CATALOG.find((m) => m.provider === "tokendance" && !m.retired)!;+ const balance = (provider: string, force = false) =>+ owner.get(+ `/api/projects/${projectId}/models/balance?provider=${provider}${force ? "&force=1" : ""}`,+ );+ /**+ * Narrows the table to one preset of each balance group and stores the given keys on them+ * (an omitted key keeps the stored one, as on the models page).+ */+ const storeKeys = async (keys: { tokendance?: string; deepseek?: string }) => {+ const res = await owner.put(`/api/projects/${projectId}/models`, {+ defaultModel: { provider: "deepseek", modelId: "deepseek-v4-pro" },+ models: [+ {+ provider: "tokendance",+ modelId: tokenDanceRow.modelId,+ ...(keys.tokendance !== undefined ? { apiKey: keys.tokendance } : {}),+ },+ {+ provider: "deepseek",+ modelId: "deepseek-v4-pro",+ ...(keys.deepseek !== undefined ? { apiKey: keys.deepseek } : {}),+ },+ ],+ });+ expect(res.status).toBe(200);+ };++ beforeEach(async () => {+ t = await createTestApp();+ const { cookie } = await provisionUser(t.app, "alice");+ owner = apiClient(t.app, cookie);+ const created = (await (+ await owner.post("/api/projects", { projectId: "alice-balance", name: "Balances" })+ ).json()) as ProjectCreateResponse;+ projectId = created.project.projectId;+ });+ afterEach(async () => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+ await t.cleanup();+ });++ it("TokenDance: reads balance.balance in micro-yuan as CNY yuan, asking with the group's stored key", async () => {+ await storeKeys({ tokendance: "sk-td-secret-0001" });+ const calls = stubVendors(() => json(200, TOKENDANCE_REPLY));+ const res = await balance("tokendance");+ expect(res.status).toBe(200);+ const text = await res.text();+ expect(text).not.toContain("sk-td-secret-0001");+ const body = JSON.parse(text) as ModelBalanceResponse;+ expect(body).toMatchObject({+ ok: true,+ provider: "tokendance",+ amount: "0.162811",+ currency: "CNY",+ });+ expect(Date.parse(body.fetchedAt)).not.toBeNaN();+ expect(calls).toEqual([{ url: TOKENDANCE_URL, authorization: "Bearer sk-td-secret-0001" }]);+ });++ it("DeepSeek: the first currency is the headline, the others ride along, is_available passes through", async () => {+ await storeKeys({ deepseek: "sk-ds-secret-0002" });+ const calls = stubVendors(() => json(200, DEEPSEEK_REPLY));+ const body = (await (await balance("deepseek")).json()) as ModelBalanceResponse;+ expect(body).toMatchObject({+ ok: true,+ provider: "deepseek",+ amount: "110.00",+ currency: "CNY",+ available: true,+ others: [{ amount: "5.00", currency: "USD" }],+ });+ expect(calls).toEqual([{ url: DEEPSEEK_URL, authorization: "Bearer sk-ds-secret-0002" }]);+ });++ it("a group with no stored key answers no_key, and nobody is called", async () => {+ const calls = stubVendors(() => json(200, TOKENDANCE_REPLY));+ const res = await balance("tokendance");+ expect(res.status).toBe(200);+ expect(await res.json()).toMatchObject({ ok: false, provider: "tokendance", error: "no_key" });+ expect(calls).toEqual([]);+ });++ it("DeepSeek with no stored key asks with DEEPSEEK_API_KEY, the key a Session on its rows would use", async () => {+ vi.stubEnv("DEEPSEEK_API_KEY", "sk-ds-env-0003");+ await storeKeys({});+ const calls = stubVendors(() => json(200, DEEPSEEK_REPLY));+ const res = await balance("deepseek");+ expect(res.status).toBe(200);+ const text = await res.text();+ expect(text).not.toContain("sk-ds-env-0003");+ expect(JSON.parse(text)).toMatchObject({ ok: true, provider: "deepseek", amount: "110.00" });+ expect(calls).toEqual([{ url: DEEPSEEK_URL, authorization: "Bearer sk-ds-env-0003" }]);+ });++ it("TokenDance is a gateway: the environment lends its rows nothing, so no stored key is no_key", async () => {+ vi.stubEnv("OPENAI_API_KEY", "sk-openai-env-0004");+ vi.stubEnv("DEEPSEEK_API_KEY", "sk-ds-env-0003");+ await storeKeys({});+ const calls = stubVendors(() => json(200, TOKENDANCE_REPLY));+ expect(await (await balance("tokendance")).json()).toMatchObject({+ ok: false,+ provider: "tokendance",+ error: "no_key",+ });+ expect(calls).toEqual([]);+ });++ it("lends only a variable the group's rows use on this vendor's own host", async () => {+ // A DeepSeek-group row on the OpenAI protocol with no base URL talks to api.openai.com, so+ // a Session there reads OPENAI_API_KEY. That key must not reach DeepSeek's balance endpoint,+ // and DEEPSEEK_API_KEY, which none of the group's rows would read, is not read either.+ vi.stubEnv("OPENAI_API_KEY", "sk-openai-env-0004");+ vi.stubEnv("DEEPSEEK_API_KEY", "sk-ds-env-0003");+ const toml = [+ "[[models]]",+ 'provider = "deepseek"',+ 'model_id = "deepseek-v4-pro"',+ 'client_type = "openai-chat"',+ "",+ ];+ await writeFile(path.join(t.root, projectId, ".project_config.toml"), toml.join("\n"), "utf8");+ const calls = stubVendors(() => json(200, DEEPSEEK_REPLY));+ expect(await (await balance("deepseek")).json()).toMatchObject({+ ok: false,+ provider: "deepseek",+ error: "no_key",+ });+ expect(calls).toEqual([]);+ });++ it("a group without a balance endpoint answers unsupported; a missing provider is a bad request", async () => {+ await storeKeys({ tokendance: "sk-td-secret-0001" });+ const calls = stubVendors(() => json(200, TOKENDANCE_REPLY));+ for (const provider of ["openrouter", "custom", "no-such-group"]) {+ expect(await (await balance(provider)).json(), provider).toMatchObject({+ ok: false,+ error: "unsupported",+ });+ }+ expect((await owner.get(`/api/projects/${projectId}/models/balance`)).status).toBe(400);+ expect(calls).toEqual([]);+ });++ it("a vendor failure is an answer, carrying the status and none of the vendor's text", async () => {+ await storeKeys({ tokendance: "sk-td-secret-0001", deepseek: "sk-ds-secret-0002" });+ stubVendors((url) =>+ url === DEEPSEEK_URL+ ? json(401, {+ error: { message: "Authentication Fails, Your api key: ****0002 is invalid" },+ })+ : json(200, { balance: { credits: 58000000 } }),+ );+ const refused = await balance("deepseek");+ expect(refused.status).toBe(200);+ const refusedText = await refused.text();+ expect(refusedText).not.toContain("Authentication Fails");+ expect(refusedText).not.toContain("0002");+ expect(JSON.parse(refusedText)).toMatchObject({+ ok: false,+ error: "upstream_failed",+ status: 401,+ });+ // A reply without the documented figure is a failure, never a zero.+ expect(await (await balance("tokendance")).json()).toMatchObject({+ ok: false,+ error: "upstream_failed",+ });++ vi.unstubAllGlobals();+ vi.stubGlobal("fetch", async () => {+ throw new TypeError("fetch failed");+ });+ expect(await (await balance("deepseek", true)).json()).toMatchObject({+ ok: false,+ error: "upstream_failed",+ });+ });++ it("answers from the cache for the same key, asks again on force or for a new key", async () => {+ await storeKeys({ tokendance: "sk-td-secret-0001" });+ const calls = stubVendors(() => json(200, TOKENDANCE_REPLY));+ const first = (await (await balance("tokendance")).json()) as ModelBalanceResponse;+ const second = (await (await balance("tokendance")).json()) as ModelBalanceResponse;+ expect(calls).toHaveLength(1);+ // The cached answer keeps the time it was read at.+ expect(second).toEqual(first);++ await balance("tokendance", true);+ expect(calls).toHaveLength(2);++ // A new authorization writes a new key: the old account's balance must not be served.+ await storeKeys({ tokendance: "sk-td-secret-0003" });+ await balance("tokendance");+ expect(calls).toHaveLength(3);+ expect(calls[2]!.authorization).toBe("Bearer sk-td-secret-0003");+ });++ it("any member may read a Project's balances; a stranger may not", async () => {+ await storeKeys({ tokendance: "sk-td-secret-0001" });+ stubVendors(() => json(200, TOKENDANCE_REPLY));+ const bob = await provisionUser(t.app, "bob");+ expect((await owner.post(`/api/projects/${projectId}/members`, { userId: "bob" })).status).toBe(+ 201,+ );+ const asBob = apiClient(t.app, bob.cookie);+ const read = await asBob.get(`/api/projects/${projectId}/models/balance?provider=tokendance`);+ expect(read.status).toBe(200);+ expect(await read.json()).toMatchObject({ ok: true, amount: "0.162811" });+ const carol = await provisionUser(t.app, "carol");+ const asCarol = apiClient(t.app, carol.cookie);+ const refused = await asCarol.get(+ `/api/projects/${projectId}/models/balance?provider=tokendance`,+ );+ expect(refused.status).toBe(404);+ });+});++describe("ModelBalances", () => {+ it("serves a cached answer for 60 s, then asks again", async () => {+ let now = 1_700_000_000_000;+ let calls = 0;+ const balances = new ModelBalances({+ groupKey: async () => "sk-td-secret-0001",+ fetchImpl: (async () => {+ calls += 1;+ return json(200, TOKENDANCE_REPLY);+ }) as unknown as typeof fetch,+ now: () => now,+ });+ await balances.read("p1", "tokendance");+ now += BALANCE_CACHE_MS - 1;+ await balances.read("p1", "tokendance");+ expect(calls).toBe(1);+ now += 1;+ await balances.read("p1", "tokendance");+ expect(calls).toBe(2);+ // Per Project: another Project's key is another account.+ await balances.read("p2", "tokendance");+ expect(calls).toBe(3);+ });++ it("shares one vendor call between readers asking at the same time", async () => {+ let calls = 0;+ let release: () => void = () => {};+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const balances = new ModelBalances({+ groupKey: async () => "sk-td-secret-0001",+ fetchImpl: (async () => {+ calls += 1;+ await gate;+ return json(200, TOKENDANCE_REPLY);+ }) as unknown as typeof fetch,+ });+ const both = Promise.all([+ balances.read("p1", "tokendance"),+ balances.read("p1", "tokendance"),+ ]);+ // Both reads have looked the key up and reached the vendor by now.+ await new Promise((resolve) => setTimeout(resolve, 0));+ release();+ const [a, b] = await both;+ expect(calls).toBe(1);+ expect(a).toEqual(b);+ });+});++describe("balance readers", () => {+ it("microToDecimal keeps every stated digit and writes at least two decimals", () => {+ expect(microToDecimal(162811)).toBe("0.162811");+ expect(microToDecimal(110_000_000)).toBe("110.00");+ expect(microToDecimal(1_500_000)).toBe("1.50");+ expect(microToDecimal(0)).toBe("0.00");+ expect(microToDecimal(-2_500_000)).toBe("-2.50");+ });++ it("TokenDance: balance.balance, as a number or a numeric string, with or without an envelope", () => {+ expect(readBalance("tokendance", TOKENDANCE_REPLY)).toEqual({+ amount: "0.162811",+ currency: "CNY",+ });+ expect(readBalance("tokendance", { data: { balance: { balance: "2000000" } } })).toEqual({+ amount: "2.00",+ currency: "CNY",+ });+ for (const body of [{}, { balance: 5 }, { balance: { balance: "lots" } }, null, "5"]) {+ expect(readBalance("tokendance", body), JSON.stringify(body)).toBeUndefined();+ }+ });++ it("DeepSeek: entries that are not a currency with a decimal amount are skipped, none left is a failure", () => {+ expect(+ readBalance("deepseek", {+ balance_infos: [+ { currency: "cny", total_balance: "1.00" },+ { currency: "USD", total_balance: "n/a" },+ { currency: "USD", total_balance: "7.25" },+ ],+ }),+ ).toEqual({ amount: "7.25", currency: "USD" });+ expect(readBalance("deepseek", { is_available: false, balance_infos: [] })).toBeUndefined();+ expect(readBalance("deepseek", { balance_infos: "none" })).toBeUndefined();+ });+});diff --git a/packages/server/test/models.test.ts b/packages/server/test/models.test.tsindex f62426e5..c46715f5 100644--- a/packages/server/test/models.test.ts+++ b/packages/server/test/models.test.ts@@ -69,6 +69,26 @@ const pairKey = (m: { provider: string; modelId: string }): string => `${m.proviconst pick = (body: ModelsResponse, provider: string, modelId: string) =>body.models.find((m) => m.provider === provider && m.modelId === modelId)!;+/**+ * Writes rows straight into a Project's config file, as a table saved before a rule existed+ * would hold them: rows a built-in group no longer takes from a PUT (see "model_not_addable")+ * are only ever reached this way.+ */+async function storeRows(+ root: string,+ projectId: string,+ rows: Array<{ provider: string; modelId: string; clientType?: string }>,+): Promise<void> {+ const toml = rows.flatMap((r) => [+ "[[models]]",+ `provider = "${r.provider}"`,+ `model_id = "${r.modelId}"`,+ ...(r.clientType !== undefined ? [`client_type = "${r.clientType}"`] : []),+ "",+ ]);+ await writeFile(path.join(root, projectId, ".project_config.toml"), toml.join("\n"), "utf8");+}+describe("models preset & catalog enrichment", () => {let t: TestApp;let api: ReturnType<typeof apiClient>;@@ -228,6 +248,11 @@ describe("models preset & catalog enrichment", () => {process.env.PENGUIN_GO_API_KEY = "sk-penguin-test-secret-value-456";// Empty counts as absent — it would not authenticate either.process.env.DEEPSEEK_API_KEY = "";+ // Two vendor-group rows no PUT may add any more, stored as a table from before would hold them.+ await storeRows(t.root, projectId, [+ { provider: "anthropic", modelId: "claude-sonnet-4-6-preview" },+ { provider: "anthropic", modelId: "claude-via-gateway", clientType: "openai" },+ ]);try {const put = await api.put(url(), {defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },@@ -320,6 +345,10 @@ describe("models preset & catalog enrichment", () => {});it("PUT a custom model: the vision flag persists; the openai protocol falls back to OPENAI_API_KEY; provider is required", async () => {+ // A vendor-group row on the openai protocol, as a group header's add once wrote it.+ await storeRows(t.root, projectId, [+ { provider: "anthropic", modelId: "claude-via-gateway", clientType: "openai" },+ ]);const put = await api.put(url(), {defaultModel: { provider: "custom", modelId: "my-model" },models: [@@ -452,6 +481,94 @@ describe("models preset & catalog enrichment", () => {expect(custom.status).toBe(200);});+ it("PUT refuses a new row that is no preset in a built-in group but custom and vLLM, and keeps every stored one", async () => {+ // A row a user added to a gateway group while gateways still took them.+ await storeRows(t.root, projectId, [+ { provider: "openrouter", modelId: "acme/legacy-pick", clientType: "openai-responses" },+ { provider: "custom", modelId: "mine", clientType: "openai-chat" },+ ]);+ const legacy = {+ provider: "openrouter",+ modelId: "acme/legacy-pick",+ clientType: "openai-responses",+ };+ const mine = { provider: "custom", modelId: "mine", clientType: "openai-chat" };++ // New in this request, in two gateways and in a vendor group — the last one an id the+ // vendor's client would route, so it is this rule and not routing that answers.+ for (const entry of [+ { provider: "openrouter", modelId: "acme/new-pick", clientType: "openai-responses" },+ { provider: "tokendance", modelId: "acme/new-pick", clientType: "openai-chat" },+ { provider: "deepseek", modelId: "deepseek-v4-my-tune" },+ ]) {+ const res = await api.put(url(), { models: [legacy, mine, entry] });+ expect(res.status, entry.provider).toBe(400);+ const error = ((await res.json()) as ErrorBody).error;+ expect(error.code, entry.provider).toBe("model_not_addable");+ expect(error.message).toContain(entry.modelId);+ expect(error.message).toContain("custom group");+ }++ // Moving a row in from another group is adding it to this one.+ const moved = await api.put(url(), {+ models: [+ legacy,+ {+ provider: "openrouter",+ modelId: "mine",+ clientType: "openai-responses",+ renamedFrom: { provider: "custom", modelId: "mine" },+ },+ ],+ });+ expect(moved.status).toBe(400);+ expect(((await moved.json()) as ErrorBody).error.code).toBe("model_not_addable");++ // Nothing above was written.+ const before = (await (await api.get(url())).json()) as ModelsResponse;+ expect(before.models.map(pairKey).sort()).toEqual(+ ["custom\0mine", "openrouter\0acme/legacy-pick"].sort(),+ );++ // The stored row keeps working: edited in place, then renamed inside its own group.+ const edited = await api.put(url(), { models: [{ ...legacy, contextWindow: 65536 }, mine] });+ expect(edited.status).toBe(200);+ const renamed = await api.put(url(), {+ models: [+ {+ provider: "openrouter",+ modelId: "acme/renamed-pick",+ clientType: "openai-responses",+ renamedFrom: { provider: "openrouter", modelId: "acme/legacy-pick" },+ },+ mine,+ ],+ });+ expect(renamed.status).toBe(200);+ const after = (await renamed.json()) as ModelsResponse;+ expect(after.models.map(pairKey).sort()).toEqual(+ ["custom\0mine", "openrouter\0acme/renamed-pick"].sort(),+ );++ // A group's own preset is welcome back, and custom, vLLM and user-defined groups take+ // anything.+ const open = await api.put(url(), {+ models: [+ { provider: "openrouter", modelId: "acme/renamed-pick", clientType: "openai-responses" },+ mine,+ { provider: "deepseek", modelId: "deepseek-v4-pro" },+ {+ provider: "vllm",+ modelId: "my-served-model",+ clientType: "openai-chat-vllm-adapter",+ baseUrl: "http://127.0.0.1:8000/v1",+ },+ { provider: "my-own-group", modelId: "anything", clientType: "openai-chat" },+ ],+ });+ expect(open.status).toBe(200);+ });+it('a config stored before the AgentHub 0.4.2 rename (client_type = "openai") keeps working: GET reports the canonical openai-chat', async () => {// Simulate an existing user config written by an older harness version: the deprecated// bare "openai" spelling on disk. Reading must not error and must report the canonical@@ -583,6 +700,10 @@ describe("models preset & catalog enrichment", () => {});it("the same model_id can coexist under different providers (paired keys, neither overwrites the other)", async () => {+ // The gateway's copy was added by hand, before gateways stopped taking such rows.+ await storeRows(t.root, projectId, [+ { provider: "siliconflow", modelId: "kimi-k2.6", clientType: "openai" },+ ]);const put = await api.put(url(), {models: [{ provider: "moonshot", modelId: "kimi-k2.6", apiKey: "sk-official-aaaa1111" },diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex 857ebc66..7e1e7bf3 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -55,6 +55,7 @@ import type {MeResponse,MessagesResponse,MessagingBindingsResponse,+ ModelBalanceResponse,ModelProtocolDetectResponse,ModelsResponse,ModelTestResponse,@@ -110,6 +111,8 @@ import type {WorkspaceFilesResponse,WorkspaceSearchResponse,} from "@prismshadow/penguin-server/api";+// The catalog decides which groups publish a balance, as it does on the server.+import { providerInfo } from "../../../../core/dist/state/model-catalog.js";import { READ_ONLY } from "./errors";import { dayKey } from "./fixtures";import type { UsageDay } from "./fixtures";@@ -355,6 +358,23 @@ router}return { defaultModel: ref };})+ .get("/api/projects/:projectId/models/balance", ({ store, query }): ModelBalanceResponse => {+ const provider = query.get("provider") ?? "";+ const fetchedAt = new Date().toISOString();+ const info = providerInfo(provider);+ if (info?.balance === undefined) {+ const message = `The ${provider} group publishes no balance.`;+ return { ok: false, provider, error: "unsupported", message, fetchedAt };+ }+ const keyed = store.f.models.models.some(+ (m) => m.provider === provider && m.credential?.apiKeyMasked,+ );+ if (!keyed) {+ const message = `The ${info.label} group stores no API key.`;+ return { ok: false, provider, error: "no_key", message, fetchedAt };+ }+ return { ok: true, provider, amount: "110.00", currency: "CNY", fetchedAt };+ }).post("/api/projects/:projectId/models/test", (): ModelTestResponse => ({ok: true,latencyMs: 640,diff --git a/packages/ui/src/components/shell/sidebar-frame/sidebar-frame.tsx b/packages/ui/src/components/shell/sidebar-frame/sidebar-frame.tsxindex a9888a0e..b08edd60 100644--- a/packages/ui/src/components/shell/sidebar-frame/sidebar-frame.tsx+++ b/packages/ui/src/components/shell/sidebar-frame/sidebar-frame.tsx@@ -444,6 +444,7 @@ export function SidebarSwitcherButton({export function SidebarAccountButton({avatar,name,+ trailing,role,expanded,onClick,@@ -452,6 +453,8 @@ export function SidebarAccountButton({}: {avatar: ReactNode;name: ReactNode;+ /** What the app shows after the name, which the name truncates before: a pinned balance. */+ trailing?: ReactNode;/** A short role after the name ("Admin"). */role?: string;/** The account menu is open. */@@ -474,6 +477,7 @@ export function SidebarAccountButton({>{avatar}<span className="min-w-0 flex-1 truncate font-sans text-sm font-medium">{name}</span>+ {trailing}{role !== undefined && <span className="text-xs text-fg-subtle">{role}</span>}</button>);diff --git a/packages/web/e2e/layout.spec.mjs b/packages/web/e2e/layout.spec.mjsindex 9dacb78a..5e43e42b 100644--- a/packages/web/e2e/layout.spec.mjs+++ b/packages/web/e2e/layout.spec.mjs@@ -103,7 +103,7 @@ test("layout: en draft + context gauge + mobile models", async ({ page }) => {pricing: { cacheRead: 1, cacheWrite: 5, output: 10 },},{ provider: "openai", modelId: "gpt-5.5", apiKey: "sk-mock2" },- { provider: "google", modelId: "gemini-3-pro" },+ { provider: "google", modelId: "gemini-3.1-pro-preview" },],},});@@ -274,25 +274,24 @@ test("models: group header actions collapse to icons instead of disappearing", a// The 900px viewport still renders the desktop sidebar, leaving only ~560px for a group// header. That is the issue #294 case: viewport breakpoints alone report plenty of room.- const openRouter = page.getByRole("button", { name: /OpenRouter \d+ 个模型/ });+ const openRouter = page.getByRole("button", { name: /OpenRouter\s*\d+ 个模型/ });await openRouter.waitFor();// Every group-level action, addressed by its accessible name (aria-label = "action vendor",// stable across widths). Narrow rows must never hide an action: it keeps its icon (with a- // title tooltip) and sheds only the visible text label.+ // tooltip) and sheds only the visible text label. OpenRouter carries its presets only, so its+ // header offers the group key and the speed test — the latter an icon at every width.const actions = [- { role: "button", name: "新增模型 OpenRouter", label: "新增模型" },- { role: "button", name: "统一配置 API key OpenRouter", label: "统一配置 API key" },- { role: "button", name: "测速 OpenRouter", label: "测速" },- { role: "link", name: "获取 API key OpenRouter", label: "获取 API key" },+ { name: "填写密钥 OpenRouter", label: "填写密钥" },+ { name: "测速 OpenRouter", label: null },];- // The expected label regime is derived from the row's measured width against the- // container thresholds — @3xl (48rem) admits the button labels, @4xl (56rem) the link- // label — because how wide the row is at a given viewport depends on the environment's- // root font size (the sidebar, page padding, viewport breakpoints and the thresholds are- // all rem-based). A row hugging a threshold (±16px) skips the label assertions; the- // coverage checks after the sweep guarantee both extreme regimes were exercised anyway.+ // The expected label regime is derived from the row's measured width against the @3xl+ // container threshold (48rem) that admits the labels, because how wide the row is at a+ // given viewport depends on the environment's root font size (the sidebar, page padding,+ // viewport breakpoints and the thresholds are all rem-based). A row hugging the threshold+ // (±16px) skips the label assertions; the coverage checks after the sweep guarantee both+ // regimes were exercised anyway.const seen = { iconOnly: false, fullyLabeled: false };for (const width of [390, 900, 1180, 1280, 1440, 1920]) {await page.setViewportSize({ width, height: 900 });@@ -306,31 +305,27 @@ test("models: group header actions collapse to icons instead of disappearing", a});const regime = (remThreshold) =>Math.abs(rowWidth - remThreshold * rem) <= 16 ? null : rowWidth >= remThreshold * rem;- const buttonLabels = regime(48);- const linkLabel = regime(56);- if (buttonLabels === false && linkLabel === false) seen.iconOnly = true;- if (buttonLabels === true && linkLabel === true) seen.fullyLabeled = true;-- for (const { role, name, label } of actions) {- const action = page.getByRole(role, { name });- await expect(action, `${label} action reachable @${width}`).toBeVisible();- await expect(action, `${label} action has a tooltip @${width}`).toHaveAttribute(- "title",- /.+/,- );- const expectLabel = role === "link" ? linkLabel : buttonLabels;- if (expectLabel === null) continue;- const text = action.locator("span", { hasText: label });+ const labels = regime(48);+ if (labels === false) seen.iconOnly = true;+ if (labels === true) seen.fullyLabeled = true;++ for (const { name, label } of actions) {+ const action = page.getByRole("button", { name });+ await expect(action, `${name} reachable @${width}`).toBeVisible();+ await expect(action, `${name} has a tooltip @${width}`).toHaveAttribute("data-tooltip", /.+/);const icon = action.locator("svg");- if (expectLabel) {+ if (label === null) {+ await expect(icon, `${name} icon shown @${width}`).toBeVisible();+ continue;+ }+ if (labels === null) continue;+ // A labelled action keeps its glyph and adds its words where the row has room.+ const text = action.locator("span", { hasText: label });+ await expect(icon, `${label} icon shown @${width}`).toBeVisible();+ if (labels) {await expect(text, `${label} label shown @${width}`).toBeVisible();- // The link swaps between glyph and text; the buttons keep their glyph alongside.- if (role === "link") {- await expect(icon, `${label} icon swapped out @${width}`).toBeHidden();- }} else {await expect(text, `${label} label hidden @${width}`).toBeHidden();- await expect(icon, `${label} icon shown @${width}`).toBeVisible();}}const metrics = await openRouter.locator("xpath=..").evaluate((header) => {@@ -533,7 +528,7 @@ test("layout: mobile chat dropdowns stay inside the viewport", async ({ page })modelId: "anthropic/claude-sonnet-4-5-thinking-preview",apiKey: "sk-mock3",},- { provider: "google", modelId: "gemini-3-pro" },+ { provider: "google", modelId: "gemini-3.1-pro-preview" },],},});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex fb566462..ae0fbaed 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -69,6 +69,7 @@ import type {MessagingBindingsResponse,MessagingChannel,MessagingTestMessageResponse,+ ModelBalanceResponse,ModelOAuthCodeResponse,ModelOAuthStartRequest,ModelOAuthStartResponse,@@ -402,6 +403,15 @@ export const putDefaultModel = (projectId: string, body: DefaultModelUpdateRequebody,});+/**+ * 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.+ */+export const getModelBalance = (projectId: string, provider: string, force = false) =>+ apiFetch<ModelBalanceResponse>(+ `/api/projects/${encodeURIComponent(projectId)}/models/balance?provider=${encodeURIComponent(provider)}${force ? "&force=1" : ""}`,+ );+/** Connectivity test: model reference (provider, modelId) is passed in the request body (may include an unsaved apiKey / baseUrl). */export const testModel = (projectId: string, body: ModelTestRequest) =>apiFetch<ModelTestResponse>(`/api/projects/${encodeURIComponent(projectId)}/models/test`, {diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex f8ad00df..be282dad 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -205,6 +205,7 @@ import type { DraftSessionEntry } from "../../features/chat/draft-sessions";import { prepareNewChatDraft } from "../../features/chat/new-chat";import { CreateProjectDialog, ProjectSettingsDialog } from "./project-dialogs";import { UserMenu } from "./user-menu";+import { PinnedBalanceBadge } from "../../features/models/group-balance";import { isCurrentPath, renderRouterLink } from "./router-link";import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";import { pendingScheduleSessions } from "../../features/schedules/schedule-panel-state";@@ -1958,6 +1959,7 @@ export function Sidebar({</UserAvatar>}name={user?.displayName ?? user?.userId}+ trailing={<PinnedBalanceBadge />}{...(user?.isAdmin ? { role: S.auth.admin } : {})}/>)}diff --git a/packages/web/src/features/models/balance.ts b/packages/web/src/features/models/balance.tsnew file mode 100644index 00000000..94364299--- /dev/null+++ b/packages/web/src/features/models/balance.ts@@ -0,0 +1,191 @@+/**+ * Group balances: the readings the models page shows in a group's header, and the one balance+ * pinned beside the user name in the sidebar.+ *+ * - **Readings** live in one module-level store keyed by Project and group, so both places+ * show the same value — a refresh clicked on the page updates the pinned copy too — and one+ * request in flight per key serves every reader asking at once. The server caches for 60 s+ * as well; a click asks it to skip that (`force`).+ * - **The pin** is stored per ACCOUNT, in `ui_prefs.pinnedBalance`, following the precedent of+ * `todoDismissed` (lib/todo-dismissals.ts): a user who pins a balance expects it wherever they+ * sign in, and on a shared machine another user must not inherit it. `PUT /me/prefs` merges+ * at the top level, so the field is always written whole; `null` is "nothing pinned". Until+ * the prefs arrive the pin reads as absent, so nothing appears and then vanishes.+ */+import { useEffect } from "react";+import { createStore } from "zustand/vanilla";+import { useStore } from "zustand/react";+import type {+ ModelBalanceAmount,+ ModelBalanceReading,+ ModelBalanceResponse,+ PinnedBalance,+} from "@prismshadow/penguin-server/api";+import * as api from "../../api/endpoints";+import { apiErrorText } from "../../lib/api-error";+import { formatMoney } from "../../lib/format";+import { USD_TO_CNY } from "../../state/theme";+import type { Currency } from "../../state/theme";++// —— Formatting (pure) ——++const CURRENCY_SYMBOL: Readonly<Record<string, string>> = { CNY: "¥", USD: "$" };++/** One amount as money is read: two decimals, the symbol where there is a common one ("¥110.00"), the code otherwise ("EUR 12.00"). */+export function formatAmount({ amount, currency }: ModelBalanceAmount): string {+ const value = Number(amount);+ const fixed = Number.isFinite(value) ? value.toFixed(2) : amount;+ const symbol = CURRENCY_SYMBOL[currency];+ return symbol !== undefined ? `${symbol}${fixed}` : `${currency} ${fixed}`;+}++/** Every currency a reading holds, the headline first, as the vendor states it: "¥110.00 · $5.00". */+export function formatBalance(reading: ModelBalanceReading): string {+ return [reading, ...(reading.others ?? [])].map(formatAmount).join(" · ");+}++/** US dollars per unit of the currencies the display currency switch covers, at the app's one fixed rate. */+const USD_PER_UNIT: Readonly<Record<string, number>> = { USD: 1, CNY: 1 / USD_TO_CNY };++/**+ * A reading in the display currency, as money is shown everywhere else in the app (formatMoney):+ * every amount the account holds is converted at the fixed rate and summed, so "¥110.00 ·+ * $5.00" reads "¥145" in yuan and "$20.71" in dollars. A currency the rate does not cover+ * leaves the reading in the vendor's own figures rather than guessing.+ */+export function displayBalance(reading: ModelBalanceReading, currency: Currency): string {+ let usd = 0;+ for (const part of [reading, ...(reading.others ?? [])]) {+ const value = Number(part.amount);+ const rate = USD_PER_UNIT[part.currency];+ if (rate === undefined || !Number.isFinite(value)) return formatBalance(reading);+ usd += value * rate;+ }+ return formatMoney(usd, currency);+}++// —— Readings ——++export interface BalanceState {+ /** A request is in flight; the previous answer, if any, stays on screen meanwhile. */+ loading: boolean;+ /** The server's last answer: a reading, or a typed reason there is none. */+ answer?: ModelBalanceResponse;+ /** The request itself failed (network, access), already worded for the tooltip. */+ requestError?: string;+}++const readingsStore = createStore<{ readings: Readonly<Record<string, BalanceState>> }>(() => ({+ readings: {},+}));++const inflight = new Map<string, Promise<void>>();++/** The newest request per key: an older one that lands after it (a refresh click overtook it) is dropped. */+const latest = new Map<string, number>();+let requestSeq = 0;++function readingKey(projectId: string, provider: string): string {+ return `${projectId}\u0000${provider}`;+}++function setReading(key: string, next: (prev: BalanceState | undefined) => BalanceState): void {+ const { readings } = readingsStore.getState();+ readingsStore.setState({ readings: { ...readings, [key]: next(readings[key]) } });+}++/**+ * Reads one group's balance into the store. A request already in flight for the same key is+ * joined rather than repeated — unless this one is a refresh click, which the in-flight one may+ * predate.+ */+export function requestBalance(projectId: string, provider: string, force = false): Promise<void> {+ const key = readingKey(projectId, provider);+ const pending = inflight.get(key);+ if (pending !== undefined && !force) return pending;+ setReading(key, (prev) => ({ ...prev, loading: true }));+ const mine = ++requestSeq;+ latest.set(key, mine);+ const call = api+ .getModelBalance(projectId, provider, force)+ .then((answer) => {+ if (latest.get(key) === mine) setReading(key, () => ({ loading: false, answer }));+ })+ .catch((error: unknown) => {+ if (latest.get(key) !== mine) return;+ setReading(key, (prev) => ({+ loading: false,+ ...(prev?.answer !== undefined ? { answer: prev.answer } : {}),+ requestError: apiErrorText(error),+ }));+ })+ .finally(() => {+ if (inflight.get(key) === call) inflight.delete(key);+ });+ inflight.set(key, call);+ return call;+}++/** Reactive read of one group's balance; undefined until something asked for it. */+export function useBalance(projectId: string | null, provider: string): BalanceState | undefined {+ return useStore(readingsStore, (s) =>+ projectId === null ? undefined : s.readings[readingKey(projectId, provider)],+ );+}++// —— The pin ——++/** The `ui_prefs` key the pin is stored under. */+export const PINNED_BALANCE_PREFS_KEY = "pinnedBalance";++/** The stored pin, or null for anything that is not one (absent, cleared, or malformed). */+export function parsePinnedBalance(raw: unknown): PinnedBalance | null {+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;+ const { projectId, provider } = raw as Record<string, unknown>;+ if (typeof projectId !== "string" || projectId === "") return null;+ if (typeof provider !== "string" || provider === "") return null;+ return { projectId, provider };+}++/** Whether a pin names this Project's group. */+export function isPinned(pin: PinnedBalance | null, projectId: string, provider: string): boolean {+ return pin !== null && pin.projectId === projectId && pin.provider === provider;+}++/** `undefined` until the prefs have been read; `null` when nothing is pinned. */+const pinStore = createStore<{ pin: PinnedBalance | null | undefined }>(() => ({ pin: undefined }));++let hydrating = false;++function hydratePin(): void {+ if (hydrating || pinStore.getState().pin !== undefined) return;+ hydrating = true;+ void api+ .getPrefs()+ .then(({ prefs }) => {+ // A pin set in this tab while the read was in flight is newer than what it read.+ if (pinStore.getState().pin === undefined) {+ pinStore.setState({ pin: parsePinnedBalance(prefs[PINNED_BALANCE_PREFS_KEY]) });+ }+ })+ .catch(() => {+ // Left unread so a later mount retries; showing no pin meanwhile is the quiet direction.+ hydrating = false;+ });+}++/**+ * The pinned balance, or null while nothing is pinned or the prefs are still unread. Every+ * caller reads the prefs once per page load at most.+ */+export function usePinnedBalance(): PinnedBalance | null {+ useEffect(() => hydratePin(), []);+ return useStore(pinStore, (s) => s.pin ?? null);+}++/** Pins one balance beside the user name, replacing any other, or clears the pin (null). */+export function setPinnedBalance(pin: PinnedBalance | null): void {+ pinStore.setState({ pin });+ // Fire-and-forget, like the other per-account markers: a lost write costs persistence only.+ void api.putPrefs({ [PINNED_BALANCE_PREFS_KEY]: pin }).catch(() => undefined);+}diff --git a/packages/web/src/features/models/group-balance.tsx b/packages/web/src/features/models/group-balance.tsxnew file mode 100644index 00000000..4212cef4--- /dev/null+++ b/packages/web/src/features/models/group-balance.tsx@@ -0,0 +1,176 @@+/**+ * A group's balance where it is shown: in its header on the models page — muted, after the pin+ * that puts it beside the user name and the refresh — and there, in the sidebar's user row.+ * Both read the one store in balance.ts, and both show the amount in the display currency the+ * cost center and the model prices use.+ *+ * The amount is plain text, and the refresh before it is a glyph: the shared tooltip only+ * speaks for an element with no words of its own (tooltip.tsx), so the glyph is what carries+ * the vendor's own figures and the read time — or, when no balance could be read, the reason.+ * A balance that cannot be read is a muted dash with that reason, never red text: it is+ * information about an account, not an error the user made on this page.+ */+import { useEffect } from "react";+import type { ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";+import { providerInfo } from "@prismshadow/penguin-core/model-catalog";+import { GlyphIcon, ICONS, ICON_SIZE, IconButton, ProviderLogo } from "@prismshadow/penguin-ui";+import { S } from "../../lib/strings";+import { formatDateTime } from "../../lib/format";+import { useProject } from "../../state/project";+import { useTheme } from "../../state/theme";+import type { Currency } from "../../state/theme";+import {+ displayBalance,+ formatBalance,+ isPinned,+ requestBalance,+ setPinnedBalance,+ useBalance,+ usePinnedBalance,+} from "./balance";+import type { BalanceState } from "./balance";+import { HEADER_SQUARE, HEADER_TEXT } from "./group-header";++/** How often the pinned balance is read again while the app is open (plus once per page load). */+export const PINNED_BALANCE_REFRESH_MS = 5 * 60 * 1000;++/**+ * What a balance reads as: the text shown — the amount in the display currency — and the+ * sentence behind it (the refresh glyph's hint and the accessible name), which keeps the+ * vendor's own figures and the time they were read.+ */+export function balanceView(+ state: BalanceState | undefined,+ label: string,+ currency: Currency,+): { text: string; title: string } {+ const answer = state?.answer;+ if (answer === undefined) {+ if (state?.requestError !== undefined) return { text: "—", title: state.requestError };+ // Nothing read yet: a quiet placeholder, not a dash, which would claim a failure.+ return { text: "…", title: S.models.balanceTitle(label, "…", "…") };+ }+ if (answer.ok) {+ const title = S.models.balanceTitle(+ label,+ formatBalance(answer),+ formatDateTime(answer.fetchedAt),+ );+ return {+ text: displayBalance(answer, currency),+ title: answer.available === false ? `${title} · ${S.models.balanceUnavailable}` : title,+ };+ }+ const reason = S.models.balanceErrors[answer.error] ?? answer.message;+ return {+ text: "—",+ title:+ answer.status !== undefined ? `${reason}${S.models.balanceStatus(answer.status)}` : reason,+ };+}++/**+ * The pin before a balance, which keeps it beside the user name: the session list's group pin+ * glyph, drawn filled while on. The accessible name stays static and `aria-pressed` carries+ * the state, as that pin's does.+ */+function BalancePin({ pinned, onToggle }: { pinned: boolean; onToggle: () => void }) {+ return (+ <IconButton+ variant="ghost"+ className={HEADER_SQUARE}+ label={S.models.pinBalance}+ title={pinned ? S.models.unpinBalance : S.models.pinBalance}+ aria-pressed={pinned}+ onClick={onToggle}+ >+ <GlyphIcon d={ICONS.pin} size={ICON_SIZE.groupHeaderAction} filled={pinned} />+ </IconButton>+ );+}++/**+ * A group's balance in its header: the pin, the refresh, then the amount, in the header's one+ * box and gap (group-header.ts). Read once when the header mounts, again on every refresh+ * click, which skips the server's cache.+ */+export function GroupBalance({+ projectId,+ provider,+}: {+ projectId: string;+ provider: ModelProviderInfo;+}) {+ const state = useBalance(projectId, provider.id);+ const pinned = isPinned(usePinnedBalance(), projectId, provider.id);+ const { currency } = useTheme();+ useEffect(() => {+ void requestBalance(projectId, provider.id);+ }, [projectId, provider.id]);+ const { text, title } = balanceView(state, provider.label, currency);+ const hint = `${title} · ${S.models.balanceRefreshHint}`;+ return (+ <span className="flex shrink-0 items-center gap-2">+ <BalancePin+ pinned={pinned}+ onToggle={() => setPinnedBalance(pinned ? null : { projectId, provider: provider.id })}+ />+ <IconButton+ variant="ghost"+ className={HEADER_SQUARE}+ label={hint}+ onClick={() => void requestBalance(projectId, provider.id, true)}+ >+ <GlyphIcon d={ICONS.refresh} size={ICON_SIZE.groupHeaderAction} />+ </IconButton>+ <span+ className={`${HEADER_TEXT} whitespace-nowrap tabular-nums text-gray-500 dark:text-gray-400${state?.loading === true && state.answer !== undefined ? " opacity-60" : ""}`}+ >+ {text}+ </span>+ </span>+ );+}++/**+ * The pinned balance as the sidebar shows it, or null when nothing is pinned or the pinned+ * Project is no longer one this user can open. Reads it when mounted — once per page load —+ * and every five minutes after that; never faster.+ */+export function usePinnedBalanceView(): { provider: string; text: string; title: string } | null {+ const pin = usePinnedBalance();+ const { projects } = useProject();+ const { currency } = useTheme();+ const reachable = pin !== null && projects.some((p) => p.projectId === pin.projectId);+ const projectId = reachable ? pin.projectId : null;+ const provider = pin?.provider ?? "";+ const state = useBalance(projectId, provider);+ useEffect(() => {+ if (projectId === null) return;+ void requestBalance(projectId, provider);+ const timer = window.setInterval(+ () => void requestBalance(projectId, provider),+ PINNED_BALANCE_REFRESH_MS,+ );+ return () => window.clearInterval(timer);+ }, [projectId, provider]);+ if (projectId === null) return null;+ return { provider, ...balanceView(state, providerInfo(provider)?.label ?? provider, currency) };+}++/**+ * The pinned balance beside the user name: the group's logo and the amount, muted. It sits+ * inside the account menu's trigger, so it carries no hint of its own; the sentence behind it+ * is spoken with the trigger's name.+ */+export function PinnedBalanceBadge() {+ const view = usePinnedBalanceView();+ if (view === null) return null;+ return (+ <span className="flex shrink-0 items-center gap-1 text-xs tabular-nums text-gray-500 dark:text-gray-400">+ <ProviderLogo provider={view.provider} className="h-3.5 w-3.5 shrink-0" />+ {view.text}+ <span className="sr-only"> · {view.title}</span>+ </span>+ );+}diff --git a/packages/web/src/features/models/group-header.ts b/packages/web/src/features/models/group-header.tsnew file mode 100644index 00000000..a9c28789--- /dev/null+++ b/packages/web/src/features/models/group-header.ts@@ -0,0 +1,112 @@+/**+ * What a provider group's header offers on its right side, decided in one place so the models+ * page renders it and the tests pin it without a DOM.+ *+ * 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.+ */+import {+ MODEL_PROVIDERS,+ PENGUIN_GO_PROVIDER_ID,+ isAddableGroup,+} from "@prismshadow/penguin-core/model-catalog";+import type { ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";++/**+ * One box for everything on the header's right side, so its items share one height, one inset+ * and one centre line: Button's `icon` size insets its glyph by 1.5 on every side, the plain+ * items (the balance, the connection status) take the same inset, and the header's single gap-2+ * spaces them all. A label rides inside its button at its neighbours' text rung and gives way+ * on a narrow header.+ */+export const HEADER_BUTTON = "h-7 shrink-0";+export const HEADER_SQUARE = "h-7 w-7 shrink-0";+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";++/** A row as far as its key is concerned: a stored (masked) key, or one lent by the server's environment. */+export interface KeyedRowLike {+ credential?: { apiKeyMasked?: string } | undefined;+ /** The masked environment key the row falls back to (GET /models' preview); absent when none applies. */+ envKeyMasked?: string | undefined;+}++/** The group obtains its key through an authorization flow: TokenDance's own, or a bridged one. */+export function hasConnectFlow(provider: ModelProviderInfo): boolean {+ return provider.oauth !== undefined || provider.bridgeAuth !== undefined;+}++/**+ * Whether the group holds a stored key on any row — what "connected" means, however the key+ * got there (a connect flow, Enter key, or a key typed on one model).+ */+export function groupKeyStored(rows: readonly KeyedRowLike[]): boolean {+ return rows.some((row) => Boolean(row.credential?.apiKeyMasked));+}++/**+ * Whether a row's key comes from the server's environment — DeepSeek's DEEPSEEK_API_KEY, say,+ * which the credential rule lends only on the vendor's own endpoint. It does not make a group+ * "connected"; it does let the balance be read.+ */+export function groupKeyFromEnv(rows: readonly KeyedRowLike[]): boolean {+ return rows.some((row) => Boolean(row.envKeyMasked));+}++/** The status beside Connect, or null for a group that has no connect flow. */+export function connectionStatus(+ provider: ModelProviderInfo,+ rows: readonly KeyedRowLike[],+): "connected" | "notConnected" | null {+ if (!hasConnectFlow(provider)) return null;+ return groupKeyStored(rows) ? "connected" : "notConnected";+}++export interface GroupHeaderFacts {+ isOwner: boolean;+ /** The group holds a stored key (groupKeyStored). */+ keyStored: boolean;+ /** A row's key comes from the server's environment instead (groupKeyFromEnv). */+ keyFromEnv?: boolean;+ /**+ * This group's balance is the one pinned beside the user name. It keeps the balance in the+ * header even after the key is gone, so the pin can still be taken off where it was put on.+ */+ balancePinned: boolean;+}++/** The header's actions, in the order they stand. */+export function groupHeaderActions(+ provider: ModelProviderInfo,+ { isOwner, keyStored, keyFromEnv = false, balancePinned }: GroupHeaderFacts,+): GroupHeaderAction[] {+ const actions: GroupHeaderAction[] = [];+ // Without a key, stored or from the environment, there is nothing to ask the vendor with.+ if (provider.balance !== undefined && (keyStored || keyFromEnv || balancePinned)) {+ actions.push("balance");+ }+ if (hasConnectFlow(provider)) actions.push("connect");+ if (!isOwner) return actions;+ 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");+ 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.+ if (!MODEL_PROVIDERS.some((p) => p.id === provider.id)) actions.push("deleteGroup");+ return actions;+}++/**+ * Whether a divider follows the balance: it separates the account's figure from the group's+ * status and actions, so it stands only where the balance leads and something comes after it.+ */+export function dividerAfterBalance(actions: readonly GroupHeaderAction[]): boolean {+ return actions[0] === "balance" && actions.length > 1;+}diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsxindex 879f4efa..c17b2091 100644--- a/packages/web/src/features/models/models-page.tsx+++ b/packages/web/src/features/models/models-page.tsx@@ -9,22 +9,23 @@* to migrate the credential and pointers).** The list is purely for "finding a model": grouped by vendor (group header = logo + vendor- * name + count, collapsible), with one card per model within a group — the card shows only- * the display name + status badges (default / vision / proxy-read), while- * context, pricing, and key status are folded into a single line of small text. Clicking a- * card opens the config dialog (credentials, context, pricing, vision toggle, plus set as- * default / set as vision model / delete); the "add model" entry point lives in each group- * header (owner only) and reuses the same dialog — provider is pre-filled with that group;- * the protocol follows group semantics: a first-party vendor group doesn't persist- * client_type (AgentHub auto-routes by upstream id, with env fallback resolved live from the- * id), while custom / user-defined groups / gateways use a fixed OpenAI protocol, and- * gateways (OpenRouter / SiliconFlow / Qwen Token Plan) additionally pre-fill their endpoint- * base URL; the "get model id / API key" external links sit next to the corresponding- * input's label (shown in both add and edit dialogs). The group list ends with an "add- * group" action (user-defined groups share custom's semantics; the group appears once the- * first model saves successfully — groups are carried by the model entry's provider field,- * not persisted separately). The header also holds an owner-only "sync presets" action next- * to the search box (union-merge with the built-in catalog, see catalog-sync.ts).+ * name + count + the collapse chevron), with one card per model within a group — the card+ * shows only the display name + status badges (default / vision / fast / free / discount), while+ * context, pricing, and key status are folded into a single line of small text. Clicking a card opens the config dialog+ * (credentials, context, pricing, vision toggle, plus set as default / set as vision model /+ * delete). The group header's right side holds the group's actions in a fixed order+ * (group-header.ts): its balance (pin and refresh before the amount, a divider after it),+ * Connect with its status, Enter key, the speed test, and — on the groups that take+ * hand-added models (custom, vLLM, user-defined) — Add model, which reuses the same dialog+ * with that group pre-filled. The protocol follows group semantics: custom / user-defined+ * groups pick or detect it, a group that pins one (vLLM) hands it to every entry. The "get+ * model id / API key" external links sit next to the corresponding input's label in the+ * dialogs, never in the header. A TokenDance banner above the groups offers its connect flow+ * until the group holds a key. The group list ends with an "add group" action (user-defined+ * groups share custom's semantics; the group appears once the first model saves successfully —+ * groups are carried by the model entry's provider field, not persisted separately). The+ * header also holds an owner-only "sync presets" action next to the search box (union-merge+ * with the built-in catalog, see catalog-sync.ts).** Saving does a PUT full-table replace (models not present are deleted; an empty apiKey* means keep the existing value); only the owner can edit.@@ -89,7 +90,7 @@ import {canonicalClientType,catalogEntryFor,fastModeProtocol,- isVendorGroup,+ isAddableGroup,modelHomepageUrl,providerClientType,providerEnvFallbackKey,@@ -146,13 +147,27 @@ import { refreshProjectTodos } from "../../lib/use-project-todos";import { buildImportedRows } from "./group-import";import { tpsTone, ttftTone } from "./speed-test";import type { SpeedResult, SpeedTone } from "./speed-test";-import { toneInk } from "../../lib/tone";+import { toneDot, toneInk } from "../../lib/tone";import { KeyAuthDialog } from "./key-auth-dialog";import type { KeyAuthTexts } from "./key-auth-dialog";+import {+ HEADER_BUTTON,+ HEADER_LABEL,+ HEADER_SQUARE,+ HEADER_TEXT,+ dividerAfterBalance,+ groupHeaderActions,+ groupKeyFromEnv,+ groupKeyStored,+} from "./group-header";+import type { GroupHeaderAction } from "./group-header";+import { GroupBalance } from "./group-balance";+import { isPinned, usePinnedBalance } from "./balance";+import { TOKENDANCE_PROVIDER_ID, TokenDanceBanner } from "./tokendance-banner";/**- * The authorization flows a group's "authorize a key" dialog can run, keyed by the flow named- * in that group's catalog descriptor. Everything the two differ in lives here — the four+ * The authorization flows a group's Connect dialog can run, keyed by the flow named in that+ * group's catalog descriptor. Everything the two differ in lives here — the four* endpoint calls and the copy — because everything else about the dialog is shared, and a* group picks its entry by carrying `bridgeAuth` rather than by being named in this file.*/@@ -753,6 +768,15 @@ export function ModelsPage() {const [speedFor, setSpeedFor] = useState<string | null>(null);/** Group currently being speed-tested (provider id); tests run strictly one model at a time. */const [speedRunning, setSpeedRunning] = useState<string | null>(null);+ /**+ * The running test was asked to stop. A ref for the loop, which reads it between probes; the+ * state mirror disables the stop button meanwhile, since the probe in flight still has to+ * come back before the loop can see it.+ */+ const speedStopRef = useRef(false);+ const [speedStopping, setSpeedStopping] = useState(false);+ /** The balance pinned beside the user name, so its group's header keeps the pin to undo it. */+ const pinnedBalance = usePinnedBalance();const [rows, setRows] = useState<RowState[] | null>(null);const [defaultModel, setDefaultModel] = useState<ModelRefDto | undefined>(undefined);@@ -982,13 +1006,17 @@ export function ModelsPage() {* Group speed test: one real request per model, strictly sequential (concurrent probes* trip provider rate limits), each result written to the card as it lands. The* confirmation dialog (speedFor) has already warned about quota by the time this runs.+ * A stop takes effect between probes: the one in flight is not abandoned (its request is+ * already billed), its result lands like the others, and no further probe starts.*/const runSpeedTest = async (providerId: string) => {if (!projectId || !rows) return;const targets = rows.filter((r) => r.provider === providerId);+ speedStopRef.current = false;setSpeedRunning(providerId);try {for (const row of targets) {+ if (speedStopRef.current) break;const key = refMapKey(row.provider, row.modelId);setSpeedResults((prev) => new Map(prev).set(key, "pending"));try {@@ -1009,9 +1037,15 @@ export function ModelsPage() {}} finally {setSpeedRunning(null);+ setSpeedStopping(false);}};+ const stopSpeedTest = () => {+ speedStopRef.current = true;+ setSpeedStopping(true);+ };+/*** Import-mode landing from the add-group dialog: one table PUT with the appended rows,* then the new group is opened so the result is visible immediately. Returns persist's@@ -1091,10 +1125,10 @@ export function ModelsPage() {draggable: true,onDragStart: (e: ReactDragEvent) => {// dragstart fires AT the source node, so target === currentTarget exactly when- // the header row itself is what the browser picked up. The row also carries the- // provider's external key link, which is natively draggable: a drag begun there- // is a link drag, and claiming it would overwrite the link's payload and effect- // and turn a release over any other header into a silent reorder.+ // the header row itself is what the browser picked up. A drag begun on anything+ // inside it that is natively draggable (selected text, a link) belongs to that+ // element, and claiming it would overwrite its payload and effect and turn a+ // release over any other header into a silent reorder.if (e.target !== e.currentTarget) return;e.dataTransfer.setData(MODEL_GROUP_DRAG_MIME, key);e.dataTransfer.effectAllowed = "move" as const;@@ -1154,6 +1188,156 @@ export function ModelsPage() {const oauthFlow = oauthFor === null ? undefined : providerInfo(oauthFor)?.bridgeAuth?.flow;const oauthKeyAuth = oauthFlow === undefined ? null : KEY_AUTH[oauthFlow];+ /** TokenDance's rows, for the banner: shown while the group has models and none of them a key. */+ const tokenDanceRows = rows?.filter((row) => row.provider === TOKENDANCE_PROVIDER_ID) ?? [];+ const showTokenDanceBanner = tokenDanceRows.length > 0 && !groupKeyStored(tokenDanceRows);++ /**+ * One of a group header's actions (group-header.ts decides which, and in what order). Every+ * button keeps an accessible name of "action group" and a title; on a narrow header the ones+ * that carry words drop them and keep their icon.+ */+ const renderGroupAction = (+ group: (typeof groups)[number],+ action: GroupHeaderAction,+ keyStored: boolean,+ ): ReactNode => {+ const { provider } = group;+ switch (action) {+ case "balance":+ return <GroupBalance projectId={projectId} provider={provider} />;+ case "connect": {+ // The status is the group holding a stored key, however it got there; the button+ // runs the group's flow again once it does, for a fresh key or another account.+ const status = keyStored ? S.models.connectedStatus : S.models.notConnectedStatus;+ const verb = keyStored ? S.models.reconnect : S.models.oauthKey;+ return (+ <span className="flex shrink-0 items-center gap-2">+ <span+ data-tooltip={status}+ className={`${HEADER_TEXT} gap-1 whitespace-nowrap text-gray-500 dark:text-gray-400`}+ >+ <span+ aria-hidden+ className={`h-1.5 w-1.5 shrink-0 rounded-full ${keyStored ? toneDot.success : toneDot.muted}`}+ />+ {/* The words give way on a narrow header; the dot and its tooltip stay. */}+ <span className="sr-only @2xl:not-sr-only">{status}</span>+ </span>+ {isOwner && (+ <Button+ size="icon"+ variant="ghost"+ className={HEADER_BUTTON}+ disabled={busy}+ aria-label={`${verb} ${provider.label}`}+ title={verb}+ onClick={() => {+ keyLanded.current = false;+ setOauthFor(group.provider.id);+ }}+ >+ <GlyphIcon d={ICONS.chainLink} size={ICON_SIZE.groupHeaderAction} />+ <span className={HEADER_LABEL}>{verb}</span>+ </Button>+ )}+ </span>+ );+ }+ case "platformSync":+ // A stored Penguin Go key enables catalog refresh, but connecting stays a separate+ // action so the owner can replace the key with another account's.+ return (+ <Button+ size="icon"+ variant="ghost"+ className={HEADER_BUTTON}+ disabled={busy}+ aria-label={`${S.models.platformSync} ${provider.label}`}+ title={S.models.platformSync}+ onClick={() => void syncPlatformModels()}+ >+ <GlyphIcon d={ICONS.rotateCw} size={ICON_SIZE.groupHeaderAction} />+ <span className={HEADER_LABEL}>{S.models.platformSync}</span>+ </Button>+ );+ case "groupKey":+ // One key written across the whole group, overwriting what each row holds; a single+ // model still takes its own in the model dialog.+ return (+ <Button+ size="icon"+ variant="ghost"+ className={HEADER_BUTTON}+ disabled={busy}+ aria-label={`${S.models.groupApiKey} ${provider.label}`}+ title={S.models.groupApiKey}+ onClick={() => setGroupKeyFor(group.provider.id)}+ >+ <GlyphIcon d={ICONS.key} size={ICON_SIZE.groupHeaderAction} />+ <span className={HEADER_LABEL}>{S.models.groupApiKey}</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+ // a circle. Every other group's waits its turn.+ const running = speedRunning === group.provider.id;+ const verb = running ? S.models.speedTestStop : S.models.speedTest;+ return (+ <Button+ size="icon"+ variant="ghost"+ className={HEADER_SQUARE}+ disabled={busy || (running ? speedStopping : speedRunning !== null)}+ aria-label={`${verb} ${provider.label}`}+ title={verb}+ onClick={() => (running ? stopSpeedTest() : setSpeedFor(group.provider.id))}+ >+ <GlyphIcon+ d={running ? ICONS.stopCircle : GAUGE_ICON}+ size={ICON_SIZE.groupHeaderAction}+ />+ </Button>+ );+ }+ case "addModel":+ // Only the groups that take hand-added models: custom, vLLM and user-defined ones. The+ // rest carry the catalog's presets, which the server enforces too (model_not_addable).+ return (+ <Button+ size="icon"+ variant="ghost"+ className={HEADER_BUTTON}+ disabled={busy}+ aria-label={`${S.models.addToGroup} ${provider.label}`}+ title={S.models.addToGroup}+ onClick={() => setAddingTo(group.provider.id)}+ >+ <GlyphIcon d={ICONS.plus} size={ICON_SIZE.groupHeaderAction} />+ <span className={HEADER_LABEL}>{S.models.addToGroup}</span>+ </Button>+ );+ case "deleteGroup":+ // Whole-group delete, user-defined groups only: a built-in group is catalog identity+ // (its rows delete one by one), a user-defined group exists solely through its rows.+ return (+ <Button+ size="icon"+ variant="ghost"+ className={HEADER_BUTTON}+ disabled={busy}+ aria-label={`${S.models.deleteGroup} ${provider.label}`}+ title={S.models.deleteGroup}+ onClick={() => setDeleteGroupFor(group.provider.id)}+ >+ <GlyphIcon d={ICONS.trash} size={ICON_SIZE.groupHeaderAction} />+ <span className={HEADER_LABEL}>{S.models.deleteGroup}</span>+ </Button>+ );+ }+ };+return (<PageFrame>{/* The header holds search, the owner-only "sync presets" action and the pair of create@@ -1230,6 +1414,17 @@ export function ModelsPage() {)}</PageHeader>+ {/* Above every group, while the TokenDance group has models but no key: its own connect+ flow, pitched as the way to skip setting keys by hand. */}+ {isOwner && showTokenDanceBanner && (+ <TokenDanceBanner+ onConnect={() => {+ keyLanded.current = false;+ setOauthFor(TOKENDANCE_PROVIDER_ID);+ }}+ />+ )}+{rows === null ? (<SkeletonList rows={4} />) : rows.length === 0 ? (@@ -1246,16 +1441,20 @@ export function ModelsPage() {{groups.map((group) => {const open = isGroupExpanded(expanded, group.provider.id, searching);const drag = groupDragProps(group.provider.id);- const platformAuthorized =- group.provider.id === PENGUIN_GO_PROVIDER_ID &&- group.rows.some((row) => Boolean(row.credential?.apiKeyMasked));+ const keyStored = groupKeyStored(group.rows);+ const actions = groupHeaderActions(group.provider, {+ isOwner,+ keyStored,+ keyFromEnv: groupKeyFromEnv(group.rows),+ balancePinned: isPinned(pinnedBalance, projectId, group.provider.id),+ });return (// The drop indicator is drawn against the WHOLE group, so "below" reads as// after this group and its model cards rather than between the header and// its own first card. It needs this wrapper to live in: the section clips// its children (overflow-hidden carries the expand/collapse transition).// Absolutely positioned, so it costs no layout width and cannot push the- // header's up-to-six actions out of a narrow page.+ // header's actions out of a narrow page.<div key={group.provider.id} className="relative">{drag.dropEdge !== null && (<div@@ -1266,43 +1465,48 @@ export function ModelsPage() {/>)}<section className="overflow-hidden rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">- {/* Group header: collapse button (logo + vendor name + count) + group-level- actions on the right. Actions are separate elements because buttons can't- nest. The row is a size container: the sidebar can narrow it while the- viewport remains desktop-sized, so action labels must respond to this- row's actual width rather than viewport breakpoints. Narrow rows never- hide an action — each one keeps its icon (with aria-label + title) and- only sheds its text label. The row is also the drag handle for- reordering the group (groupDragProps). */}+ {/* Group header: collapse button (logo + vendor name + count + chevron) ++ the group's actions on the right, in group-header.ts's order. Actions are+ separate elements because buttons can't nest. The row is a size+ container: the sidebar can narrow it while the viewport remains+ desktop-sized, so labels respond to this row's actual width rather than+ viewport breakpoints. Narrow rows never hide an action — each one keeps+ its icon (with aria-label + title) and only sheds its text. When even the+ icons leave the name too little room, the actions move to a line of their+ own below it, as one block (the name keeps a floor, so it is never+ squeezed to nothing). The row is also the drag handle for reordering the+ group (groupDragProps). */}<div{...drag.header}- className={`@container flex items-center gap-2 bg-gray-50 pr-2 transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900/60 dark:hover:bg-gray-800/60${canDrag && !searching ? " cursor-grab" : ""}`}+ className={`@container flex flex-wrap items-center gap-x-2 bg-gray-50 pr-1.5 transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900/60 dark:hover:bg-gray-800/60${canDrag && !searching ? " cursor-grab" : ""}`}><buttontype="button"aria-expanded={open}onClick={() => toggleGroup(group.provider.id)}- className="flex min-w-0 flex-1 items-center gap-2 px-3 py-2.5 text-left"+ className="flex min-w-[10rem] flex-1 items-center gap-2 px-3 py-2 text-left"><ProviderLogoprovider={group.provider.id}className="h-5 w-5 shrink-0 text-gray-700 dark:text-gray-300"/>- {/* The vendor name is the only thing in this row allowed to take the- remaining space, and the only one that truncates. Giving it a- minimum width is what made a narrow row overlap: the items beside- it never shrink, so once their widths plus that floor exceeded the- button, the whole group overflowed the box and ran under the- actions. The floor is gone; what gives way instead is the two marks- after it, which drop out on a narrow row (below, and the actions'- labels do the same at @3xl). The name then always has the leftovers- to itself and truncates inside them, so nothing can overlap. */}+ {/* The vendor name is the only thing in this button allowed to take+ the remaining space, and the only one that truncates. */}<span className="min-w-0 truncate text-sm font-semibold">{group.provider.label}</span>- <span className="hidden shrink-0 whitespace-nowrap font-mono text-xs text-gray-400 @xl:inline">- {S.models.modelCount(group.rows.length)}+ {/* The count as the model picker's rail writes it: a bare number, with+ the words kept for assistive tech. */}+ <span+ aria-hidden+ className="shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500"+ >+ {group.rows.length}</span>+ <span className="sr-only">{S.models.modelCount(group.rows.length)}</span>+ {/* The chevron follows the name and its count rather than the row's far+ edge, so it reads as part of the group it folds. */}+ <Chevron open={open} className="text-gray-400" />{/* The recommendation rides the collapse bar itself, so it is read withthe group's name rather than as a caption floating above thesection. `shrink-0` keeps it whole: the vendor name beside it is@@ -1312,9 +1516,8 @@ export function ModelsPage() {// endorsement is neither, which is the category tone.ts keeps out on// purpose. Unfilled, like the card marks below it: an outline// is enough to make it a pill, and a block of colour on the collapse- // bar competes with the vendor name it is endorsing. It holds on- // longer than the model count beside it and gives way before the- // name does.+ // bar competes with the vendor name it is endorsing. It gives way on+ // a narrow row before the name does.//// Gold, and the darker end of it: `yellow-700` (#a16207) is the last// rung that still clears 4.5:1 against this bar's gray-50 — 12px bold@@ -1328,150 +1531,23 @@ export function ModelsPage() {</span>)}</button>- {isOwner && platformAuthorized && (- // A stored Penguin Go key enables catalog refresh, but authorization remains- // a separate action so the owner can replace it with another account.- // Sync leads the group actions and sits immediately before Add model.- <Button- size="sm"- variant="ghost"- className="shrink-0"- disabled={busy}- aria-label={`${S.models.platformSync} ${group.provider.label}`}- title={S.models.platformSync}- onClick={() => void syncPlatformModels()}- >- <GlyphIcon d={ICONS.rotateCw} size={ICON_SIZE.groupHeaderAction} />- <span className="hidden @3xl:inline">{S.models.platformSync}</span>- </Button>- )}- {isOwner && !isVendorGroup(group.provider.id) && (- // Add-model entry point: on every group header whose group decides a- // protocol — custom, user-defined, and the gateways. A vendor group- // carries the built-in catalog and nothing else: it persists no- // client_type, so AgentHub places its entries by the model id alone- // and anything outside the catalog's ids cannot start. The way to add- // a model of one's own is a custom group, which has a protocol to- // pick. Narrow rows never hide a group action — they drop its label- // and keep the icon (same pattern for every action in this row), so- // the button stays reachable.- <Button- size="sm"- variant="ghost"- className="shrink-0"- disabled={busy}- aria-label={`${S.models.addToGroup} ${group.provider.label}`}- title={S.models.addToGroup}- onClick={() => setAddingTo(group.provider.id)}- >- <GlyphIcon d={ICONS.plus} size={ICON_SIZE.groupHeaderAction} />- <span className="hidden @3xl:inline">{S.models.addToGroup}</span>- </Button>- )}- {isOwner &&- (group.provider.oauth || group.provider.bridgeAuth !== undefined) && (- // Authorize-a-key action: rendered off the group's own catalog- // descriptor, so a provider gains this button by publishing a flow- // rather than by being named here — `oauth` for the ones whose PKCE- // round-trip the App runs itself, `bridgeAuth` for the ones an- // authorization bridge runs for it. Same narrow-row rule as its- // neighbours — the label goes, the icon and its names stay. It leads the- // manual key action: where a group can mint a key, that is the shorter path.- <Button- size="sm"- variant="ghost"- className="shrink-0"- disabled={busy}- aria-label={`${S.models.oauthKey} ${group.provider.label}`}- title={S.models.oauthKey}- onClick={() => setOauthFor(group.provider.id)}- >- <GlyphIcon d={SIGN_IN_ICON} size={ICON_SIZE.groupHeaderAction} />- <span className="hidden @3xl:inline">{S.models.oauthKey}</span>- </Button>- )}- {isOwner && group.provider.id !== "custom" && (- // Bulk key action: icon-only while this row is narrow, labeled from- // @3xl up. The button itself never disappears — aria-label + title- // carry the name while the visible label is dropped.- <Button- size="sm"- variant="ghost"- className="shrink-0"- disabled={busy}- aria-label={`${S.models.groupApiKey} ${group.provider.label}`}- title={S.models.groupApiKey}- onClick={() => setGroupKeyFor(group.provider.id)}- >- <GlyphIcon d={ICONS.key} size={ICON_SIZE.groupHeaderAction} />- <span className="hidden @3xl:inline">{S.models.groupApiKey}</span>- </Button>- )}- {isOwner && (- <Button- size="sm"- variant="ghost"- className="shrink-0"- disabled={busy || speedRunning !== null}- aria-label={`${S.models.speedTest} ${group.provider.label}`}- title={- speedRunning === group.provider.id- ? S.models.speedPending- : S.models.speedTest- }- onClick={() => setSpeedFor(group.provider.id)}- >- <GlyphIcon d={GAUGE_ICON} size={ICON_SIZE.groupHeaderAction} />- {/* Compact rows keep this accessible action icon-only. */}- <span className="hidden @3xl:inline">- {speedRunning === group.provider.id- ? S.models.speedPending- : S.models.speedTest}- </span>- </Button>- )}- {isOwner && !MODEL_PROVIDERS.some((p) => p.id === group.provider.id) && (- // Whole-group delete, user-defined groups only: a built-in group is- // catalog identity (its rows delete one by one), a user-defined group- // exists solely through its rows and can go as a unit.- <Button- size="sm"- variant="ghost"- className="shrink-0"- disabled={busy}- aria-label={`${S.models.deleteGroup} ${group.provider.label}`}- title={S.models.deleteGroup}- onClick={() => setDeleteGroupFor(group.provider.id)}- >- <GlyphIcon d={ICONS.trash} size={ICON_SIZE.groupHeaderAction} />- <span className="hidden @3xl:inline">{S.models.deleteGroup}</span>- </Button>- )}- {group.provider.apiKeyUrl && (- // External link: its label is the last one admitted as space grows- // (@4xl); below that only the link's external glyph is left, with a- // small padding bump for a usable touch target.- <Link- href={group.provider.apiKeyUrl}- external- variant="standalone"- aria-label={`${S.models.getApiKey} ${group.provider.label}`}- data-tooltip={S.models.getApiKey}- className="shrink-0 whitespace-nowrap p-1 text-xs @4xl:p-0"- >- <span className="hidden @4xl:inline">{S.models.getApiKey}</span>- </Link>+ {actions.length > 0 && (+ <div className="ml-auto flex shrink-0 items-center gap-2 py-1">+ {actions.map((action) => (+ <Fragment key={action}>+ {renderGroupAction(group, action, keyStored)}+ {/* A rule between the account's figure and the group's status and+ actions, drawn only when something follows the balance. */}+ {action === "balance" && dividerAfterBalance(actions) && (+ <span+ aria-hidden+ className="h-7 w-px shrink-0 bg-gray-300 dark:bg-gray-600"+ />+ )}+ </Fragment>+ ))}+ </div>)}- {/* Collapse arrow sits at the far right of the header (after group actions); it too can be clicked to collapse. */}- <button- type="button"- aria-expanded={open}- aria-label={group.provider.label}- onClick={() => toggleGroup(group.provider.id)}- className="shrink-0 p-1.5"- >- <Chevron open={open} className="text-gray-400" />- </button></div>{/* Expand/collapse: grid-template-rows goes between 0fr and 1fr, with the@@ -1480,7 +1556,7 @@ export function ModelsPage() {(and stills it under reduced motion). Content stays in the DOM whilecollapsed (height is 0), so both directions animate. The section keeps itsown head rather than being a CollapsibleSection: the head is the group's- drag handle and a size container, and its chevron trails the actions. */}+ drag handle and a size container, and its chevron follows the group's name. */}<divdata-layout-motionclassName={`grid ${open ? "grid-rows-[1fr]" : "grid-rows-[0fr]"}`}@@ -3008,7 +3084,14 @@ function ModelDialog({set({ provider, clientType: clientTypeAfterProviderChange(provider, form.clientType) });}}>- {MODEL_PROVIDERS.map((p) => (+ {/* Built-in groups: the ones that take hand-added models (custom, vLLM), and the+ group the row was loaded in — a row already in a gateway or vendor group may stay+ there, but no other row may be moved into one (the server refuses that as an+ addition, model_not_addable). The current value stays listed so it is valid. */}+ {MODEL_PROVIDERS.filter(+ (p) =>+ isAddableGroup(p.id) || p.id === row?.original?.provider || p.id === form.provider,+ ).map((p) => (<option key={p.id} value={p.id}>{p.label}</option>diff --git a/packages/web/src/features/models/tokendance-banner.tsx b/packages/web/src/features/models/tokendance-banner.tsxnew file mode 100644index 00000000..a6c9ea53--- /dev/null+++ b/packages/web/src/features/models/tokendance-banner.tsx@@ -0,0 +1,90 @@+/**+ * The banner above every group on the models page: TokenDance's own connect flow, offered as the+ * way to skip setting model keys by hand. The page shows it to the owner while the TokenDance+ * group has models and no stored key; once dismissed it stays hidden in this browser.+ *+ * Its slow highlight sweep is the one decoration on the page, asked for by name, and it crosses+ * the brand name only; the rest of the banner stands still. It is CSS only (`.banner-shimmer`+ * in styles.css), and the word's resting state is plain ink, so the global reduced-motion rule+ * leaves it plain.+ */+import { useState } from "react";+import { providerInfo } from "@prismshadow/penguin-core/model-catalog";+import { Button, CloseButton, ICON_GAP, ProviderLogo } from "@prismshadow/penguin-ui";+import { S } from "../../lib/strings";++/** The group the banner connects: it is TokenDance's by name, so it names the group too. */+export const TOKENDANCE_PROVIDER_ID = "tokendance";++/**+ * The banner's sentence split around the brand name, so the sweep can ride that word alone;+ * null when a wording does not carry the name, which then shows plain.+ */+export function splitBrand(text: string, brand: string): [before: string, after: string] | null {+ const at = brand === "" ? -1 : text.indexOf(brand);+ return at === -1 ? null : [text.slice(0, at), text.slice(at + brand.length)];+}++/** The localStorage key remembering the dismissal: a display preference of this browser. */+export const TOKENDANCE_BANNER_DISMISSED_KEY = "penguin.tokenDanceBannerDismissed";++/** Minimal storage surface; tests inject an in-memory one. */+export interface BannerStorage {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+}++/** Storage that is missing or refuses to answer reads as "not dismissed": the banner shows. */+export function bannerDismissed(storage?: BannerStorage): boolean {+ try {+ return (storage ?? localStorage).getItem(TOKENDANCE_BANNER_DISMISSED_KEY) === "1";+ } catch {+ return false;+ }+}++function rememberDismissal(): void {+ try {+ localStorage.setItem(TOKENDANCE_BANNER_DISMISSED_KEY, "1");+ } catch {+ // The banner still goes away for this page view; only the memory of it is lost.+ }+}++export function TokenDanceBanner({ onConnect }: { onConnect: () => void }) {+ const [dismissed, setDismissed] = useState(() => bannerDismissed());+ if (dismissed) return null;+ const brand = providerInfo(TOKENDANCE_PROVIDER_ID)?.label ?? "TokenDance";+ const parts = splitBrand(S.models.tokenDanceBanner, brand);+ return (+ <div+ className={`mb-3 flex items-center ${ICON_GAP.card} rounded-md border border-gray-200 bg-gray-100 py-2.5 pl-3.5 pr-2 dark:border-gray-800 dark:bg-gray-900`}+ >+ <ProviderLogo+ provider="tokendance"+ className="h-6 w-6 shrink-0 text-gray-900 dark:text-gray-100"+ />+ <p className="min-w-0 flex-1 text-sm text-gray-700 dark:text-gray-300">+ {parts === null ? (+ S.models.tokenDanceBanner+ ) : (+ <>+ {parts[0]}+ <span className="banner-shimmer">{brand}</span>+ {parts[1]}+ </>+ )}+ </p>+ <Button size="sm" variant="primary" className="shrink-0" onClick={onConnect}>+ {S.models.oauthKey}+ </Button>+ <CloseButton+ className="shrink-0"+ onClose={() => {+ rememberDismissal();+ setDismissed(true);+ }}+ />+ </div>+ );+}diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.tsindex 0ea39796..c059c7dc 100644--- a/packages/web/src/lib/install-scope.ts+++ b/packages/web/src/lib/install-scope.ts@@ -337,6 +337,12 @@ export const KEY_RULES: readonly KeyRule[] = [scope: "browser",why: "That company mode's beta notice has been shown in this browser; it names nothing on the server, and a wipe is not a request to show it again.",},+ {+ kind: "exact",+ key: "penguin.tokenDanceBannerDismissed",+ scope: "browser",+ why: "That the models page's TokenDance banner was dismissed in this browser; it names nothing on the server, and a wipe is not a request to show it again.",+ },{kind: "exact",key: "penguin.lastOrgKey",diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 3464ed63..57b43480 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1409,9 +1409,9 @@ export const en: Strings = {{key: "openrouter",label: "OpenRouter's popular models",- description: "Reads the listing page, adds one group",+ description: "Reads the listing page, adds a group of your own",prompt:- "Add the popular models on https://openrouter.ai/models as an OpenRouter group (ask me for the API key first).",+ "Add the popular models on https://openrouter.ai/models as a group of my own (ask me for the API key first).",},{key: "vllm",@@ -1448,6 +1448,8 @@ export const en: Strings = {platformSync: "Sync",homepage: "Model page",speedTest: "Speed test",+ /** The same icon button while its group's run is going: stops after the probe in flight. */+ speedTestStop: "Stop speed test",speedTestTitle: "Speed test",speedTestConfirm: (n: number): string =>`This sends one real request to each of the ${n} models in this group, one at a time, to measure time-to-first-token (TTFT) and output rate (TPS). It consumes a small amount of API quota. Continue?`,@@ -1571,14 +1573,42 @@ export const en: Strings = {confirmDeleteTitle: "Delete model",confirmDelete: (name: string): string =>`Delete "${name}"? Its configuration and API key will be removed.`,- groupApiKey: "Set key",+ groupApiKey: "Enter key",groupApiKeyTitle: (label: string): string => `Set the API key for ${label}`,groupApiKeyHint: (n: number): string =>`Applies to all ${n} models in this group; leave empty to keep them unchanged.`,getApiKey: "Manage keys",getModelIds: "Get model IDs",groupKeyApplied: (n: number): string => `API key set for ${n} models`,- oauthKey: "Authorize key",+ oauthKey: "Connect",+ /** The same button once the group holds a key: the flow again, for a fresh key or another account. */+ reconnect: "Reconnect",+ /** The small status beside it: whether the group holds a stored key, however that key got there. */+ connectedStatus: "Connected",+ notConnectedStatus: "Not connected",+ /**+ * A group's account balance in its header (and pinned beside the user name): the tooltip+ * names the group, the vendor's own figures and the time of the reading. `amounts` and+ * `time` are already formatted.+ */+ balanceTitle: (label: string, amounts: string, time: string): string =>+ `${label} balance ${amounts}, read at ${time}`,+ balanceRefreshHint: "Click to refresh",+ /** Added to the tooltip when the vendor says the account cannot make requests (DeepSeek's is_available). */+ balanceUnavailable: "The account cannot make requests right now; its balance may be too low",+ /** The tooltip of the muted dash shown when no balance could be read, by the server's code. */+ balanceErrors: {+ no_key: "This group has no API key to read its balance with",+ upstream_failed: "The provider returned no balance; click to try again",+ unsupported: "This group has no balance to read",+ } as Record<string, string | undefined>,+ /** Appended when the vendor answered with an HTTP error. */+ balanceStatus: (status: number): string => ` (the provider answered HTTP ${status})`,+ /** Pin toggle before a balance: keeps it beside the user name in the sidebar, one at a time. */+ pinBalance: "Pin beside your name",+ unpinBalance: "Unpin",+ /** The banner above every group: TokenDance's own connect flow, pitched as the way to skip keys. */+ tokenDanceBanner: "Connect your TokenDance wallet — no model keys to set by hand",oauthTitle: (label: string): string => `Authorize a new ${label} API key`,oauthIntro: (label: string, n: number): string =>`A new API key will be created on your ${label} account and written to all ${n} models in this group, replacing the key they use now.`,@@ -4766,6 +4796,8 @@ Scenarios:"This import would overwrite or delete memories. Confirm it to continue.",schedule_exists: "A scheduled task with this name already exists.",schedule_not_found: "This scheduled task no longer exists.",+ model_not_addable:+ "This group carries its built-in models only; add the model under a custom group.",model_not_routable:"This model ID cannot be routed by a vendor group's protocol. Vendor groups carry built-in models only — add the model under a custom group and pick or detect its protocol.",unknown_skill: "This skill is not in the selected directory.",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 0be11102..e994a575 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1444,9 +1444,9 @@ export const zh = {{key: "openrouter",label: "OpenRouter 热门模型",- description: "读取模型列表页,加为一个分组",+ description: "读取模型列表页,加为一个自建分组",prompt:- "把 https://openrouter.ai/models 上的热门模型加为一个 OpenRouter 分组(先问我要 API key)。",+ "把 https://openrouter.ai/models 上的热门模型加为一个自建分组(先问我要 API key)。",},{key: "vllm",@@ -1481,6 +1481,8 @@ export const zh = {platformSync: "同步",homepage: "模型主页",speedTest: "测速",+ /** The same icon button while its group's run is going: stops after the probe in flight. */+ speedTestStop: "停止测速",speedTestTitle: "分组测速",speedTestConfirm: (n: number): string =>`将对该分组的 ${n} 个模型逐个发起一次真实请求,测量首 token 延迟(TTFT)与输出速率(TPS),会消耗少量 API 额度。是否继续?`,@@ -1622,7 +1624,7 @@ export const zh = {confirmDeleteTitle: "删除模型",confirmDelete: (name: string): string =>`确定删除「${name}」?该模型的配置与 API key 将一并移除。`,- groupApiKey: "手动设置密钥",+ groupApiKey: "填写密钥",groupApiKeyTitle: (label: string): string => `为「${label}」统一配置 API key`,groupApiKeyHint: (n: number): string => `将写入该分组下全部 ${n} 个模型;留空不改动。`,getApiKey: "前往密钥管理",@@ -1630,7 +1632,35 @@ export const zh = {groupKeyApplied: (n: number): string => `已为 ${n} 个模型配置 API key`,// 供应商授权取 key(模型分组头部动作):整个 PKCE 流程都在服务端跑,前端只拿到一个// 不透明的 flow id 和状态。- oauthKey: "自动获取密钥",+ oauthKey: "连接",+ /** The same button once the group holds a key: the flow again, for a fresh key or another account. */+ reconnect: "重新连接",+ /** The small status beside it: whether the group holds a stored key, however that key got there. */+ connectedStatus: "连接成功",+ notConnectedStatus: "未连接",+ /**+ * A group's account balance in its header (and pinned beside the user name): the tooltip+ * names the group, the vendor's own figures and the time of the reading. `amounts` and+ * `time` are already formatted.+ */+ balanceTitle: (label: string, amounts: string, time: string): string =>+ `${label} 余额 ${amounts},查询于 ${time}`,+ balanceRefreshHint: "点击同步",+ /** Added to the tooltip when the vendor says the account cannot make requests (DeepSeek's is_available). */+ balanceUnavailable: "账户当前不可用,余额可能不足",+ /** The tooltip of the muted dash shown when no balance could be read, by the server's code. */+ balanceErrors: {+ no_key: "该分组没有可用的 API key,无法查询余额",+ upstream_failed: "服务商没有返回余额,可点击重试",+ unsupported: "该分组不支持查询余额",+ } as Record<string, string | undefined>,+ /** Appended when the vendor answered with an HTTP error. */+ balanceStatus: (status: number): string => `(服务商返回 HTTP ${status})`,+ /** Pin toggle before a balance: keeps it beside the user name in the sidebar, one at a time. */+ pinBalance: "常驻到用户名旁",+ unpinBalance: "取消常驻",+ /** The banner above every group: TokenDance's own connect flow, pitched as the way to skip keys. */+ tokenDanceBanner: "连接 TokenDance 钱包,无需手动配置模型密钥",oauthTitle: (label: string): string => `从「${label}」授权新建 API key`,oauthIntro: (label: string, n: number): string =>`将在你的 ${label} 账户下新建一个 API key,并写入该分组下全部 ${n} 个模型,覆盖它们当前的 key。`,@@ -4782,6 +4812,7 @@ Benchmark:memory_import_confirm_required: "本次导入会覆盖或删除已有记忆,请确认后继续。",schedule_exists: "已存在同名定时任务。",schedule_not_found: "该定时任务已不存在。",+ model_not_addable: "该分组只承载内置模型,不能再添加其他模型;请在自定义分组中添加。",model_not_routable:"该模型 ID 无法按厂商分组的协议路由。厂商分组只承载内置模型;请在自定义分组中添加该模型,并选择或检测其接口协议。",unknown_skill: "所选目录下没有这个技能。",diff --git a/packages/web/src/styles.css b/packages/web/src/styles.cssindex d5d0a1d6..62d78571 100644--- a/packages/web/src/styles.css+++ b/packages/web/src/styles.css@@ -348,6 +348,42 @@animation: browser-agent-ring 1.6s ease-in-out infinite;}+/* The models page's TokenDance banner (features/models/tokendance-banner.tsx): a slow highlight+ sweeps across the brand name alone every 6 s — the page's single decoration, asked for by+ name; the rest of the banner stands still. The word is painted by a gradient clipped to its+ glyphs: its own ink on both sides of a narrow bright band, three times the word's width. The+ band sweeps from before the word to past its end, and the word's own resting position shows+ ink only, so under the global `animation: none` below it is plain text. */+@keyframes banner-shimmer {+ 0% {+ background-position: 100% 0;+ }+ 30%,+ 100% {+ background-position: 0% 0;+ }+}+.banner-shimmer {+ --banner-ink: var(--color-gray-700);+ --banner-glow: var(--color-gray-300);+ background-image: linear-gradient(+ 100deg,+ var(--banner-ink) 42%,+ var(--banner-glow) 50%,+ var(--banner-ink) 58%+ );+ background-size: 300% 100%;+ background-position: 0% 0;+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ animation: banner-shimmer 6s ease-in-out infinite;+}+.dark .banner-shimmer {+ --banner-ink: var(--color-gray-300);+ --banner-glow: var(--color-white);+}+/* Login page circuit traces (login-circuit.tsx): pathLength=1 normalization, draw-in -> hold -> fade-outloop. Base state is fully hidden: the positive animation-delay wait keeps the first paint blank, andlines only start growing after load; once reduced-motion globally disables animation, the override belowdiff --git a/packages/web/test/model-balance.test.ts b/packages/web/test/model-balance.test.tsnew file mode 100644index 00000000..364a31f4--- /dev/null+++ b/packages/web/test/model-balance.test.ts@@ -0,0 +1,189 @@+/**+ * Group balances in the Web App: how an amount reads (balance.ts) — in the vendor's own figures+ * and in the display currency — what the header and the sidebar show for each state of a+ * reading (group-balance.tsx), how the per-account pin is read back out of the free-form prefs,+ * and the TokenDance banner: its per-browser dismissal, and a sweep that rides the brand name.+ */+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import type { ModelBalanceResponse } from "@prismshadow/penguin-server/api";+import {+ displayBalance,+ formatAmount,+ formatBalance,+ isPinned,+ parsePinnedBalance,+} from "../src/features/models/balance";+import { balanceView } from "../src/features/models/group-balance";+import {+ TOKENDANCE_BANNER_DISMISSED_KEY,+ TokenDanceBanner,+ bannerDismissed,+ splitBrand,+} from "../src/features/models/tokendance-banner";+import { S, zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";++const reading: ModelBalanceResponse = {+ ok: true,+ provider: "deepseek",+ amount: "110.00",+ currency: "CNY",+ others: [{ amount: "5", currency: "USD" }],+ fetchedAt: "2026-09-30T06:05:00.000Z",+};++describe("formatting an amount", () => {+ it("writes two decimals with the common symbol, or the code where there is none", () => {+ expect(formatAmount({ amount: "110.00", currency: "CNY" })).toBe("¥110.00");+ expect(formatAmount({ amount: "0.162811", currency: "CNY" })).toBe("¥0.16");+ expect(formatAmount({ amount: "5", currency: "USD" })).toBe("$5.00");+ expect(formatAmount({ amount: "12.5", currency: "EUR" })).toBe("EUR 12.50");+ });++ it("lists every currency a reading holds, the headline first", () => {+ expect(reading.ok && formatBalance(reading)).toBe("¥110.00 · $5.00");+ });+});++describe("a balance in the display currency", () => {+ const single = (amount: string, currency: string) =>+ ({ ok: true, provider: "tokendance", amount, currency, fetchedAt: reading.fetchedAt }) as const;++ it("converts at the app's fixed rate, as money is shown elsewhere", () => {+ expect(displayBalance(single("128.46", "CNY"), "CNY")).toBe("¥128");+ expect(displayBalance(single("128.46", "CNY"), "USD")).toBe("$18.35");+ expect(displayBalance(single("12.5", "USD"), "CNY")).toBe("¥87.50");+ expect(displayBalance(single("0.162811", "CNY"), "CNY")).toBe("¥0.1628");+ });++ it("sums every currency the account holds into one amount", () => {+ // ¥110 and $5: $15.71 + $5 in dollars, ¥110 + ¥35 in yuan.+ expect(reading.ok && displayBalance(reading, "USD")).toBe("$20.71");+ expect(reading.ok && displayBalance(reading, "CNY")).toBe("¥145");+ });++ it("keeps the vendor's own figures for a currency the rate does not cover", () => {+ expect(displayBalance(single("12.5", "EUR"), "CNY")).toBe("EUR 12.50");+ expect(displayBalance(single("n/a", "CNY"), "USD")).toBe("¥n/a");+ });+});++describe("what a balance reads as", () => {+ it("a reading: the amount in the display currency, the vendor's figures in the tooltip", () => {+ const view = balanceView({ loading: false, answer: reading }, "DeepSeek", "CNY");+ expect(view.text).toBe("¥145");+ expect(view.title).toContain("DeepSeek");+ expect(view.title).toContain("¥110.00 · $5.00");+ expect(view.title).not.toContain(S.models.balanceUnavailable);+ expect(balanceView({ loading: false, answer: reading }, "DeepSeek", "USD").text).toBe("$20.71");+ });++ it("an account the vendor says cannot make requests says so in the tooltip", () => {+ const view = balanceView(+ { loading: false, answer: { ...reading, available: false } },+ "DeepSeek",+ "CNY",+ );+ expect(view.title).toContain(S.models.balanceUnavailable);+ });++ it("no balance is a muted dash, the reason and the vendor's status in the tooltip", () => {+ const view = balanceView(+ {+ loading: false,+ answer: {+ ok: false,+ provider: "tokendance",+ error: "upstream_failed",+ status: 401,+ message: "TokenDance answered the balance request with HTTP 401.",+ fetchedAt: reading.fetchedAt,+ },+ },+ "TokenDance",+ "CNY",+ );+ expect(view.text).toBe("—");+ expect(view.title).toContain(S.models.balanceErrors.upstream_failed!);+ expect(view.title).toContain("401");+ });++ it("a request that failed outright is a dash too; nothing read yet is not", () => {+ expect(+ balanceView({ loading: false, requestError: "Network error" }, "TokenDance", "CNY"),+ ).toEqual({ text: "—", title: "Network error" });+ expect(balanceView(undefined, "TokenDance", "CNY").text).toBe("…");+ expect(balanceView({ loading: true }, "TokenDance", "USD").text).toBe("…");+ });+});++describe("the pinned balance", () => {+ it("reads a stored pin, and anything else as nothing pinned", () => {+ expect(parsePinnedBalance({ projectId: "p1", provider: "tokendance" })).toEqual({+ projectId: "p1",+ provider: "tokendance",+ });+ for (const raw of [+ undefined,+ null,+ "p1",+ [],+ {},+ { projectId: "p1" },+ { projectId: "", provider: "x" },+ ]) {+ expect(parsePinnedBalance(raw), JSON.stringify(raw)).toBeNull();+ }+ });++ it("names one Project's group: the same group in another Project is another balance", () => {+ const pin = { projectId: "p1", provider: "tokendance" };+ expect(isPinned(pin, "p1", "tokendance")).toBe(true);+ expect(isPinned(pin, "p2", "tokendance")).toBe(false);+ expect(isPinned(pin, "p1", "deepseek")).toBe(false);+ expect(isPinned(null, "p1", "tokendance")).toBe(false);+ });+});++describe("the TokenDance banner's dismissal", () => {+ it("is remembered per browser under its own key", () => {+ const store = new Map<string, string>();+ const storage = {+ getItem: (key: string) => store.get(key) ?? null,+ setItem: (key: string, value: string) => void store.set(key, value),+ };+ expect(bannerDismissed(storage)).toBe(false);+ storage.setItem(TOKENDANCE_BANNER_DISMISSED_KEY, "1");+ expect(bannerDismissed(storage)).toBe(true);+ });++ it("a storage that refuses to answer shows the banner rather than failing", () => {+ const broken = {+ getItem: (): string | null => {+ throw new Error("denied");+ },+ setItem: () => undefined,+ };+ expect(bannerDismissed(broken)).toBe(false);+ });+});++describe("the TokenDance banner's sweep", () => {+ it("rides the brand name alone, in both languages", () => {+ for (const text of [zh.models.tokenDanceBanner, en.models.tokenDanceBanner]) {+ const parts = splitBrand(text, "TokenDance");+ expect(parts, text).not.toBeNull();+ expect(`${parts![0]}TokenDance${parts![1]}`).toBe(text);+ }+ const html = renderToStaticMarkup(createElement(TokenDanceBanner, { onConnect: () => {} }));+ expect(html.match(/banner-shimmer/g)).toHaveLength(1);+ expect(html).toContain('<span class="banner-shimmer">TokenDance</span>');+ });++ it("leaves a wording without the name plain", () => {+ expect(splitBrand("Connect your wallet", "TokenDance")).toBeNull();+ expect(splitBrand("TokenDance", "")).toBeNull();+ });+});diff --git a/packages/web/test/model-group-header.test.ts b/packages/web/test/model-group-header.test.tsnew file mode 100644index 00000000..4443407d--- /dev/null+++ b/packages/web/test/model-group-header.test.ts@@ -0,0 +1,149 @@+/**+ * A provider group's header on the models page (group-header.ts): which actions each kind of+ * group offers, in the order they stand, and the connection status of a group whose key comes+ * from an authorization flow.+ *+ * 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.+ */+import { describe, expect, it } from "vitest";+import { MODEL_PROVIDERS, providerInfo } from "@prismshadow/penguin-core/model-catalog";+import type { ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";+import {+ connectionStatus,+ dividerAfterBalance,+ groupHeaderActions,+ groupKeyFromEnv,+ groupKeyStored,+ hasConnectFlow,+} from "../src/features/models/group-header";+import { userProviderInfo } from "../src/features/models/model-grouping";++const group = (id: string): ModelProviderInfo => providerInfo(id) ?? userProviderInfo(id);+const owner = (id: string, keyStored = false, balancePinned = false) =>+ groupHeaderActions(group(id), { isOwner: true, keyStored, balancePinned });+const member = (id: string, keyStored = false, balancePinned = false) =>+ groupHeaderActions(group(id), { isOwner: false, keyStored, balancePinned });++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"]);+ // Without a key there is nothing to ask the vendor with.+ expect(owner("tokendance", false)).toEqual(["connect", "groupKey", "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"]);+ });++ 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"]);+ for (const id of [+ "openrouter",+ "siliconflow",+ "opencode-go",+ "anthropic",+ "openai",+ "google",+ ]) {+ expect(owner(id, true), id).toEqual(["groupKey", "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("custom")).toEqual(["speedTest", "addModel"]);+ expect(owner("my-own-group")).toEqual(["groupKey", "speedTest", "addModel", "deleteGroup"]);+ });++ it("Add model appears on no built-in group but custom and vLLM", () => {+ const adding = MODEL_PROVIDERS.filter((p) => owner(p.id, true).includes("addModel")).map(+ (p) => p.id,+ );+ expect(adding.sort()).toEqual(["custom", "vllm"]);+ });++ it("a member keeps the balance and the connection status, and nothing that writes", () => {+ expect(member("tokendance", true)).toEqual(["balance", "connect"]);+ expect(member("deepseek", true)).toEqual(["balance"]);+ expect(member("vllm")).toEqual([]);+ expect(member("my-own-group")).toEqual([]);+ });++ 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"]);+ // Only where the catalog declares a balance at all.+ expect(owner("openrouter", false, true)).toEqual(["groupKey", "speedTest"]);+ });+});++describe("a key lent by the server's environment", () => {+ it("shows DeepSeek's balance, as a stored key does", () => {+ const facts = { isOwner: true, keyStored: false, keyFromEnv: true, balancePinned: false };+ expect(groupHeaderActions(group("deepseek"), facts)).toEqual([+ "balance",+ "groupKey",+ "speedTest",+ ]);+ expect(groupHeaderActions(group("deepseek"), { ...facts, isOwner: false })).toEqual([+ "balance",+ ]);+ });++ it("is read off the rows' masked preview, and does not make a group connected", () => {+ const envRows = [{ envKeyMasked: "sk-d…0003" }, {}];+ expect(groupKeyFromEnv(envRows)).toBe(true);+ expect(groupKeyFromEnv(keyed)).toBe(false);+ expect(groupKeyFromEnv([])).toBe(false);+ expect(connectionStatus(group("tokendance"), envRows)).toBe("notConnected");+ });+});++describe("the connection status beside Connect", () => {+ it("is exactly the three groups with an authorization flow", () => {+ const connecting = MODEL_PROVIDERS.filter(hasConnectFlow).map((p) => p.id);+ expect(connecting).toEqual(["tokendance", "penguin-go", "modelscope"]);+ });++ it("reads connected once any row holds a stored key, however it got there", () => {+ expect(groupKeyStored(keyed)).toBe(true);+ expect(groupKeyStored(keyless)).toBe(false);+ expect(groupKeyStored([])).toBe(false);+ expect(connectionStatus(group("tokendance"), keyed)).toBe("connected");+ expect(connectionStatus(group("penguin-go"), keyless)).toBe("notConnected");+ expect(connectionStatus(group("modelscope"), [])).toBe("notConnected");+ });++ it("is absent on a group that does not connect", () => {+ expect(connectionStatus(group("deepseek"), keyed)).toBeNull();+ expect(connectionStatus(group("my-own-group"), keyed)).toBeNull();+ });+});++describe("the divider after the balance", () => {+ it("stands between the balance and whatever follows it", () => {+ expect(dividerAfterBalance(owner("tokendance", true))).toBe(true);+ expect(dividerAfterBalance(owner("deepseek", true))).toBe(true);+ // A member of TokenDance: the balance, then the connection status.+ expect(dividerAfterBalance(member("tokendance", true))).toBe(true);+ });++ it("is left out where it would separate nothing", () => {+ // A member of DeepSeek sees the balance alone.+ expect(dividerAfterBalance(member("deepseek", true))).toBe(false);+ // No balance to lead: no key stored, or a group without one.+ expect(dividerAfterBalance(owner("tokendance", false))).toBe(false);+ expect(dividerAfterBalance(owner("openai", true))).toBe(false);+ expect(dividerAfterBalance([])).toBe(false);+ });+});diff --git a/packages/web/test/vendor-group-models.test.ts b/packages/web/test/vendor-group-models.test.tsindex 6ac460be..aae0111e 100644--- a/packages/web/test/vendor-group-models.test.ts+++ b/packages/web/test/vendor-group-models.test.ts@@ -7,9 +7,9 @@* the fix that row's own shape calls for, since a built-in model whose stored entry lost its* protocol pin must not be told to move into a custom group.*- * vitest runs node-only here, so the card is rendered to static markup and the group header —- * which lives inside the page component and needs a fetch, a Project and localStorage — is- * checked against the source of its own render condition.+ * vitest runs node-only here, so the card is rendered to static markup and the group header's+ * add entry point is checked through the action set group-header.ts decides (the header lives+ * inside the page component and needs a fetch, a Project and localStorage).*/import { readFileSync } from "node:fs";import { dirname, resolve } from "node:path";@@ -17,7 +17,13 @@ import { fileURLToPath } from "node:url";import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vitest";-import { isVendorGroup, unroutableVendorModel } from "@prismshadow/penguin-core/model-catalog";+import {+ MODEL_PROVIDERS,+ isAddableGroup,+ isVendorGroup,+ unroutableVendorModel,+} from "@prismshadow/penguin-core/model-catalog";+import { groupHeaderActions } from "../src/features/models/group-header";import { ModelCard, unroutableFix } from "../src/features/models/models-page";import type { RowState } from "../src/features/models/models-page";import { S, zh } from "../src/lib/strings";@@ -148,18 +154,36 @@ describe("the ways the page can open the add-model dialog", () => {it("are exactly three, none of which can name a vendor group", () => {// A fourth would be a new way into the state this change closed, so it has to be read// here rather than discovered as a bug report. The three: the "no models at all" empty- // state, which opens custom; the group header, guarded by the predicate; and a- // brand-new group, whose name is rejected when it collides with a built-in id.- expect(openers).toEqual(['"custom"', "group.provider.id", "name"]);- expect(source).toContain("{isOwner && !isVendorGroup(group.provider.id) && (");+ // state, which opens custom; the group header's Add model action, which the header only+ // carries where group-header.ts puts it; and a brand-new group, whose name is rejected+ // when it collides with a built-in id.+ expect([...openers].sort()).toEqual(['"custom"', "group.provider.id", "name"].sort());+ expect(source).toContain('case "addModel":');expect(source).toContain("MODEL_PROVIDERS.some((p) => p.id === trimmed)");+ for (const p of MODEL_PROVIDERS.filter((provider) => isVendorGroup(provider.id))) {+ const actions = groupHeaderActions(p, {+ isOwner: true,+ keyStored: true,+ balancePinned: false,+ });+ expect(actions, p.id).not.toContain("addModel");+ }});- it("leave the page's other group actions unguarded (only adding a model is closed off)", () => {- // A vendor group still takes a bulk API key, a speed test and its console link — the rule- // is about what may be written into the group, not about reaching it.+ it("leave the page's other group actions in place (only adding a model is closed off)", () => {+ // A vendor group still takes a group API key and a speed test — the rule is about what+ // may be written into the group, not about reaching it.expect(source).toContain("onClick={() => setGroupKeyFor(group.provider.id)}");- expect(source).toContain("onClick={() => setSpeedFor(group.provider.id)}");+ expect(source).toContain("setSpeedFor(group.provider.id)");+ for (const p of MODEL_PROVIDERS.filter((provider) => isVendorGroup(provider.id))) {+ const actions = groupHeaderActions(p, {+ isOwner: true,+ keyStored: true,+ balancePinned: false,+ });+ expect(actions, p.id).toContain("groupKey");+ expect(actions, p.id).toContain("speedTest");+ }});});@@ -170,6 +194,10 @@ describe("the predicate the page reads", () => {expect(isVendorGroup("openrouter")).toBe(false);expect(unroutableVendorModel("deepseek", "qwen/qwen3.8-flash-next")).toBe(true);expect(unroutableVendorModel("custom", "qwen/qwen3.8-flash-next")).toBe(false);+ // Whether a model may be added at all is the wider rule: gateways take none either.+ expect(isAddableGroup("deepseek")).toBe(false);+ expect(isAddableGroup("openrouter")).toBe(false);+ expect(isAddableGroup("custom")).toBe(true);});});diff --git a/plugins/agent-development/plugin.json b/plugins/agent-development/plugin.jsonindex 6559449f..3e594aac 100644--- a/plugins/agent-development/plugin.json+++ b/plugins/agent-development/plugin.json@@ -3,6 +3,6 @@"description_zh": "基于 PenguinHarness 的智能体开发:用 SDK 构建应用、经统一的 LLM API 调用任意模型、管理模型与密钥、编排智能体/会话/成本/定时任务。","short_description": "SDK, unified LLM API, config and orchestration.","short_description_zh": "SDK、统一 LLM API、配置与编排。",- "version": "2026.09.30.1",+ "version": "2026.09.30.2","category": "ai-app-development"}diff --git a/plugins/agent-development/skills/penguin-config/SKILL.md b/plugins/agent-development/skills/penguin-config/SKILL.mdindex 2b501e27..76a689c3 100644--- a/plugins/agent-development/skills/penguin-config/SKILL.md+++ b/plugins/agent-development/skills/penguin-config/SKILL.md@@ -23,6 +23,7 @@ penguin config model add --provider <group> --model-id <upstream_id> [--api-key```- A model is identified by the `(provider, model_id)` pair, so `--provider` and `--model-id` are **both required** — the group is never inferred from the model id, because gateways resell vendor models under their upstream ids and a wrong guess would send the key to another vendor's endpoint. `--model-id` takes the provider's upstream model id (what the API expects) and is persisted as the entry's request id, so it reaches the API unchanged; `--provider` names the group (`deepseek`, `openai`, `anthropic`, `google`, `openrouter`, `siliconflow`, … — `custom` for any other endpoint).+- Only `custom`, `vllm` and groups of your own take models added by hand. Every other built-in group carries its catalog models only: `model add` there accepts one of that group's catalog model ids (to set its key, limits or prices, or to bring it back) and refuses any other id with "cannot be added". Add such a model under `custom` with `--base-url`, or under a group of your own.- For any OpenAI chat-completion compatible endpoint use `--client-type openai --base-url <endpoint>`; omit `--client-type` to auto-route by model id.- Prices are USD per million tokens (cache read / cache write / output).- `--vision` / `--no-vision` mark whether the model accepts images; omitting both keeps the current value (default is vision-capable).