A local-first multi-agent app development platform, built on PenguinHarness
Five small UX fixes: Doubao Seed rows, discount badge wording, cost-center clear range, Copy Session ID, Ctrl+W closes a terminal (#590)
Yaowei Zheng4dd3ac1a9067
diff --git a/changelog/unreleased/2026-09-02-copy-session-id-label.md b/changelog/unreleased/2026-09-02-copy-session-id-label.mdnew file mode 100644index 00000000..47849483--- /dev/null+++ b/changelog/unreleased/2026-09-02-copy-session-id-label.md@@ -0,0 +1,15 @@+# "Copy Session ID", placed after archive++- **Date:** 2026-09-02+- **Type:** fix+- **Scope:** `web`, `docs`+- **PR:** [#590](https://github.com/Prism-Shadow/penguin-harness/pull/590)++[中文版](2026-09-02-copy-session-id-label.zh.md)++The Session row's id-copy action is now labelled **Copy Session ID** (Chinese: 复制 Session ID) wherever it appears — the context menu and the details card's copy button — and it moved within the context menu to sit between archive and delete. The menu now runs pin, rename, remote control, archive, copy Session ID, delete: the actions that change the Session first, then the one that changes nothing, beside the one that ends it.++## Details++- `chat.copySessionId` carries the new label in both dictionaries; `contextMenuActions` carries the new order for pinnable and folder rows alike, and the unit test and e2e assertion follow it.+- The Web App docs list the menu in its new order.diff --git a/changelog/unreleased/2026-09-02-copy-session-id-label.zh.md b/changelog/unreleased/2026-09-02-copy-session-id-label.zh.mdnew file mode 100644index 00000000..96b45c52--- /dev/null+++ b/changelog/unreleased/2026-09-02-copy-session-id-label.zh.md@@ -0,0 +1,15 @@+# 「复制 Session ID」,位置移到归档之后++- **Date:** 2026-09-02+- **Type:** fix+- **Scope:** `web`, `docs`+- **PR:** [#590](https://github.com/Prism-Shadow/penguin-harness/pull/590)++[English](2026-09-02-copy-session-id-label.md)++会话行的复制 id 操作在所有出现之处——右键菜单与详情卡的复制按钮——都改为**复制 Session ID**(英文 Copy Session ID),并在右键菜单里移到归档与删除之间。菜单顺序现为置顶、重命名、远程控制、归档、复制 Session ID、删除:先是改变会话的操作,然后是这一项什么都不改的,紧挨着结束它的那一项。++## 细节++- 两套词典的 `chat.copySessionId` 换用新文案;`contextMenuActions` 对可置顶行与折叠夹内的行都采用新顺序,单元测试与 e2e 断言随之更新。+- Web App 文档按新顺序列出该菜单。diff --git a/changelog/unreleased/2026-09-02-cost-center-clear-range.md b/changelog/unreleased/2026-09-02-cost-center-clear-range.mdnew file mode 100644index 00000000..7c65ae8e--- /dev/null+++ b/changelog/unreleased/2026-09-02-cost-center-clear-range.md@@ -0,0 +1,23 @@+# Clearing error records names its range and takes what the panel showed++- **Date:** 2026-09-02+- **Type:** fix+- **Scope:** `server`, `web`, `docs`+- **PR:** [#590](https://github.com/Prism-Shadow/penguin-harness/pull/590)+- **Breaking:** yes — `GET /usage` no longer returns `errors.clearable`, and a `DELETE /usage/errors` missing either date bound is refused with 400 instead of clearing the whole history++[中文版](2026-09-02-cost-center-clear-range.zh.md)++The cost center's **Clear** confirmation now names the range the way the picker does — "in the last 7 days", "in the last hour" — and spells out dates only for a custom range. Behind it, a clear now deletes exactly the rows the panel listed: the two trailing presets (last hour, last 24 hours) narrow the error table's reads and the clear alike to their instant window instead of to whole days, and an admin's clear takes the unattributed rows an admin's panel shows — login failures and process crashes with no Project — which a Project-scoped clear used to leave behind.++## Details++- `GET` and `DELETE /api/projects/:projectId/usage/errors` accept `fromTs` / `toTs` (both or neither, in order, like the dashboard); the dashboard's error statistics honour the pair too. Both bounds are inclusive. The clear additionally requires `from` and `to` (400 otherwise), as the panel already required them before offering the action — an open bound is the whole history rather than a filter.+- The delete reaches exactly what the caller's reads reach: an admin's clear includes unattributed rows, a member's (whose reads never show them) never does. `UsageErrors.clearable`, which counted the difference, is gone — `total` is what a clear takes.+- New strings `usage.errorsClearRangePreset` / `usage.errorsClearRangeCustom` feed `usage.errorsClearScope` and `usage.errorsClearScopeAgent`, which now take the range as one phrase.+- The Web App and server API docs describe the clear's reach.++## Compatibility++- `GET /api/projects/:projectId/usage` no longer returns `errors.clearable`. Read `errors.total`, which is now the count a clear takes. The Web App ships with the server, so a user has nothing to do; an API client reading `clearable` switches to `total`.+- `DELETE /api/projects/:projectId/usage/errors` answers 400 when `from` or `to` is missing, where such a call used to clear the Project's whole error history. Send both bounds — the range the panel is showing.diff --git a/changelog/unreleased/2026-09-02-cost-center-clear-range.zh.md b/changelog/unreleased/2026-09-02-cost-center-clear-range.zh.mdnew file mode 100644index 00000000..2110c988--- /dev/null+++ b/changelog/unreleased/2026-09-02-cost-center-clear-range.zh.md@@ -0,0 +1,23 @@+# 清空错误记录时点出范围,并删掉面板所列的全部记录++- **Date:** 2026-09-02+- **Type:** fix+- **Scope:** `server`, `web`, `docs`+- **PR:** [#590](https://github.com/Prism-Shadow/penguin-harness/pull/590)+- **Breaking:** yes — `GET /usage` 不再返回 `errors.clearable`;`DELETE /usage/errors` 缺任一端日期时以 400 拒绝,不再清空全部历史++[English](2026-09-02-cost-center-clear-range.md)++成本中心的**清空**确认框现在按范围选择器的叫法点出范围——「近 7 天内」「最近一小时内」——只有自定义范围才写起止日期。其背后,一次清空现在删除的正是面板列出的那些行:两个滑动档位(最近一小时、最近一天)对异常表的读取与清空一并收窄到其瞬时窗口,而不再是整天;管理员的清空同时带走其面板所示的无归属记录——没有 Project 归属的登录失败与进程崩溃——它们正是 Project 范围的清空过去留下的那部分。++## 细节++- `GET` 与 `DELETE /api/projects/:projectId/usage/errors` 接受 `fromTs` / `toTs`(同给或同不给、须有序,与看板一致);看板上的异常统计同样遵循这一对参数。两端均为闭区间。清空另外要求 `from` 与 `to` 必填(缺一即 400),与面板此前提供该操作的前提一致——开区间等于整段历史,而非一次筛选。+- 删除的触及范围与调用者的读取范围相同:管理员的清空包含无归属记录,成员(其读取从不显示这些行)的清空从不包含。原先用于表示两者之差的 `UsageErrors.clearable` 已移除——`total` 即一次清空会删掉的数量。+- 新增字符串 `usage.errorsClearRangePreset` / `usage.errorsClearRangeCustom` 供 `usage.errorsClearScope` 与 `usage.errorsClearScopeAgent` 使用,后两者现在以一个短语接收范围。+- Web App 与服务端 API 文档描述了清空的触及范围。++## 兼容性++- `GET /api/projects/:projectId/usage` 不再返回 `errors.clearable`,改读 `errors.total`——它现在就是一次清空会删掉的数量。Web App 与服务端一起发布,用户无需做任何事;读取 `clearable` 的 API 客户端改读 `total`。+- `DELETE /api/projects/:projectId/usage/errors` 在缺少 `from` 或 `to` 时应答 400,而此前这样的调用会清空该 Project 的全部异常历史。请同时给出两端日期——即面板当前显示的范围。diff --git a/changelog/unreleased/2026-09-02-discount-badge-wording.md b/changelog/unreleased/2026-09-02-discount-badge-wording.mdnew file mode 100644index 00000000..c95b91d9--- /dev/null+++ b/changelog/unreleased/2026-09-02-discount-badge-wording.md@@ -0,0 +1,14 @@+# The discount badge says what it means++- **Date:** 2026-09-02+- **Type:** fix+- **Scope:** `web`, `docs`+- **PR:** [#590](https://github.com/Prism-Shadow/penguin-harness/pull/590)++[中文版](2026-09-02-discount-badge-wording.zh.md)++The models page's discount badge read `-50%`, a figure with no word beside it to say what was fifty percent less than what. It now reads `50% off` in English and `省 50%` in Chinese; the hover text saying whether the rate is a running promotion or an off-peak schedule is unchanged.++## Details++- `models.discountBadge` renders the new wording in both dictionaries; the `models` docs page describes the DeepSeek off-peak mark with it.diff --git a/changelog/unreleased/2026-09-02-discount-badge-wording.zh.md b/changelog/unreleased/2026-09-02-discount-badge-wording.zh.mdnew file mode 100644index 00000000..89296196--- /dev/null+++ b/changelog/unreleased/2026-09-02-discount-badge-wording.zh.md@@ -0,0 +1,14 @@+# 折扣徽标写明含义++- **Date:** 2026-09-02+- **Type:** fix+- **Scope:** `web`, `docs`+- **PR:** [#590](https://github.com/Prism-Shadow/penguin-harness/pull/590)++[English](2026-09-02-discount-badge-wording.md)++模型页的折扣徽标原来只写 `-50%`,旁边没有一个字说明是什么比什么少了一半。现在英文写作 `50% off`、中文写作「省 50%」;悬停时说明该折扣是限时促销还是分时段计价的文案不变。++## 细节++- 两套词典的 `models.discountBadge` 都改为新写法;`models` 文档页对 DeepSeek 空闲时段标记的描述随之更新。diff --git a/changelog/unreleased/2026-09-02-doubao-seed-models.md b/changelog/unreleased/2026-09-02-doubao-seed-models.mdnew file mode 100644index 00000000..e9fbc642--- /dev/null+++ b/changelog/unreleased/2026-09-02-doubao-seed-models.md@@ -0,0 +1,16 @@+# Doubao Seed models on the TokenDance group++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `model-catalog`, `docs`+- **PR:** [#590](https://github.com/Prism-Shadow/penguin-harness/pull/590)++[中文版](2026-09-02-doubao-seed-models.zh.md)++The built-in catalog's TokenDance group gained ByteDance's three Doubao Seed chat models: `seed-2.1-pro` (Doubao Seed 2.1 Pro), `seed-2.1-turbo` (Doubao Seed 2.1 Turbo) and `seed-evolving` (Doubao Seed Evolving, a rolling id that currently serves the same model as 2.1 Pro). All three are on the gateway's 50%-off promotion, recorded the way every promoted TokenDance row is — the list price in `pricing`, the rate in `discount` — so the models page shows the billed price with a discount badge, and a Project preset with them charges what the gateway charges.++## Details++- Billed rates (CNY per million tokens, input / output / cache hit): 2.1 Turbo 1.5 / 7.5 / 0.3; 2.1 Pro and Evolving 3 / 15 / 0.6. Context window 256K, image input supported, `openai-chat` on the group's preset base URL like every other TokenDance row.+- Existing Projects pick the rows up through the models page's **sync presets**; new Projects get them on creation.+- The `models` docs page lists the new rows and the group's nine discounted models.diff --git a/changelog/unreleased/2026-09-02-doubao-seed-models.zh.md b/changelog/unreleased/2026-09-02-doubao-seed-models.zh.mdnew file mode 100644index 00000000..10849607--- /dev/null+++ b/changelog/unreleased/2026-09-02-doubao-seed-models.zh.md@@ -0,0 +1,16 @@+# TokenDance 分组新增 Doubao Seed 模型++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `model-catalog`, `docs`+- **PR:** [#590](https://github.com/Prism-Shadow/penguin-harness/pull/590)++[English](2026-09-02-doubao-seed-models.md)++内置目录的 TokenDance 分组新增字节跳动的三个 Doubao Seed 对话模型:`seed-2.1-pro`(Doubao Seed 2.1 Pro)、`seed-2.1-turbo`(Doubao Seed 2.1 Turbo)与 `seed-evolving`(Doubao Seed Evolving,一个滚动更新的 id,当前与 2.1 Pro 为同一模型)。三者都在该网关的五折促销中,按 TokenDance 促销条目的既有口径记录——`pricing` 存牌价、`discount` 存折扣率——因此模型页显示实际计费价并带折扣徽标,预置进 Project 的价格即网关实际收取的价格。++## 细节++- 计费价(CNY / 百万 Token,输入 / 输出 / 缓存命中):2.1 Turbo 1.5 / 7.5 / 0.3;2.1 Pro 与 Evolving 3 / 15 / 0.6。上下文窗口 256K,支持图片输入,与该分组其他条目一样固定 `openai-chat` 客户端与分组预置 base URL。+- 既有 Project 通过模型页的**同步预置**获得这些条目;新建 Project 创建时即带上。+- `models` 文档页列出了新条目与该分组当前九个折扣中的模型。diff --git a/changelog/unreleased/2026-09-02-terminal-close-shortcut.md b/changelog/unreleased/2026-09-02-terminal-close-shortcut.mdnew file mode 100644index 00000000..47156de7--- /dev/null+++ b/changelog/unreleased/2026-09-02-terminal-close-shortcut.md@@ -0,0 +1,15 @@+# Ctrl+W closes the focused terminal++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#590](https://github.com/Prism-Shadow/penguin-harness/pull/590)++[中文版](2026-09-02-terminal-close-shortcut.zh.md)++Pressing Ctrl+W inside a terminal closes that terminal — the same thing its tab's × does: a confirmation first, then the shell is ended. It works in the dock's terminal tabs and on the standalone `/terminal` page, where the window then closes itself when the browser allows it (a window opened by the dock's detach); a window reached by address stays open showing the exited shell, with **New shell** one click away. The keystroke never reaches the shell, and only the terminal that has focus sees it — nothing is registered window-wide. The tab's × tooltip names the shortcut.++## Details++- Browsers reserve Ctrl+W for closing the browser tab and may act on it before the page does; the desktop app delivers it to the terminal.+- In the shell, Ctrl+W was readline's delete-previous-word; inside a PenguinHarness terminal it is now the close.diff --git a/changelog/unreleased/2026-09-02-terminal-close-shortcut.zh.md b/changelog/unreleased/2026-09-02-terminal-close-shortcut.zh.mdnew file mode 100644index 00000000..8c50f546--- /dev/null+++ b/changelog/unreleased/2026-09-02-terminal-close-shortcut.zh.md@@ -0,0 +1,15 @@+# Ctrl+W 关闭当前终端++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#590](https://github.com/Prism-Shadow/penguin-harness/pull/590)++[English](2026-09-02-terminal-close-shortcut.md)++在终端内按 Ctrl+W 即关闭该终端——与其标签上的 × 完全相同:先确认,再结束 Shell。停靠面板的终端标签与独立的 `/terminal` 页都支持;后者在浏览器允许时(由停靠面板「分离」打开的窗口)随后自行关闭窗口,直接按地址打开的窗口则留在原地显示已退出的 Shell,**新建 Shell** 一键可达。按键不会到达 Shell,也只有获得焦点的那个终端会收到它——没有注册任何全局快捷键。标签 × 的悬停提示写明了这个快捷键。++## 细节++- 浏览器把 Ctrl+W 留给关闭浏览器标签页,可能先于页面响应;桌面应用会把它交给终端。+- 在 Shell 里 Ctrl+W 原本是 readline 的删除前一个词;在 PenguinHarness 的终端内它现在是关闭。diff --git a/packages/core/src/state/model-catalog.ts b/packages/core/src/state/model-catalog.tsindex cf982229..d642648f 100644--- a/packages/core/src/state/model-catalog.ts+++ b/packages/core/src/state/model-catalog.ts@@ -7,12 +7,14 @@* 2026-08-21; the TokenDance group: 2026-08-25, its glm-5.3-flash row: 2026-08-26, its* qwen3.8-flash row: 2026-08-27 and its running promotions plus the hy4-preview rows* (TokenDance + OpenRouter): 2026-08-28; the GLM-5.3 Flash rows (direct + OpenRouter) and- * the direct qwen3.8-flash: 2026-08-26; the vLLM group: 2026-09-03; the direct DeepSeek V4- * Flash rows (flash and flash-vision-exp): 2026-09-08, for the official adjustment effective- * 2026-09-10; the GPT-6 Astra rows (direct + OpenRouter): 2026-09-09; the pre-registered- * deepseek-v4.1-flash row: 2026-09-09, from DeepSeek's release announcement; the whole Gemini- * 3.x line-up, direct + OpenRouter — the 3.6 / 3.7 / 3.8 Flash launch discounts declared,- * every other row re-read and unchanged: 2026-09-09 — per each provider's docs).+ * the direct qwen3.8-flash: 2026-08-26; the TokenDance Doubao Seed rows (seed-2.1-pro,+ * seed-2.1-turbo, seed-evolving): 2026-09-02; the vLLM group: 2026-09-03; the direct DeepSeek+ * V4 Flash rows (flash and flash-vision-exp): 2026-09-08, for the official adjustment+ * effective 2026-09-10; the GPT-6 Astra rows (direct + OpenRouter): 2026-09-09; the+ * pre-registered deepseek-v4.1-flash row: 2026-09-09, from DeepSeek's release announcement;+ * the whole Gemini 3.x line-up, direct + OpenRouter — the 3.6 / 3.7 / 3.8 Flash launch+ * discounts declared, every other row re-read and unchanged: 2026-09-09 — per each+ * provider's docs).* Docs: packages/docs/content/models.{zh,en}.md (site path /docs/models) documents the* provider groups and credential resolution described here.*@@ -1227,9 +1229,10 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [// price rewritten — a promotion that lapses is then one field to delete, with the rate to// return to still on the row. effectivePricing() applies it and presetModelEntries writes// that billed rate into a Project, so the cost center charges what the gateway charges.- // Six rows are promoted: deepseek-v4-flash-0731, deepseek-v4-pro-0813 and glm-5.3-flash at- // 50% off, kimi-k3 at 20%, glm-5.3 and qwen3.8-max at 10%. The rest carry no discount, so- // for them list price and billed rate coincide.+ // Nine rows are promoted: deepseek-v4-flash-0731, deepseek-v4-pro-0813, glm-5.3-flash and+ // the three Doubao Seed rows (seed-2.1-pro, seed-2.1-turbo, seed-evolving) at 50% off,+ // kimi-k3 at 20%, glm-5.3 and qwen3.8-max at 10%. The rest carry no discount, so for them+ // list price and billed rate coincide.//// A running promotion usually also shows up without a credential: the catalog API opens// such a model's `description` with a bracketed 限时 ("limited-time") tag, so the same@@ -1358,6 +1361,51 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [clientType: "openai-chat",baseUrl: TOKENDANCE_BASE_URL,},+ {+ // The three Doubao Seed rows share this note. Priced 2026-09-02 from the seller's quoted+ // 50%-off rates, doubled back to the list price a row stores; context windows and+ // protocols from the catalog API, whose descriptions call the 2.1 models multimodal+ // Coding/Agent models (this group's openai-chat client forwards image_url parts, so+ // image input works on this path). That API tags the two 2.1 rows with a limited-time+ // 20% line rather than the 50% here; as for every promoted row in this group, the rate+ // recorded is the one the seller confirmed. seed-2.1-pro and seed-2.1-turbo also list+ // openai:responses, so their openai-chat pin is the group's convention rather than the+ // only shape they serve; seed-evolving lists chat-completions alone.+ modelId: "seed-2.1-pro",+ displayName: "Doubao Seed 2.1 Pro",+ provider: "tokendance",+ contextWindow: 256000,+ pricing: cny(1.2, 6, 30),+ discount: 0.5,+ supportsVision: true,+ clientType: "openai-chat",+ baseUrl: TOKENDANCE_BASE_URL,+ },+ {+ modelId: "seed-2.1-turbo",+ displayName: "Doubao Seed 2.1 Turbo",+ provider: "tokendance",+ contextWindow: 256000,+ pricing: cny(0.6, 3, 15),+ discount: 0.5,+ supportsVision: true,+ clientType: "openai-chat",+ baseUrl: TOKENDANCE_BASE_URL,+ },+ {+ // A rolling id: the catalog API describes it as the newest Seed Coding/Agent model+ // under one stable id — the same model as seed-2.1-pro at the time of reading — and+ // the seller prices it the same.+ modelId: "seed-evolving",+ displayName: "Doubao Seed Evolving",+ provider: "tokendance",+ contextWindow: 256000,+ pricing: cny(1.2, 6, 30),+ discount: 0.5,+ supportsVision: true,+ clientType: "openai-chat",+ baseUrl: TOKENDANCE_BASE_URL,+ },// -- Qwen Token Plan (subscription gateway; vision flags per the plan's supported-model// table). Pricing and context windows from each model's page at// www.qianwenai.com/models/<id> (official CNY list prices; limited-time promotions such asdiff --git a/packages/core/test/model-catalog.test.ts b/packages/core/test/model-catalog.test.tsindex 9d21f88c..8897fdf3 100644--- a/packages/core/test/model-catalog.test.ts+++ b/packages/core/test/model-catalog.test.ts@@ -410,6 +410,9 @@ describe("model-catalog", () => {["kimi-k3", 1048576, true],["qwen3.8-flash", 1000000, true],["qwen3.8-max", 1000000, true],+ ["seed-2.1-pro", 256000, true],+ ["seed-2.1-turbo", 256000, true],+ ["seed-evolving", 256000, true],]);for (const m of td) {expect(m.clientType).toBe("openai-chat");@@ -439,6 +442,9 @@ describe("model-catalog", () => {["deepseek-v4-flash-0731", 0.5, [1.5, 4.5, 0.05]],["kimi-k3", 0.2, [16, 80, 1.6]],["qwen3.8-max", 0.1, [10.8, 32.4, 1.35]],+ ["seed-2.1-pro", 0.5, [3, 15, 0.6]],+ ["seed-2.1-turbo", 0.5, [1.5, 7.5, 0.3]],+ ["seed-evolving", 0.5, [3, 15, 0.6]],];for (const [modelId, discount, cnyBilled] of discounted) {const entry = td.find((m) => m.modelId === modelId)!;@@ -448,7 +454,7 @@ describe("model-catalog", () => {expect(output, `${modelId} output`).toBeCloseTo(cnyBilled[1], 4);expect(cacheHit, `${modelId} cache hit`).toBeCloseTo(cnyBilled[2], 4);}- // Exactly those six are promoted; every other row bills its list price unchanged.+ // Exactly those nine are promoted; every other row bills its list price unchanged.expect(td.filter((m) => m.discount !== undefined)diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.mdindex 83b6739b..b9b3d0a1 100644--- a/packages/docs/content/models.en.md+++ b/packages/docs/content/models.en.md@@ -78,9 +78,9 @@ The gateway groups (openrouter / fireworks / siliconflow / tokendance / qwen-payThe preset catalog also carries OpenRouter's free tier: the `:free` model variant `nvidia/nemotron-3-ultra-550b-a55b:free` and the `openrouter/free` unified Free Models Router. They cost nothing, but are subject to OpenRouter's free-tier rate limits and data policy.-Some models in the preset catalog: deepseek-v4.1-flash / deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp (deepseek-v4.1-flash and deepseek-v4-flash-vision-exp are the DeepSeek group's vision-capable models), MiniMax-M3, gemini-3.8-flash, claude-opus-5 / claude-opus-4-8 / claude-sonnet-5, gpt-6-astra / gpt-5.6 / gpt-5.5, glm-5.3 / glm-5.3-flash, kimi-k3, qwen3.8-max / qwen3.8-flash (not exhaustive). The whole OpenAI line-up is listed twice — directly (your own OpenAI key, list prices) and on OpenRouter as `openai/<id>` (the gateway's rates, which follow its running promotions). DeepSeek's direct-group rows record the official peak tier and declare its off-peak schedule: outside Beijing weekday 9:00–12:00 and 14:00–18:00 every bucket is halved, which the models page marks with a `-50%` tag and the cost center bills at. The stored price is always the peak one, so what is on disk does not depend on the hour a Project was created or re-synced in. `glm-5.3-flash` appears three times, and all three rows accept images: AgentHub's GLM client forwards image parts for this one GLM id (every other GLM id refuses them), while the OpenRouter row `z-ai/glm-5.3-flash` and the TokenDance row go through the generic OpenAI-compatible client, which carries them for any id. What the three rows do not share is the price: each records what its own seller charges, so they disagree while a promotion is running.+Some models in the preset catalog: deepseek-v4.1-flash / deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp (deepseek-v4.1-flash and deepseek-v4-flash-vision-exp are the DeepSeek group's vision-capable models), MiniMax-M3, gemini-3.8-flash, claude-opus-5 / claude-opus-4-8 / claude-sonnet-5, gpt-6-astra / gpt-5.6 / gpt-5.5, glm-5.3 / glm-5.3-flash, kimi-k3, qwen3.8-max / qwen3.8-flash, seed-2.1-pro / seed-2.1-turbo / seed-evolving (not exhaustive). The whole OpenAI line-up is listed twice — directly (your own OpenAI key, list prices) and on OpenRouter as `openai/<id>` (the gateway's rates, which follow its running promotions). DeepSeek's direct-group rows record the official peak tier and declare its off-peak schedule: outside Beijing weekday 9:00–12:00 and 14:00–18:00 every bucket is halved, which the models page marks with a `50% off` badge and the cost center bills at. The stored price is always the peak one, so what is on disk does not depend on the hour a Project was created or re-synced in. `glm-5.3-flash` appears three times, and all three rows accept images: AgentHub's GLM client forwards image parts for this one GLM id (every other GLM id refuses them), while the OpenRouter row `z-ai/glm-5.3-flash` and the TokenDance row go through the generic OpenAI-compatible client, which carries them for any id. What the three rows do not share is the price: each records what its own seller charges, so they disagree while a promotion is running.-TokenDance rows record the gateway's list price and, where a promotion is running, the rate off it. Six models are discounted today — `deepseek-v4-flash-0731`, `deepseek-v4-pro-0813` and `glm-5.3-flash` at 50% off, `kimi-k3` at 20%, `glm-5.3` and `qwen3.8-max` at 10%. Their model cards show the price being billed right now, with the rate as a badge, and a Project is preset with the **discounted** price, so the cost center charges what the gateway charges. Prices you edit yourself keep the discount decoration off the card: the figure is then yours, not the gateway's.+TokenDance rows record the gateway's list price and, where a promotion is running, the rate off it. Nine models are discounted today — `deepseek-v4-flash-0731`, `deepseek-v4-pro-0813`, `glm-5.3-flash` and the three Doubao Seed rows (`seed-2.1-pro`, `seed-2.1-turbo`, `seed-evolving`) at 50% off, `kimi-k3` at 20%, `glm-5.3` and `qwen3.8-max` at 10%. Their model cards show the price being billed right now, with the rate as a badge, and a Project is preset with the **discounted** price, so the cost center charges what the gateway charges. Prices you edit yourself keep the discount decoration off the card: the figure is then yours, not the gateway's.## App attributiondiff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.mdindex ed38f40f..00392594 100644--- a/packages/docs/content/models.zh.md+++ b/packages/docs/content/models.zh.md@@ -78,9 +78,9 @@ api_key = "sk-..."预置目录还收录了 OpenRouter 的免费档:`:free` 模型变体 `nvidia/nemotron-3-ultra-550b-a55b:free` 与统一路由 `openrouter/free`(Free Models Router),零成本可用,但受 OpenRouter 免费档速率限制与数据政策约束。-预置目录中的部分模型:deepseek-v4.1-flash / deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp(其中 deepseek-v4.1-flash 与 deepseek-v4-flash-vision-exp 是 DeepSeek 分组中支持图像输入的两条)、MiniMax-M3、gemini-3.8-flash、claude-opus-5 / claude-opus-4-8 / claude-sonnet-5、gpt-6-astra / gpt-5.6 / gpt-5.5、glm-5.3 / glm-5.3-flash、kimi-k3、qwen3.8-max / qwen3.8-flash 等(非完整清单)。OpenAI 全系列都收录了两份——直连(用自己的 OpenAI Key,记牌价)与 OpenRouter 上的 `openai/<id>`(记网关实际计费价,会随其促销浮动)。DeepSeek 直连分组的条目记录官方高峰档,并声明其空闲时段规则:在北京时间周一至周五 9:00–12:00、14:00–18:00 之外,各档价格减半——模型页以 `-50%` 标记,成本中心按此计价。存盘的始终是高峰价,因此磁盘上的数字不会随 Project 创建或同步预置的时刻而变。`glm-5.3-flash` 收录了三份,三条都支持图像输入:AgentHub 的 GLM 客户端只为这一个 GLM id 转发图像部件(其余 GLM id 一律拒绝),而 OpenRouter 上的 `z-ai/glm-5.3-flash` 与 TokenDance 分组的同名条目走通用 OpenAI 兼容客户端,对任何 id 都能携带图片。三条不一致的是价格:每一条都记录各自卖家的收费,因此促销期间三者不同。+预置目录中的部分模型:deepseek-v4.1-flash / deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp(其中 deepseek-v4.1-flash 与 deepseek-v4-flash-vision-exp 是 DeepSeek 分组中支持图像输入的两条)、MiniMax-M3、gemini-3.8-flash、claude-opus-5 / claude-opus-4-8 / claude-sonnet-5、gpt-6-astra / gpt-5.6 / gpt-5.5、glm-5.3 / glm-5.3-flash、kimi-k3、qwen3.8-max / qwen3.8-flash、seed-2.1-pro / seed-2.1-turbo / seed-evolving 等(非完整清单)。OpenAI 全系列都收录了两份——直连(用自己的 OpenAI Key,记牌价)与 OpenRouter 上的 `openai/<id>`(记网关实际计费价,会随其促销浮动)。DeepSeek 直连分组的条目记录官方高峰档,并声明其空闲时段规则:在北京时间周一至周五 9:00–12:00、14:00–18:00 之外,各档价格减半——模型页以「省 50%」徽标标记,成本中心按此计价。存盘的始终是高峰价,因此磁盘上的数字不会随 Project 创建或同步预置的时刻而变。`glm-5.3-flash` 收录了三份,三条都支持图像输入:AgentHub 的 GLM 客户端只为这一个 GLM id 转发图像部件(其余 GLM id 一律拒绝),而 OpenRouter 上的 `z-ai/glm-5.3-flash` 与 TokenDance 分组的同名条目走通用 OpenAI 兼容客户端,对任何 id 都能携带图片。三条不一致的是价格:每一条都记录各自卖家的收费,因此促销期间三者不同。-TokenDance 分组的条目记录该网关的牌价,并在有促销时记录折扣率。当前有六个模型处于折扣中——`deepseek-v4-flash-0731`、`deepseek-v4-pro-0813` 与 `glm-5.3-flash` 五折,`kimi-k3` 八折,`glm-5.3` 与 `qwen3.8-max` 九折。它们的模型卡片显示当前实际计费的那个价格,并以徽标标出折扣率;新建 Project 预置的是**折后价**,因此成本中心按网关实际收费计价。自行修改过价格的条目不再显示折扣标记:此时那个数字属于你,而不是网关。+TokenDance 分组的条目记录该网关的牌价,并在有促销时记录折扣率。当前有九个模型处于折扣中——`deepseek-v4-flash-0731`、`deepseek-v4-pro-0813`、`glm-5.3-flash` 与三条 Doubao Seed 条目(`seed-2.1-pro`、`seed-2.1-turbo`、`seed-evolving`)五折,`kimi-k3` 八折,`glm-5.3` 与 `qwen3.8-max` 九折。它们的模型卡片显示当前实际计费的那个价格,并以徽标标出折扣率;新建 Project 预置的是**折后价**,因此成本中心按网关实际收费计价。自行修改过价格的条目不再显示折扣标记:此时那个数字属于你,而不是网关。## 应用归因diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex b954e2cd..5db1d10f 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -249,8 +249,8 @@ On Session creation, `modelId` and `provider` are both-or-neither: send the comp| Method | Path | Description || --- | --- | --- || GET | /usage | Usage statistics; query parameters `from`, `to`, `fromTs`/`toTs` (ISO timestamps bounding a trailing window, given together; required for `minute`), `groupBy`, `granularity` (`minute` / `hour` / `day` / `week` / `month` time-series precision, default `day`; oversized range × precision combinations are rejected), `agentId`, `provider`, `modelId` |-| GET | /usage/errors | One page of the error detail table (newest first): `offset`, `limit`, plus the same `from` / `to` / `agentId` filter and an optional `kind` (`unexpected` / `expected`) → `{items, total}` |-| DELETE | /usage/errors | Empties the error table for the filter on screen: `from` / `to` / `agentId`, the same pair the reads take (no `kind` — the panel offers no such control) → `{deleted}`. Project owner only; errors with no Project attribution are outside every clear, admin included |+| GET | /usage/errors | One page of the error detail table (newest first): `offset`, `limit`, plus the same `from` / `to` / `fromTs` / `toTs` / `agentId` filter and an optional `kind` (`unexpected` / `expected`) → `{items, total}` |+| DELETE | /usage/errors | Empties the error table for the filter on screen: `from` / `to` / `fromTs` / `toTs` / `agentId`, the same set the reads take (no `kind` — the panel offers no such control) → `{deleted}`. `from` and `to` are both required here (400 otherwise) — an open bound would be the whole history rather than a filter. Project owner only; the clear reaches exactly what the caller's reads reach, so an admin's clear also takes the unattributed rows an admin's read shows, and a member's never does || GET | /agents/:agentId/traces | Date → Session drill-down structure of Trace files || GET | /agents/:agentId/traces/:sessionId/:index | Read Trace events (`offset` / `limit` pagination) || GET | /agents/:agentId/traces/:sessionId/:index/analysis | Trace performance analysis |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex c80348e3..e17283ae 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -249,8 +249,8 @@ Schedule 写操作仅限 Owner。新建 Session 模式的任务,`modelId` 与| 方法 | 路径 | 说明 || --- | --- | --- || GET | /usage | 用量统计,查询参数 `from`、`to`、`fromTs`/`toTs`(ISO 时间戳界定的滑动窗口,须成对给出;`minute` 精度必需)、`groupBy`、`granularity`(时间序列精度 `minute` / `hour` / `day` / `week` / `month`,默认 `day`;范围 × 精度过大的组合会被拒绝)、`agentId`、`provider`、`modelId` |-| GET | /usage/errors | 异常明细表分页(按时间倒序):`offset`、`limit`,以及与看板一致的 `from` / `to` / `agentId` 过滤,另可选 `kind`(`unexpected` / `expected`)→ `{items, total}` |-| DELETE | /usage/errors | 清空当前筛选下的异常明细:`from` / `to` / `agentId`,与读取所用的同一组(不接受 `kind`,面板没有该控件)→ `{deleted}`。仅 Project owner;无 Project 归属的异常不在任何一次清空范围内,管理员亦然 |+| GET | /usage/errors | 异常明细表分页(按时间倒序):`offset`、`limit`,以及与看板一致的 `from` / `to` / `fromTs` / `toTs` / `agentId` 过滤,另可选 `kind`(`unexpected` / `expected`)→ `{items, total}` |+| DELETE | /usage/errors | 清空当前筛选下的异常明细:`from` / `to` / `fromTs` / `toTs` / `agentId`,与读取所用的同一组(不接受 `kind`,面板没有该控件)→ `{deleted}`。此处 `from` 与 `to` 必填(缺一即 400)——开区间等于整段历史而非一次筛选。仅 Project owner;删除的触及范围与调用者的读取范围相同,故管理员的清空同时带走其读取所含的无归属异常,成员的清空从不涉及 || GET | /agents/:agentId/traces | Trace 文件的日期 → Session 下钻结构 || GET | /agents/:agentId/traces/:sessionId/:index | 读取 Trace 事件(`offset` / `limit` 分页) || GET | /agents/:agentId/traces/:sessionId/:index/analysis | Trace 性能分析结果 |diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex b2714417..ef4970f5 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -46,7 +46,7 @@ The sidebar's conversation list groups by Workspace or by Agent. Grouping and soA row's actions come at two levels:- **Hovering** a row replaces the trailing last-active time with two icon buttons — archive and delete. They are reachable from the keyboard too: tabbing onto either one reveals it;-- **Right-clicking** a row opens the full menu at the pointer: pin, rename, archive, delete. A **long press** on touch and **Shift+F10** on the keyboard open the same menu, since neither hover nor a secondary click exists there. Escape, a click elsewhere, or scrolling the list dismisses it; the browser's own context menu is taken over on conversation rows only, and stays as usual everywhere else on the page.+- **Right-clicking** a row opens the full menu at the pointer: pin, rename, remote control, archive, copy Session ID, delete. A **long press** on touch and **Shift+F10** on the keyboard open the same menu, since neither hover nor a secondary click exists there. Escape, a click elsewhere, or scrolling the list dismisses it; the browser's own context menu is taken over on conversation rows only, and stays as usual everywhere else on the page.Beside a row's title sit its status marks: a turning hourglass while the Session runs (a squeezing bar while it compacts), a green dot once a run finished that you have not looked at yet, and a small activity trace while the Session still owns **background tasks** — commands running on past their yield window and background subagents mid-round. Its tooltip counts them ("2 background tasks"). The mark is independent of the others: an idle conversation whose dev server is still up keeps it, and it disappears the moment the last task ends, pushed live without a refresh.@@ -79,6 +79,7 @@ Copy buttons across the app confirm at the button itself: the copy icon flips to- When human approval is required, tool calls show inline allow/deny buttons in the message stream; the approval mode can be changed mid-Session;- While the engine waits out a reconnect backoff (≥2s), the retry line shows a live countdown to the next attempt with inline **Retry now** (skips the remaining wait) and **Give up** (the ordinary abort) controls;- When the model API rejects the Session's credentials (an authentication failure), the composer grays out and disables — recoverably: the Session pins only the model reference, and credentials come from the current Project config. The notice's primary button opens the Models page; saving a new API key there unlocks the composer by itself (open tabs unlock live via a `credentials_updated` event, and after a reload the composer stays unlocked because the credential update is newer than the recorded auth failure). A "Retry" button clears the state manually for another attempt (it re-arms if the key is still bad), a completed request always clears it, and "New Session" remains as the escape to a fresh draft. The disabled composer keeps its draft selectable, so a long message that failed to send can still be copied out.+- Terminals live in the docks beside the conversation: Ctrl+` shows or hides the terminal tabs (adopting or starting a shell when none is open), and Ctrl+W, with a terminal focused, closes that terminal — the same confirm-then-kill its tab's × runs, in the dock and on the standalone `/terminal` page alike — and never reaches the shell. Browsers reserve Ctrl+W for closing the browser tab and may act on it first; the desktop app delivers it to the terminal.### Files Panel@@ -117,7 +118,7 @@ A per-Project model table grouped by provider. Models can be added and edited: i- Summary cards: today / last 7 days / cumulative;- Charts, all time series over the selected range: requests + success rate broken down by Agent and, beside it, the same by Model (a bucket's requests stacked one segment per entity on the left axis, each entity's success rate as its own dashed line on a right 0–100% axis, drawn above the bars; the top few entities are named and the rest fold into a neutral series labelled with how many), Token trend (three-segment stacked bars with a dashed cache-hit-rate line in front), and cost trend (line + points + area). Every chart takes the same hovers: a column for its bubble, one bar segment to single that segment out, a line to single the line out. Lines are straight segments, never smoothed, all at the same stroke width. Charts fit their card and never scroll;- Two things a chart cannot draw. A bucket with **no rate** — an entity that made no request in it, or a bucket with no cache traffic — has its line carried across at the top of the axis so the stroke stays continuous; the hover table prints a dash there, never a percentage, and a real 0% (requests were made and all of them failed) still prints 0%. A bucket that recorded **nothing at all** is not plotted: every chart drops it and packs the rest left to right, so all four share one x axis that skips the quiet intervals and carries a break mark at each skip. Emptiness is judged per bucket, never per entity — an interval anything ran in stays, with the entities that were idle in it showing their zeros and dashes;-- A server error panel: summary stats plus an errors table paged at a fixed page size (no scrolling).+- A server error panel: summary stats plus an errors table paged at a fixed page size (no scrolling). Its **Clear** (Project owner only) deletes the rows the current range and Agent filter lists — the trailing window or calendar preset the picker holds, named as such in the confirmation, or a custom range named by its dates; an admin's clear also takes the unattributed rows only admins see.## Benchmark (/benchmark)diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex e7b5c919..afa3b0a8 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -46,7 +46,7 @@ penguin web会话行的操作分两层:- **悬停**一行时,行尾的最近活跃时间让位给两个图标按钮——归档与删除;键盘同样够得到:Tab 到其中任意一个,该按钮即显形;-- **右键点击**一行,在指针处打开完整菜单:置顶、重命名、归档、删除。触屏**长按**、键盘 **Shift+F10** 打开同一个菜单(触屏没有悬停,也没有右键)。按 Esc、点击别处或滚动列表都会关闭它;系统右键菜单只在会话行上被接管,页面其他位置照常。+- **右键点击**一行,在指针处打开完整菜单:置顶、重命名、远程控制、归档、复制 Session ID、删除。触屏**长按**、键盘 **Shift+F10** 打开同一个菜单(触屏没有悬停,也没有右键)。按 Esc、点击别处或滚动列表都会关闭它;系统右键菜单只在会话行上被接管,页面其他位置照常。会话行标题旁是它的状态标记:Session 运行中是翻转的沙漏(压缩中是向中线合拢的压缩标),有一条你还没看过的回复时是一枚绿点,会话仍有**后台任务**——超过 yield 窗口继续运行的命令、正在跑一轮的后台子智能体——时另有一枚小小的活动波形标记,悬停显示数量(「2 个后台任务」)。这枚标记与其他标记互不影响:dev server 还开着的空闲对话照样带着它,最后一项后台任务结束的那一刻它即消失,由服务端实时推送、无需刷新。@@ -78,6 +78,7 @@ penguin web- 需要人工审批时,工具调用在消息流中内联显示“允许 / 拒绝”按钮;审批模式在会话中途可随时调整;- 引擎在重连退避等待(≥2 秒)期间,重试提示行会实时倒计时到下一次尝试,并内联提供**立即重试**(跳过剩余等待)与**放弃**(普通中断)两个按钮;- 模型 API 拒绝该 Session 的凭据(鉴权失败)时,输入框会置灰禁用——但可恢复:Session 锁定的只是模型引用,凭据取自当前 Project 配置。提示条的主按钮跳转到模型配置页;在那里保存新的 API key 后输入框会自动解锁(已打开的标签页经 `credentials_updated` 事件即时解锁;刷新后也保持解锁,因为凭据更新时间晚于记录的鉴权失败时间)。「重试」按钮可手动清除该状态再试一次(key 仍无效时会重新变灰),一次成功的请求总会清除该状态,「新建会话」仍作为跳到全新草稿的出口。禁用态的输入框保留草稿且可选中——发送失败的长消息仍能复制出来。+- 终端位于对话两侧的停靠面板:Ctrl+` 显示或收起终端标签(没有打开的终端时会接管或新建一个 Shell),终端获得焦点时按 Ctrl+W 关闭该终端——与标签 × 相同,先确认、再结束 Shell,停靠面板与独立的 `/terminal` 页一致——按键不会到达 Shell。浏览器把 Ctrl+W 留给关闭浏览器标签页,可能先于页面响应;桌面应用会把它交给终端。### 文件面板@@ -116,7 +117,7 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,- 概览卡片:今日 / 近 7 天 / 累计用量;- 图表,全部按所选范围展示的时间序列:并排的「按 Agent 拆分」与「按模型拆分」的请求与成功率图(单个时间桶的请求数按对象分段堆叠、走左轴,每个对象的成功率各自成一条虚线、走右侧 0–100% 轴并绘制在柱子上方;请求数最高的若干对象具名呈现,其余折叠为一条标注了数量的中性色序列)、Token 变化(三段堆叠柱 + 前置的缓存命中率虚线)、成本变化(折线带点 + 面积)。每张图都支持同样的悬停:悬停整列看气泡、悬停单段柱突出该段、悬停折线突出该线。所有折线都是直连线段、不做平滑,线宽统一。图表自适应卡片宽度,不出现滚动条;- 有两种情况图画不出来。**没有比率**的桶——该对象在这个桶里一次请求都没发,或该桶没有缓存流量——折线沿坐标轴顶部横穿过去,只为让线保持连续;悬停表格在该处显示「—」而非百分比,而真正的 0%(发了请求且全部失败)仍然显示 0%。**什么都没记录**的桶一律不画:四张图都丢弃它、把其余的从左往右依次排开,因此共用同一条会跳过空闲区间的横轴,跳过处画有断轴标记。空与不空按桶判断、绝不按单个对象判断——只要有任何对象在这个区间跑过,桶就保留,当时空闲的对象在该列显示 0 与「—」;-- 服务端错误面板:汇总统计 + 异常明细表,按固定页大小分页(不滚动)。+- 服务端错误面板:汇总统计 + 异常明细表,按固定页大小分页(不滚动)。其**清空**(仅 Project owner)删除当前范围与 Agent 筛选所列的记录——确认框按档位名点出范围(如「近 7 天内」「最近一小时内」),自定义范围才写起止日期;管理员的清空同时带走只有管理员看得到的无归属记录。## Benchmark(/benchmark)diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex c201adde..d92ca2b8 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -2858,16 +2858,8 @@ export interface UsageErrorItem {* items.*/export interface UsageErrors {+ /** Filtered row count — also what a clear of the same filter takes (see {@link UsageErrorsClearResponse}). */total: number;- /**- * How many of {@link total} a clear would actually take (see {@link UsageErrorsClearResponse}).- *- * The same as `total` for an ordinary member, and smaller for an admin, whose reads include- * unattributed rows that no Project-scoped clear removes. The confirmation is the only place- * this matters, and it is the place it matters most: an irreversible delete has to name the- * number that will really go, not the number on screen.- */- clearable: number;/** Count of unexpected ones (500 / runtime exceptions) among them — the part the frontend highlights. */unexpected: number;/** The most frequent source · code (null when there are no errors). */@@ -2880,8 +2872,9 @@ export interface UsageErrors {* GET /api/projects/:projectId/usage/errors — one page of the error detail table, newest* first. The dashboard response above already carries the first page; this exists so* "show me earlier ones" does not have to refetch the whole aggregate. It takes the same- * date/agent filter as the dashboard, so a page never widens what the summary counted, plus- * an optional `kind` ({@link UsageErrorKind}) narrowing to one of the two categories — which+ * date/agent filter as the dashboard (`fromTs`/`toTs` narrow it to a trailing window, both+ * or neither), so a page never widens what the summary counted, plus an optional `kind`+ * ({@link UsageErrorKind}) narrowing to one of the two categories — which* is how the cost-center badge asks "are there unexpected errors, and how new is the newest"* with `limit=1` instead of pulling the whole dashboard aggregate.*/@@ -2893,11 +2886,15 @@ export interface UsageErrorsPage {/*** DELETE /api/projects/:projectId/usage/errors — empties the error table for the filter the- * panel is showing (its date range and Agent), Project owner only.+ * panel is showing (its date range, the trailing window when one is on, and Agent), Project+ * owner only.** Scoped to the filter rather than the Project's whole history, so a clear takes exactly the- * rows on screen. Errors with no Project attribution are never included, whoever asks: they- * belong to no Project and are surfaced in every Project's admin view.+ * rows on screen — for an admin, the unattributed rows an admin's panel shows included; a+ * member's panel never shows them and a member's clear never takes them.+ *+ * `from` and `to` are both required (400 otherwise), where the reads treat them as optional:+ * an absent bound is unbounded on that side, which is the whole history rather than a filter.*/export interface UsageErrorsClearResponse {/** How many rows were deleted, so the caller can say what went instead of guessing. */diff --git a/packages/server/src/db/repos/errors.ts b/packages/server/src/db/repos/errors.tsindex 2f92c4c0..2daa2ad5 100644--- a/packages/server/src/db/repos/errors.ts+++ b/packages/server/src/db/repos/errors.ts@@ -52,6 +52,12 @@ export interface ErrorRecordInsert {export interface ErrorFilter {from?: string;to?: string;+ /**+ * Instant bounds (UTC ISO strings, the spelling `ts` is written in) narrowing the date+ * range to a trailing window — the last hour, the last 24 hours. Both or neither.+ */+ fromTs?: string;+ toTs?: string;agentId?: string;/** One error category (`unexpected` / `expected`); absent counts both, which is what the panel shows. */kind?: string;@@ -153,6 +159,14 @@ export class ErrorsRepo {conds.push("date <= :to");params.to = f.to;}+ if (f.fromTs !== undefined) {+ conds.push("ts >= :fromTs");+ params.fromTs = f.fromTs;+ }+ if (f.toTs !== undefined) {+ conds.push("ts <= :toTs");+ params.toTs = f.toTs;+ }if (f.agentId !== undefined) {// Filtering by Agent naturally leaves only that Agent's errors (HTTP / process-level errors have no agent_id).conds.push("agent_id = :agentId");@@ -221,23 +235,18 @@ export class ErrorsRepo {/*** Deletes the rows a matching read would have returned, and answers how many went.*- * The WHERE comes from the same `conds` the SELECTs use, so the delete can never reach a row- * the caller's own reads could not: narrowing a filter narrows both halves together, and- * there is no second expression to drift.- *- * `includeGlobal` is deliberately not accepted. Unattributed rows belong to no Project and- * appear in EVERY Project's admin view, so a Project-scoped clear that took them would empty- * them out of every other Project's panel as well — the same line deleteByProject and- * deleteByAgent already draw. Clearing them is an admin-wide act and needs an admin-wide- * surface, not a side effect of tidying one Project.- *- * The `Omit` on the parameter says that, but it does not enforce it: excess-property checking- * only fires on a fresh object literal, so a caller already holding an `ErrorFilter` could- * forward one carrying `includeGlobal: true` and compile clean. Hence the explicit `false`- * below — the guard is in the query, where a future caller cannot get around it.+ * The WHERE comes from the same `conds` the SELECTs use, `includeGlobal` included, so the+ * delete reaches exactly the rows the caller's own reads reach and never one more: narrowing+ * a filter narrows both halves together, and there is no second expression to drift. The+ * caller passes the `includeGlobal` it reads with — an admin's clear takes the unattributed+ * rows an admin's panel shows, and a member's clear, like a member's read, never sees them.+ * Unattributed rows sit in every Project's admin view, so clearing them from one Project's+ * panel clears them from every other's too: that is the one person who can see them anywhere+ * emptying instance-wide noise, not one tenant reaching into another. deleteByProject and+ * deleteByAgent keep leaving them alone — a cascade is not a person deciding to clear.*/- deleteFiltered(projectId: string, f: Omit<ErrorFilter, "includeGlobal"> = {}): number {- const { where, params } = this.conds(projectId, { ...f, includeGlobal: false });+ deleteFiltered(projectId: string, f: ErrorFilter = {}): number {+ const { where, params } = this.conds(projectId, f);const res = this.db.prepare(`DELETE FROM error_records WHERE ${where}`).run(params);return Number(res.changes);}diff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.tsindex cef1374f..665a61b4 100644--- a/packages/server/src/http/routes/usage.ts+++ b/packages/server/src/http/routes/usage.ts@@ -5,13 +5,16 @@* sets the time-series precision, defaulting to day; fromTs/toTs bound a* trailing window down to instants — required for minute — and must be given* together);- * GET /api/projects/:p/usage/errors?offset&limit&from&to&agentId&kind — one page of the error- * detail table, for paging back past the first page the dashboard already returns;- * DELETE /api/projects/:p/usage/errors?from&to&agentId — empties that table for the filter- * the panel is showing (owner only);+ * GET /api/projects/:p/usage/errors?offset&limit&from&to&fromTs&toTs&agentId&kind — one page+ * of the error detail table, for paging back past the first page the dashboard already+ * returns;+ * DELETE /api/projects/:p/usage/errors?from&to&fromTs&toTs&agentId — empties that table for+ * the filter the panel is showing (owner only; `from`/`to` are required, unlike on the reads;+ * an admin's clear also takes the unattributed rows an admin's read shows);* GET /api/projects/:p/usage/model-totals — lifetime Token total per Model, unfiltered.*/import { Hono } from "hono";+import type { Context } from "hono";import type {UsageErrorKind,UsageErrorsClearResponse,@@ -31,8 +34,8 @@ const ERROR_KINDS: readonly UsageErrorKind[] = ["unexpected", "expected"];/*** Parse an optional ISO-8601 timestamp parameter, normalized to the UTC ISO- * form the usage rows record — string comparison against `usage_records.ts`- * only works with both sides in that one spelling.+ * form the rows record — string comparison against `usage_records.ts` and+ * `error_records.ts` only works with both sides in that one spelling.*/function optionalTsParam(value: string | undefined, label: string): string | undefined {if (value === undefined || value === "") return undefined;@@ -41,6 +44,22 @@ function optionalTsParam(value: string | undefined, label: string): string | undreturn new Date(ms).toISOString();}+/**+ * The optional trailing-window pair, normalized: both or neither, and in order. One parser+ * for the dashboard and the two error routes, so a window means the same thing to all three.+ */+function tsWindowQuery(c: Context<AppEnv>): { fromTs?: string; toTs?: string } {+ const fromTs = optionalTsParam(c.req.query("fromTs"), "fromTs");+ const toTs = optionalTsParam(c.req.query("toTs"), "toTs");+ if ((fromTs === undefined) !== (toTs === undefined)) {+ throw badRequest("fromTs and toTs must be given together.");+ }+ if (fromTs !== undefined && toTs !== undefined && fromTs > toTs) {+ throw badRequest("fromTs must not be after toTs.");+ }+ return { ...(fromTs !== undefined ? { fromTs } : {}), ...(toTs !== undefined ? { toTs } : {}) };+}+export function usageRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();@@ -59,14 +78,7 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {const granularity = granularityRaw as UsageGranularity;const from = optionalDateParam(c.req.query("from"), "from");const to = optionalDateParam(c.req.query("to"), "to");- const fromTs = optionalTsParam(c.req.query("fromTs"), "fromTs");- const toTs = optionalTsParam(c.req.query("toTs"), "toTs");- if ((fromTs === undefined) !== (toTs === undefined)) {- throw badRequest("fromTs and toTs must be given together.");- }- if (fromTs !== undefined && toTs !== undefined && fromTs > toTs) {- throw badRequest("fromTs must not be after toTs.");- }+ const window = tsWindowQuery(c);const agentId = c.req.query("agentId");const provider = c.req.query("provider");const modelId = c.req.query("modelId");@@ -74,8 +86,7 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {await deps.usageService.query(projectId, {groupBy: groupByRaw as UsageGroupBy,granularity,- ...(fromTs !== undefined ? { fromTs } : {}),- ...(toTs !== undefined ? { toTs } : {}),+ ...window,// Unattributed errors (login failures, process crashes, etc. with no Project// context) are visible only to admins: requireProjectAccess only guarantees// "is a member of this Project" — a regular member seeing another tenant's errors@@ -111,6 +122,7 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {const { offset, limit } = paginationQuery(c);const from = optionalDateParam(c.req.query("from"), "from");const to = optionalDateParam(c.req.query("to"), "to");+ const window = tsWindowQuery(c);const agentId = c.req.query("agentId");const kindRaw = c.req.query("kind");// `kind` narrows to one of the two categories the panel's stats already separate. It is@@ -132,15 +144,17 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {includeGlobalErrors: c.var.user.isAdmin,...(from !== undefined ? { from } : {}),...(to !== undefined ? { to } : {}),+ ...window,...(agentId !== undefined && agentId !== "" ? { agentId } : {}),...(kindRaw !== undefined && kindRaw !== "" ? { kind: kindRaw } : {}),}),);});- // Empties the error table for the filter the panel is showing. Takes the same date/agent- // filter as the two reads above and no other: a clear removes exactly the rows the caller- // was looking at, never the Project's whole history behind a narrowed view. `kind` is not+ // Empties the error table for the filter the panel is showing. Takes the same date, window+ // and agent filter as the two reads above and no other: a clear removes exactly the rows the+ // caller was looking at, never the Project's whole history behind a narrowed view — the date+ // range is required for that reason, where the reads leave it optional. `kind` is not// accepted — the panel has no control for it, so a clear can offer no narrowing its reader// could have seen on screen.app.delete("/errors", (c) => {@@ -151,14 +165,26 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {deps.projectService.requireProjectOwner(c.var.user.userId, projectId);const from = optionalDateParam(c.req.query("from"), "from");const to = optionalDateParam(c.req.query("to"), "to");+ // Both bounds are required here, unlike on the two reads: a missing bound reads as+ // unbounded on that side, and an unbounded clear is the Project's entire history — for an+ // admin, every unattributed row in the instance along with it, rows that sit in every+ // other Project's admin panel. The panel already withholds the action while either date+ // input is blank (see clearableFilter); this is that same rule where it can be enforced,+ // rather than a promise only the caller who uses the UI keeps.+ if (from === undefined || to === undefined) {+ throw badRequest("from and to are both required.");+ }+ const window = tsWindowQuery(c);const agentId = c.req.query("agentId");- // No `includeGlobalErrors` counterpart to the reads above, on purpose. Unattributed rows- // (login failures, process crashes) are admin-only to READ, and are excluded from every- // clear — so the delete's reach is strictly narrower than any caller's, and a clear can- // never become a way to remove a row its caller was not allowed to see.+ // The same admin visibility the reads above carry, so a clear takes exactly the rows the+ // caller's panel showed. An admin's panel shows the unattributed rows (login failures,+ // process crashes) and so an admin's clear takes them; a member's never shows them, so a+ // clear can never become a way to remove a row its caller was not allowed to see.const deleted = deps.usageService.clearErrors(projectId, {- ...(from !== undefined ? { from } : {}),- ...(to !== undefined ? { to } : {}),+ includeGlobalErrors: c.var.user.isAdmin,+ from,+ to,+ ...window,...(agentId !== undefined && agentId !== "" ? { agentId } : {}),});return c.json({ deleted } satisfies UsageErrorsClearResponse);diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.tsindex 50a076bd..97479e4c 100644--- a/packages/server/src/services/usage-service.ts+++ b/packages/server/src/services/usage-service.ts@@ -111,6 +111,9 @@ export interface UsageErrorsQuery {limit: number;from?: string;to?: string;+ /** The trailing window narrowing those dates (see {@link UsageQuery}); both or neither. */+ fromTs?: string;+ toTs?: string;agentId?: string;/** Narrow to one category — `unexpected` (500s / runtime exceptions) or `expected`; absent counts both. */kind?: string;@@ -119,15 +122,19 @@ export interface UsageErrorsQuery {}/**- * What a clear removes (see {@link UsageService.clearErrors}): the panel's own date range and- * Agent, and nothing else. No `kind` — the panel offers no such control, so a clear has no- * narrowing the reader could have seen — and no `includeGlobalErrors`, since unattributed rows- * are never a Project's to delete.+ * What a clear removes (see {@link UsageService.clearErrors}): the panel's own range — dates,+ * and the trailing window when one is on — and Agent, read with the same admin visibility the+ * panel has. No `kind`: the panel offers no such control, so a clear has no narrowing the+ * reader could have seen.*/export interface UsageErrorsClearQuery {from?: string;to?: string;+ fromTs?: string;+ toTs?: string;agentId?: string;+ /** Admin only, the value the caller's reads carry: an admin's clear takes the unattributed rows an admin's panel shows. */+ includeGlobalErrors?: boolean;}/** Cost formula: sum of the three buckets at the tier these Tokens ran in, USD per million. */@@ -266,11 +273,13 @@ export class UsageService {...ts,}): seriesRows;- // Error statistics: likewise not affected by the model filter (HTTP / process errors have no Model dimension), but still affected by the date + agent filter.+ // Error statistics: likewise not affected by the model filter (HTTP / process errors have no Model dimension), but still affected by the date + agent filter — and by the trailing window, like every other range-scoped aggregate.const errorFilter: ErrorFilter = {...(q.agentId !== undefined ? { agentId: q.agentId } : {}),...(q.from !== undefined ? { from: q.from } : {}),...(q.to !== undefined ? { to: q.to } : {}),+ ...(q.fromTs !== undefined ? { fromTs: q.fromTs } : {}),+ ...(q.toTs !== undefined ? { toTs: q.toTs } : {}),// Unattributed errors are visible only to admins (regular members only see errors within their own Project, see the ErrorsRepo file header)....(q.includeGlobalErrors === true ? { includeGlobal: true } : {}),};@@ -323,6 +332,8 @@ export class UsageService {...(q.agentId !== undefined ? { agentId: q.agentId } : {}),...(q.from !== undefined ? { from: q.from } : {}),...(q.to !== undefined ? { to: q.to } : {}),+ ...(q.fromTs !== undefined ? { fromTs: q.fromTs } : {}),+ ...(q.toTs !== undefined ? { toTs: q.toTs } : {}),...(q.kind !== undefined ? { kind: q.kind } : {}),...(q.includeGlobalErrors === true ? { includeGlobal: true } : {}),};@@ -335,20 +346,21 @@ export class UsageService {/*** Empties the error table for the filter the panel is showing, and answers how many rows went.*- * The filter is the same date range and Agent the dashboard and the paged route take, so a- * clear removes exactly the set the caller was looking at and never a row outside it: a- * reader who has narrowed to one Agent and one week does not lose the rest of the year to a- * button that said "clear".- *- * Unattributed rows are outside every clear (see ErrorsRepo.deleteFiltered): they carry no- * Project, so they are not this Project's to remove, and the delete's scope is therefore- * strictly narrower than what any caller — admin included — is allowed to read.+ * The filter is the same range (dates, and the trailing window when one is on) and Agent+ * the dashboard and the paged route take, read with the same admin visibility, so a clear+ * removes exactly the set the caller was looking at and never a row outside it: a reader+ * who has narrowed to one Agent and one week does not lose the rest of the year to a button+ * that said "clear", and an admin whose panel showed unattributed rows is not left holding+ * them after clearing it (see ErrorsRepo.deleteFiltered).*/clearErrors(projectId: string, q: UsageErrorsClearQuery): number {return this.errors.deleteFiltered(projectId, {...(q.agentId !== undefined ? { agentId: q.agentId } : {}),...(q.from !== undefined ? { from: q.from } : {}),...(q.to !== undefined ? { to: q.to } : {}),+ ...(q.fromTs !== undefined ? { fromTs: q.fromTs } : {}),+ ...(q.toTs !== undefined ? { toTs: q.toTs } : {}),+ ...(q.includeGlobalErrors === true ? { includeGlobal: true } : {}),});}@@ -357,13 +369,6 @@ export class UsageService {const { total, unexpected } = this.errors.summary(projectId, f);return {total,- // Counted the way deleteFiltered selects — without the unattributed rows an admin's read- // includes — so the clear confirmation states what will really go rather than what is on- // screen. Identical to `total` for everyone whose read did not include them.- clearable:- f.includeGlobal === true- ? this.errors.summary(projectId, { ...f, includeGlobal: false }).total- : total,unexpected,topCode: this.errors.topCode(projectId, f),recent: this.errors.recent(projectId, f, ERROR_RECENT_N),diff --git a/packages/server/test/errors.test.ts b/packages/server/test/errors.test.tsindex b2e9dd21..08d1f6b6 100644--- a/packages/server/test/errors.test.ts+++ b/packages/server/test/errors.test.ts@@ -131,6 +131,31 @@ describe("errors-repo", () => {expect(repo.recent("p1", { agentId: "a1" })).toHaveLength(1);});+ it("a trailing window narrows the dates to instants, both ends inclusive, for reads and the clear alike", () => {+ const window = {+ from: "2026-07-06",+ to: "2026-07-06",+ fromTs: "2026-07-06T10:00:00.000Z",+ toTs: "2026-07-06T11:00:00.000Z",+ };+ for (const [time, message] of [+ ["09:59:59.999", "just before"],+ ["10:00:00.000", "at from"],+ ["10:30:00.000", "inside"],+ ["11:00:00.000", "at to"],+ ["11:00:00.001", "just after"],+ ] as const) {+ repo.insert(row("2026-07-06", { ts: `2026-07-06T${time}Z`, message }));+ }+ // A row stamped exactly on either bound is inside the window …+ expect(repo.summary("p1", window)).toEqual({ total: 3, unexpected: 3 });+ expect(repo.recent("p1", window).map((r) => r.message)).toEqual(["at to", "inside", "at from"]);+ // … and the clear of the same window takes exactly those, sparing the same day's rows a+ // millisecond outside it.+ expect(repo.deleteFiltered("p1", window)).toBe(3);+ expect(repo.recent("p1").map((r) => r.message)).toEqual(["just after", "just before"]);+ });+it("recent errors: newest first, top limit rows", () => {repo.insert(row("2026-07-05", { message: "old" }));repo.insert(row("2026-07-06", { message: "new" }));@@ -169,20 +194,24 @@ describe("errors-repo", () => {expect(repo.recent("p1").map((r) => r.message)).toEqual(["after-range", "before-range"]);});- it("deleteFiltered: never reaches unattributed rows or another Project's", () => {- // Unattributed rows appear in EVERY Project's admin view, so a Project-scoped clear that- // took them would empty them out of every other Project's panel as well.+ it("deleteFiltered follows the caller's includeGlobal: a member's clear leaves unattributed rows, an admin's takes them", () => {+ // Unattributed rows appear in every Project's admin view and in no member's. The clear+ // reaches exactly what the caller's read reaches, so only a read that includes them+ // deletes them; another Project's rows are out of reach either way.repo.insert(row("2026-07-06", { projectId: null, source: "process", message: "crash" }));repo.insert(row("2026-07-06", { projectId: "p-other", message: "other tenant" }));repo.insert(row("2026-07-06", { message: "mine" }));-- expect(repo.deleteFiltered("p1")).toBe(1);- expect(+ const remaining = () =>db.prepare("SELECT message FROM error_records ORDER BY id").all()- .map((r) => r.message),- ).toEqual(["crash", "other tenant"]);+ .map((r) => r.message);++ expect(repo.deleteFiltered("p1")).toBe(1);+ expect(remaining()).toEqual(["crash", "other tenant"]);++ expect(repo.deleteFiltered("p1", { includeGlobal: true })).toBe(1);+ expect(remaining()).toEqual(["other tenant"]);});// —— Row cap (the second line of defense against error storms; the first is ErrorRecorder's short-window dedup) ——@@ -1131,11 +1160,6 @@ describe("HTTP onError persistence (integration)", () => {expect(adminBody.errors.total).toBe(1);expect(adminBody.errors.topCode).toMatchObject({ source: "http", code: "invalid_credentials" });expect(adminBody.errors.recent[0]).toMatchObject({ code: "invalid_credentials" });- // …but not clear it. The clear confirmation states `clearable`, so what it promises is what- // the delete can really take: the read reaches this row, no Project-scoped delete does.- expect(adminBody.errors.clearable).toBe(0);- // A member's read never included them, so the two numbers are the same one.- expect(plainBody.errors.clearable).toBe(0);});it("the paged error route pages inside the caller's own tenant, at every offset", async () => {@@ -1277,11 +1301,47 @@ describe("HTTP onError persistence (integration)", () => {expect(await ranged.json()).toEqual({ deleted: 1 });expect(errorRows().map((r) => r.code)).toEqual(["before_range", "after_range"]);- // No filter clears the Project's whole history, which is what an unfiltered panel showed.- expect(await (await api.delete(`/api/projects/${projectId}/usage/errors`)).json()).toEqual({- deleted: 2,- });- expect(errorRows()).toHaveLength(0);+ // A missing bound is refused rather than read as unbounded: an open side is the Project's+ // whole history, which is wider than any filter a panel could have shown.+ for (const query of ["", "?from=2026-07-06", "?to=2026-07-06"]) {+ const refused = await api.delete(`/api/projects/${projectId}/usage/errors${query}`);+ expect(refused.status).toBe(400);+ }+ // Those refusals are themselves recorded by onError, so the seeded rows are what is+ // checked: nothing outside the two deletes above went.+ expect(+ errorRows()+ .map((r) => r.code)+ .filter((code) => code !== "bad_request"),+ ).toEqual(["before_range", "after_range"]);+ });++ it("a trailing-window clear deletes exactly the rows the window listed", async () => {+ const day = "2026-07-06";+ seedRow({ date: day, code: "before_window", ts: `${day}T09:59:59.999Z` });+ seedRow({ date: day, code: "at_from", ts: `${day}T10:00:00.000Z` });+ seedRow({ date: day, code: "at_to", ts: `${day}T11:00:00.000Z` });+ seedRow({ date: day, code: "after_window", ts: `${day}T11:00:00.001Z` });+ const window = `from=${day}&to=${day}&fromTs=${day}T10:00:00.000Z&toTs=${day}T11:00:00.000Z`;++ // What the panel lists for the window …+ const listed = (await (+ await api.get(`/api/projects/${projectId}/usage/errors?offset=0&limit=20&${window}`)+ ).json()) as UsageErrorsPage;+ expect(listed.items.map((e) => e.code)).toEqual(["at_to", "at_from"]);+ expect(listed.total).toBe(2);++ // … is what the clear of the same window takes: the same day's rows a millisecond+ // outside it stay.+ const cleared = await api.delete(`/api/projects/${projectId}/usage/errors?${window}`);+ expect(await cleared.json()).toEqual({ deleted: 2 });+ expect(errorRows().map((r) => r.code)).toEqual(["before_window", "after_window"]);++ // Half a window is refused, as the dashboard refuses it.+ const half = await api.delete(+ `/api/projects/${projectId}/usage/errors?fromTs=${day}T10:00:00.000Z`,+ );+ expect(half.status).toBe(400);});it("a member cannot clear the log, so it is no route to the unattributed rows", async () => {@@ -1319,10 +1379,10 @@ describe("HTTP onError persistence (integration)", () => {expect(seeded()).toEqual(["project_row", "unattributed_row"]);});- it("unattributed rows survive every clear, including an admin's own", async () => {- // They belong to no Project and show in EVERY Project's admin view, so a Project-scoped- // clear taking them would empty them out of every other Project's panel too. That keeps- // the delete strictly narrower than any caller's read, admin included.+ it("an admin's clear takes the unattributed rows an admin's read showed", async () => {+ // They show in every Project's admin view and in no member's, so the clear follows the+ // read: the one person who can see them anywhere empties them from the panel that showed+ // them, while a member's clear (whose read never lists them) never reaches them.const adminApi = apiClient(t.app, (await loginAdmin(t.app)).cookie);new ErrorsRepo(t.deps.db).insert({ts: "2026-07-06T00:00:00.000Z",@@ -1342,9 +1402,11 @@ describe("HTTP onError persistence (integration)", () => {).json()) as UsageErrorsPage;expect(before.items.map((e) => e.code)).toEqual(["uncaught_exception"]);- const cleared = await adminApi.delete(`/api/projects/default_project/usage/errors`);- expect(await cleared.json()).toEqual({ deleted: 0 });- expect(errorRows().filter((r) => r.project_id === null)).toHaveLength(1);+ const cleared = await adminApi.delete(+ `/api/projects/default_project/usage/errors?from=2026-07-06&to=2026-07-06`,+ );+ expect(await cleared.json()).toEqual({ deleted: 1 });+ expect(errorRows().filter((r) => r.project_id === null)).toHaveLength(0);});it("Project deletion cascade-cleans that Project's error records", async () => {diff --git a/packages/web/e2e/chat-tweaks.spec.mjs b/packages/web/e2e/chat-tweaks.spec.mjsindex 7c7017be..f23f00d5 100644--- a/packages/web/e2e/chat-tweaks.spec.mjs+++ b/packages/web/e2e/chat-tweaks.spec.mjs@@ -95,7 +95,7 @@ test("schedule form pickers and details Session-id copy", async ({ page }) => {await page.getByPlaceholder(/输入消息/).waitFor();await page.locator('button[title="Session 信息"]').click();await expect(page.getByText(sessionId, { exact: true }).first()).toBeVisible();- const copyBtn = page.getByRole("button", { name: "复制 Session id" });+ const copyBtn = page.getByRole("button", { name: "复制 Session ID" });await copyBtn.click();expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(sessionId);// Feedback at the button: tooltip flips while copied; the accessible name (aria-label)@@ -107,7 +107,7 @@ test("schedule form pickers and details Session-id copy", async ({ page }) => {// while the button itself stays icon-only, as asserted right above.await expect(page.getByText("已复制", { exact: true })).toHaveCount(1);// …and both halves clear once the copied flash ends (1.5s).- await expect(copyBtn).toHaveAttribute("title", "复制 Session id", { timeout: 5_000 });+ await expect(copyBtn).toHaveAttribute("title", "复制 Session ID", { timeout: 5_000 });await expect(page.getByText("已复制", { exact: true })).toHaveCount(0);// The section label above the id is not the feedback target — it stays "Session id".await expect(page.getByText("Session id", { exact: true })).toBeVisible();diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 929cffe6..8cbd9e30 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -874,8 +874,8 @@ export const importAgentTrace = (projectId: string, agentId: string, body: Trace/*** One page of the cost center's error table (newest first). The dashboard response already* carries the first page; this is for paging back to earlier ones without refetching the- * whole aggregate. Takes the dashboard's date/agent filter only — the model filter never- * applied to errors.+ * whole aggregate. Takes the dashboard's date/agent filter (and its trailing window, when one+ * is on) only — the model filter never applied to errors.*/export const getUsageErrors = (projectId: string,@@ -884,6 +884,9 @@ export const getUsageErrors = (limit: number;from?: string;to?: string;+ /** The trailing window narrowing those dates; both or neither. */+ fromTs?: string;+ toTs?: string;agentId?: string;/** Narrow to one category; the cost-center badge asks for `unexpected` with `limit: 1`. */kind?: UsageErrorKind;@@ -895,25 +898,34 @@ export const getUsageErrors = (limit: String(params.limit),from: params.from,to: params.to,+ fromTs: params.fromTs,+ toTs: params.toTs,agentId: params.agentId,kind: params.kind,},});/**- * Empties the cost center's error table for the filter the panel is showing — the same- * date/agent pair the reads take, so what goes is what was on screen. Owner only, and errors- * with no Project attribution are never included. Answers how many rows were deleted.+ * Empties the cost center's error table for the filter the panel is showing — the same dates,+ * trailing window and Agent the reads take, so what goes is what was on screen (for an admin,+ * the unattributed rows an admin's panel shows included). Owner only. Answers how many rows+ * were deleted.*/export const clearUsageErrors = (projectId: string,- params: { from?: string; to?: string; agentId?: string },+ params: { from?: string; to?: string; fromTs?: string; toTs?: string; agentId?: string },) =>apiFetch<UsageErrorsClearResponse>(`/api/projects/${encodeURIComponent(projectId)}/usage/errors`,{method: "DELETE",- query: { from: params.from, to: params.to, agentId: params.agentId },+ query: {+ from: params.from,+ to: params.to,+ fromTs: params.fromTs,+ toTs: params.toTs,+ agentId: params.agentId,+ },},);diff --git a/packages/web/src/components/ui/session-row-menu.tsx b/packages/web/src/components/ui/session-row-menu.tsxindex 3f4f2e3c..de015dc9 100644--- a/packages/web/src/components/ui/session-row-menu.tsx+++ b/packages/web/src/components/ui/session-row-menu.tsx@@ -10,8 +10,8 @@* pointer entry is the ellipsis; delete moved inside the menu with them (still* danger-styled there), keeping the hover surface to one safe direct action.* - Right-clicking a row (or holding it on touch, Shift+F10 on the keyboard, or clicking- * the ellipsis) opens the whole set — pin, rename, messaging, archive, delete — as a- * labelled menu.+ * the ellipsis) opens the whole set — pin, rename, messaging, archive, copy id, delete —+ * as a labelled menu.** Rename therefore keeps a home: every Session must stay renamable, archivable and* deletable, and paring the hover affordance down would otherwise have dropped rename@@ -80,14 +80,15 @@ export const HOVER_ROW_ACTIONS: readonly SessionRowAction[] = ["archive"];/*** The context menu's actions. Pin only reorders rows in the active list, so folder rows* (archived / subagent / scheduled) offer the rest without it — the same gate the- * ellipsis menu applied before this moved. Copying the id sits next to rename, the other- * action about which Session this is rather than what happens to it, and the messaging- * binding sits with them, before the archive/delete pair.+ * ellipsis menu applied before this moved. The order runs from the actions that change+ * the Session to the one that ends it: pin, rename and the messaging binding first, then+ * archive, then copying the id — the one row that changes nothing, kept between archive+ * and delete — and delete last.*/export function contextMenuActions(canPin: boolean): readonly SessionRowAction[] {return canPin- ? ["pin", "rename", "copy", "messaging", "archive", "delete"]- : ["rename", "copy", "messaging", "archive", "delete"];+ ? ["pin", "rename", "messaging", "archive", "copy", "delete"]+ : ["rename", "messaging", "archive", "copy", "delete"];}export interface SessionRowMenuItem {diff --git a/packages/web/src/features/dock/dock-panel.tsx b/packages/web/src/features/dock/dock-panel.tsxindex c0fdb344..bca7a15e 100644--- a/packages/web/src/features/dock/dock-panel.tsx+++ b/packages/web/src/features/dock/dock-panel.tsx@@ -47,6 +47,7 @@ import {subscribeTerminalViewStates,terminalViewContainer,terminalViewState,+ subscribeTerminalCloseRequests,} from "../terminal/terminal-view-pool";import type { TerminalInfo } from "../terminal/terminal-view";import { createShellInDock, detachTerminal, openTerminalInDock } from "./dock-terminal";@@ -130,6 +131,8 @@ function DockTabButton(props: {/** Attention dot (e.g. a pending approval inside a subagent) shown beside the name. */badge: boolean;closeLabel: string;+ /** The keyboard shortcut that runs the same close, named after the label in the ×'s tooltip. */+ closeShortcut?: string;onSelect: () => void;onClose: () => void;/** Terminal tabs keep their id on the node for tests and the strip's drag targeting. */@@ -163,7 +166,11 @@ function DockTabButton(props: {</button><buttontype="button"- title={props.closeLabel}+ title={+ props.closeShortcut !== undefined+ ? `${props.closeLabel} (${props.closeShortcut})`+ : props.closeLabel+ }aria-label={`${props.closeLabel}: ${props.label}`}data-testid="dock-tab-close"onClick={props.onClose}@@ -628,6 +635,19 @@ export function DockPanel({if (tab.kind === "terminal") terminalOrdinals.set(tab.terminalId, terminalOrdinals.size + 1);});+ // Ctrl+W inside a shown terminal asks for its tab to close, and takes the × path above,+ // confirmation included. Only the dock holding that tab answers — and not while it is+ // collapsing out, when the merged view may list the same tab — so no request is answered+ // twice. The ref keeps one subscription per mount while the handler reads the current tabs.+ const closeRequest = useRef<(id: string) => void>(() => {});+ closeRequest.current = (id) => {+ if (!open) return;+ const tab = tabs.find((t) => t.kind === "terminal" && t.terminalId === id);+ if (!tab) return;+ closeTab(tab, terminalLabel(terminalById.get(id), id, terminalOrdinals.get(id) ?? 1));+ };+ useEffect(() => subscribeTerminalCloseRequests((id) => closeRequest.current(id)), []);+const header = (<headerdata-testid="dock-header"@@ -679,6 +699,7 @@ export function DockPanel({active={key === activeKey}badge={false}closeLabel={S.terminal.killShell}+ closeShortcut="Ctrl+W"onSelect={() => activateTab(key)}onClose={() => closeTab(tab, label)}/>diff --git a/packages/web/src/features/terminal/terminal-page.tsx b/packages/web/src/features/terminal/terminal-page.tsxindex 19e3dbe0..d9a58bb7 100644--- a/packages/web/src/features/terminal/terminal-page.tsx+++ b/packages/web/src/features/terminal/terminal-page.tsx@@ -18,7 +18,9 @@*/import { useCallback, useMemo, useState } from "react";import { S } from "../../lib/strings";+import { ConfirmModal } from "../../components/ui/confirm-modal";import { useTerminalChrome } from "./terminal-appearance";+import { killTerminal } from "./terminal-list";import {TerminalView,fetchJson,@@ -132,6 +134,22 @@ export function TerminalPage() {setDetail(statusDetail);}, []);+ /**+ * Ctrl+W inside the terminal takes the dock tab's × path — confirm, then end the shell —+ * and then closes this window, which exists only to host that shell. A window the browser+ * will not let a script close (one opened by address rather than by the dock's detach)+ * stays, showing the exited shell with "New shell" one click away. The kill is awaited+ * first so the dock's detach watcher, which probes the shell when the window closes, finds+ * it ended rather than restoring a tab for it.+ */+ const [confirmKill, setConfirmKill] = useState(false);+ const killConfirmed = useCallback(async () => {+ if (!info) return;+ setConfirmKill(false);+ await killTerminal(info.id);+ window.close();+ }, [info]);+const statusText =status === "exited" && detail? `${S.terminal.status.exited} — ${S.terminal.exitedWithCode(detail)}`@@ -171,8 +189,22 @@ export function TerminalPage() {ensure={ensure}onStatus={onStatus}onInfo={setInfo}+ onCloseRequest={info ? () => setConfirmKill(true) : undefined}className="min-h-0 flex-1 overflow-hidden px-2 py-1"/>+ <ConfirmModal+ open={confirmKill}+ title={S.dock.killConfirmTitle}+ onClose={() => setConfirmKill(false)}+ onConfirm={() => void killConfirmed()}+ confirmLabel={S.terminal.killShell}+ >+ {info && (+ <p className="break-words text-sm text-gray-600 dark:text-gray-300">+ {S.dock.killConfirmBody(info.name)}+ </p>+ )}+ </ConfirmModal></div>);}diff --git a/packages/web/src/features/terminal/terminal-view-pool.tsx b/packages/web/src/features/terminal/terminal-view-pool.tsxindex c06ccccd..b52b9587 100644--- a/packages/web/src/features/terminal/terminal-view-pool.tsx+++ b/packages/web/src/features/terminal/terminal-view-pool.tsx@@ -37,6 +37,22 @@ export function subscribeTerminalViewStates(listener: () => void): () => void {const IDLE_STATE: TerminalViewState = { status: "connecting", info: null };+/**+ * Listeners for a shown terminal asking to be closed (Ctrl+W inside it). A view knows only+ * its own id, while the dock holding the tab owns the close path — the confirm-then-kill+ * its × runs — so the request is relayed by id to whichever dock has that tab.+ */+const closeRequestListeners = new Set<(id: string) => void>();++export function subscribeTerminalCloseRequests(listener: (id: string) => void): () => void {+ closeRequestListeners.add(listener);+ return () => closeRequestListeners.delete(listener);+}++function requestTerminalClose(id: string): void {+ for (const listener of [...closeRequestListeners]) listener(id);+}+export function terminalViewState(id: string | null): TerminalViewState {return (id !== null ? viewStates.get(id) : undefined) ?? IDLE_STATE;}@@ -132,6 +148,7 @@ export function TerminalDockRuntime() {void refreshTerminals();}}onTitle={(title) => noteTerminalTitle(id, title)}+ onCloseRequest={() => requestTerminalClose(id)}className="min-h-0 flex-1 overflow-hidden"/>,terminalViewContainer(id),diff --git a/packages/web/src/features/terminal/terminal-view.tsx b/packages/web/src/features/terminal/terminal-view.tsxindex a2de5f01..3a30ecfa 100644--- a/packages/web/src/features/terminal/terminal-view.tsx+++ b/packages/web/src/features/terminal/terminal-view.tsx@@ -179,10 +179,23 @@ export interface TerminalViewProps {onInfo?: (info: TerminalInfo) => void;/** OSC window-title changes, parsed by this client's own xterm from the byte stream. */onTitle?: (title: string) => void;+ /**+ * Ctrl+W pressed inside this terminal. The host decides what a close is — the dock tab's+ * confirm-then-kill, the standalone page's kill-then-close-window; with no handler the key+ * goes to the shell like any other.+ */+ onCloseRequest?: () => void;className?: string;}-export function TerminalView({ ensure, onStatus, onInfo, onTitle, className }: TerminalViewProps) {+export function TerminalView({+ ensure,+ onStatus,+ onInfo,+ onTitle,+ onCloseRequest,+ className,+}: TerminalViewProps) {const hostRef = useRef<HTMLDivElement | null>(null);// The terminal's OWN appearance setting (light / dark / follow the app, defaulting to// dark — see TerminalThemeMode), not the app's. It is repainted in place rather than@@ -198,8 +211,8 @@ export function TerminalView({ ensure, onStatus, onInfo, onTitle, className }: T}, [terminalDark]);// Kept in refs so the (intentionally once-per-mount) effect always calls the latest// callbacks without re-running when a parent re-renders with a new closure.- const callbacks = useRef({ ensure, onStatus, onInfo, onTitle });- callbacks.current = { ensure, onStatus, onInfo, onTitle };+ const callbacks = useRef({ ensure, onStatus, onInfo, onTitle, onCloseRequest });+ callbacks.current = { ensure, onStatus, onInfo, onTitle, onCloseRequest };useEffect(() => {const host = hostRef.current;@@ -364,6 +377,19 @@ export function TerminalView({ ensure, onStatus, onInfo, onTitle, className }: Tif (pasteCombo) {return false; // native paste path (see above)}+ // Ctrl+W closes this terminal when the host offers a close (the dock tab's ×, the+ // standalone page). Consumed here so it never reaches the shell, where it is+ // readline's delete-word, and seen only by the terminal that has focus — xterm hands+ // this handler its own textarea's events and nothing else, so no window-level+ // listener is involved. Browsers keep Ctrl+W for closing the browser tab and may act+ // first; the desktop shell delivers it here.+ const closeCombo =+ event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey && key === "w";+ if (closeCombo && callbacks.current.onCloseRequest) {+ event.preventDefault();+ callbacks.current.onCloseRequest();+ return false;+ }return true;});diff --git a/packages/web/src/features/usage/errors-panel.tsx b/packages/web/src/features/usage/errors-panel.tsxindex 6b179393..bcd8e9fa 100644--- a/packages/web/src/features/usage/errors-panel.tsx+++ b/packages/web/src/features/usage/errors-panel.tsx@@ -28,24 +28,38 @@ type ErrorKindKey = "unexpected" | "expected";export interface ErrorsFilters {from?: string;to?: string;+ /** The trailing window narrowing those dates (the two "last …" presets); both or neither. */+ fromTs?: string;+ toTs?: string;agentId?: string;}+/** The quick range presets the clear confirmation names by name; a custom range is named by its dates. */+export type ErrorsRangePreset = "1h" | "1d" | "7d" | "30d" | "90d";+/*** The one sentence the clear confirmation has to get right: exactly which rows will go.** The delete is scoped to the filter on screen, so a dialog naming a wider set (the Project's* whole history) or a narrower one (this page of rows) would misdescribe what the button does- * — which is the entire failure a confirmation exists to prevent. Pure and exported so that is- * asserted directly: this package's vitest runs in `node`, so an opened dialog is not- * something a test can inspect.+ * — which is the entire failure a confirmation exists to prevent. The range is named the way+ * the picker names it — "the last 7 days", not the two dates standing for it, which a reader+ * would have to work back from — and only a custom range, which has no other name, is spelled+ * as its dates. Pure and exported so that is asserted directly: this package's vitest runs in+ * `node`, so an opened dialog is not something a test can inspect.*/-export function errorsClearScopeText(filters: ErrorsFilters, count: number): string {- const from = filters.from ?? "";- const to = filters.to ?? "";+export function errorsClearScopeText(+ filters: ErrorsFilters,+ preset: ErrorsRangePreset | undefined,+ count: number,+): string {+ const range =+ preset !== undefined+ ? S.usage.errorsClearRangePreset(preset)+ : S.usage.errorsClearRangeCustom(filters.from ?? "", filters.to ?? "");return filters.agentId !== undefined && filters.agentId !== ""- ? S.usage.errorsClearScopeAgent(count, from, to, filters.agentId)- : S.usage.errorsClearScope(count, from, to);+ ? S.usage.errorsClearScopeAgent(count, range, filters.agentId)+ : S.usage.errorsClearScope(count, range);}/**@@ -133,6 +147,7 @@ export function ErrorsPanel({errors,projectId,filters,+ preset,canClear,onCleared,}: {@@ -143,6 +158,8 @@ export function ErrorsPanel({* Memoize it at the call site: the fetch effect depends on the object's identity.*/filters: ErrorsFilters;+ /** The quick preset `filters` stands for, named as such in the clear confirmation; absent for a custom range. */+ preset?: ErrorsRangePreset;/*** Whether this viewer may empty the table (Project owner). A member can read the panel but* not clear it, and the route enforces that on its own; hiding the button keeps the panel@@ -152,7 +169,7 @@ export function ErrorsPanel({/** Reload the dashboard after a clear — the stats above the table are the caller's data. */onCleared: () => void;}) {- const { total, clearable, unexpected, topCode, recent } = errors;+ const { total, unexpected, topCode, recent } = errors;// Page size is read off the first page rather than duplicating the server's ERROR_RECENT_N:// whenever a second page exists at all, `recent` is exactly that many rows, so the two cannot// drift apart into skipping or repeating rows. (Empty means a single empty page anyway.)@@ -327,10 +344,9 @@ export function ErrorsPanel({The pager itself still appears only once there is more than one page. */}{(items.length > 0 || page > 0) && (<div className="mt-2 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">- {/* Offered on what the clear can really take: `clearable` excludes the unattributed- rows an admin's read includes but no Project-scoped delete removes, so a window- holding only those shows no button rather than one that deletes nothing. */}- {canClear && clearable > 0 && clearableFilter(filters) && (+ {/* Offered while there is something to take: the clear reaches exactly the rows the+ panel lists — for an admin, the unattributed rows an admin's read includes too. */}+ {canClear && total > 0 && clearableFilter(filters) && (<buttontype="button"disabled={clearing}@@ -375,7 +391,7 @@ export function ErrorsPanel({onConfirm={() => void runClear()}><div className="space-y-1.5 text-sm text-gray-700 dark:text-gray-300">- <p className="break-words">{errorsClearScopeText(filters, clearable)}</p>+ <p className="break-words">{errorsClearScopeText(filters, preset, total)}</p><p className="text-xs text-gray-500 dark:text-gray-400">{S.usage.errorsClearIrreversible}</p>diff --git a/packages/web/src/features/usage/usage-page.tsx b/packages/web/src/features/usage/usage-page.tsxindex a51460cc..56a90944 100644--- a/packages/web/src/features/usage/usage-page.tsx+++ b/packages/web/src/features/usage/usage-page.tsx@@ -132,6 +132,18 @@ function ChartCard({);}+/**+ * The range the dashboard last read: the preset and the bounds it resolved to at load time —+ * the two trailing presets add their instant pair (see `loaded` in the page).+ */+interface LoadedRange {+ preset: RangePreset;+ from: string;+ to: string;+ fromTs?: string;+ toTs?: string;+}+export function UsagePage() {useDocumentTitle(S.usage.title);const { currency } = useTheme();@@ -170,16 +182,15 @@ export function UsagePage() {};const [data, setData] = useState<UsageResponse | null>(null);/**- * The date window the dashboard actually READ, which is not always the one the picker holds.- * A trailing preset computes its window at load time and deliberately leaves `from`/`to` on+ * The range the dashboard actually READ, which is not always the one the picker holds. A+ * trailing preset computes its window at load time and deliberately leaves `from`/`to` on* whatever the last calendar preset put there, so the two diverge the moment "last hour" is- * chosen. The error panel pages against this window and, for an owner, DELETES against it —- * so it has to be the window whose rows are on screen, never the stale pair behind them.- * Kept as two primitives so the memo below holds its identity across a reload that changes- * nothing (the panel's fetch effect depends on that identity).+ * chosen. The error panel pages against this range and, for an owner, DELETES against it —+ * so it has to be the range whose rows are on screen, never the stale pair behind them. The+ * memo below reads its primitives one by one so it holds its identity across a reload that+ * changes nothing (the panel's fetch effect depends on that identity).*/- const [loadedFrom, setLoadedFrom] = useState(from);- const [loadedTo, setLoadedTo] = useState(to);+ const [loaded, setLoaded] = useState<LoadedRange>(() => ({ preset, from, to }));const [error, setError] = useState<string | null>(null);// The legend / control state that lives in the card headers (ChartCard's// extra) while the marks live inside the cards, lifted to this level.@@ -204,8 +215,7 @@ export function UsagePage() {...(modelFilter ? { provider: modelFilter.provider, modelId: modelFilter.modelId } : {}),});setData(res);- setLoadedFrom(range.from);- setLoadedTo(range.to);+ setLoaded({ preset, ...range });} catch (e) {setError(apiErrorText(e));}@@ -219,12 +229,19 @@ export function UsagePage() {// The error panel pages against this filter and depends on the object's identity, so it is// built once per filter value rather than fresh on every render — a new object each render// would refetch the current page on any unrelated state change (hovering a chart bucket).- // Built from the window the dashboard read (see loadedFrom/loadedTo), not from the picker's- // state: the panel's rows, its later pages and its clear all have to name one same set.- // The model filter is deliberately absent: it never applied to errors.+ // Built from the range the dashboard read (see `loaded`), not from the picker's state: the+ // panel's rows, its later pages and its clear all have to name one same set. The model+ // filter is deliberately absent: it never applied to errors.const errorFilters = useMemo(- () => ({ from: loadedFrom, to: loadedTo, ...(agentFilter ? { agentId: agentFilter } : {}) }),- [loadedFrom, loadedTo, agentFilter],+ () => ({+ from: loaded.from,+ to: loaded.to,+ ...(loaded.fromTs !== undefined && loaded.toTs !== undefined+ ? { fromTs: loaded.fromTs, toTs: loaded.toTs }+ : {}),+ ...(agentFilter ? { agentId: agentFilter } : {}),+ }),+ [loaded.from, loaded.to, loaded.fromTs, loaded.toTs, agentFilter],);if (!projectId) return null;@@ -435,6 +452,7 @@ export function UsagePage() {errors={data.errors}projectId={projectId}filters={errorFilters}+ preset={loaded.preset === "custom" ? undefined : loaded.preset}// Clearing the log is a Project-level management operation, gated on the owner// by the route; a member reads the panel without the action.canClear={currentProject?.role === "owner"}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 2e677c6a..85949b55 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -856,7 +856,7 @@ export const en: Strings = {* needs first and is the element that truncates.*/recommendedGroup: "Recommended",- discountBadge: (pct: number): string => `-${pct}%`,+ discountBadge: (pct: number): string => `${pct}% off`,discountTitle: (pct: number): string => `Promotion: ${pct}% off the list price`,offPeakTitle: (pct: number): string =>`Off-peak rate: ${pct}% off list. Peak hours bill at list price — 09:00–12:00 and 14:00–18:00 Beijing time, Monday to Friday`,@@ -1707,7 +1707,7 @@ Scenarios:sessionStats: "Stats",/** Info-dropdown Session id row: the id itself is a click-to-copy button. */sessionIdLabel: "Session id",- copySessionId: "Copy Session id",+ copySessionId: "Copy Session ID",/** Info-dropdown list of background processes the conversation started, and its per-row actions (Stop on running rows, Remove on exited ones). */processList: "Processes",processStop: "Stop",@@ -2328,10 +2328,19 @@ Scenarios:/** Clearing the table: the action, and the confirm that must name exactly what goes. */errorsClear: "Clear",errorsClearTitle: "Clear error records",- errorsClearScope: (count: number, from: string, to: string): string =>- `Deletes this Project's ${count} error record${count === 1 ? "" : "s"} between ${from} and ${to}. Records outside that range are kept.`,- errorsClearScopeAgent: (count: number, from: string, to: string, agentId: string): string =>- `Deletes this Project's ${count} error record${count === 1 ? "" : "s"} for agent ${agentId} between ${from} and ${to}. Other agents and other dates are kept.`,+ errorsClearRangePreset: (preset: "1h" | "1d" | "7d" | "30d" | "90d"): string =>+ ({+ "1h": "in the last hour",+ "1d": "in the last 24 hours",+ "7d": "in the last 7 days",+ "30d": "in the last 30 days",+ "90d": "in the last 90 days",+ })[preset],+ errorsClearRangeCustom: (from: string, to: string): string => `between ${from} and ${to}`,+ errorsClearScope: (count: number, range: string): string =>+ `Deletes this Project's ${count} error record${count === 1 ? "" : "s"} ${range}. Records outside that range are kept.`,+ errorsClearScopeAgent: (count: number, range: string, agentId: string): string =>+ `Deletes this Project's ${count} error record${count === 1 ? "" : "s"} for agent ${agentId} ${range}. Other agents and records outside that range are kept.`,errorsClearIrreversible: "This cannot be undone.",errorsClearDone: (count: number): string =>`Deleted ${count} error record${count === 1 ? "" : "s"}`,diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex e7c1592c..fbd23779 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -834,7 +834,7 @@ export const zh = {*/recommendedGroup: "官方推荐",/** Badge on a row the seller is currently discounting: the rate off its list price. */- discountBadge: (pct: number): string => `-${pct}%`,+ discountBadge: (pct: number): string => `省 ${pct}%`,discountTitle: (pct: number): string => `促销价:已在牌价基础上打 ${pct}% 折扣`,/** Same badge as a flat promotion; only the explanation differs, because this rate comes and goes with the clock. */offPeakTitle: (pct: number): string =>@@ -1672,7 +1672,7 @@ Benchmark:sessionStats: "统计",/** Info-dropdown Session id row: the id itself is a click-to-copy button. */sessionIdLabel: "Session id",- copySessionId: "复制 Session id",+ copySessionId: "复制 Session ID",/** Info-dropdown list of background processes the conversation started, and its per-row actions (Stop on running rows, Remove on exited ones). */processList: "会话进程",processStop: "停止",@@ -2281,10 +2281,20 @@ Benchmark:/** Clearing the table: the action, and the confirm that must name exactly what goes. */errorsClear: "清空",errorsClearTitle: "清空错误记录",- errorsClearScope: (count: number, from: string, to: string): string =>- `将删除本 Project 在 ${from} 至 ${to} 区间内的 ${count} 条错误记录,其余时间段的记录保留。`,- errorsClearScopeAgent: (count: number, from: string, to: string, agentId: string): string =>- `将删除本 Project 中 Agent「${agentId}」在 ${from} 至 ${to} 区间内的 ${count} 条错误记录,其他 Agent 与其余时间段的记录保留。`,+ /** The range half of the confirm: a quick preset by the name the picker gives it, a custom range by its two dates — each one adverbial the sentence below slots in. */+ errorsClearRangePreset: (preset: "1h" | "1d" | "7d" | "30d" | "90d"): string =>+ ({+ "1h": "最近一小时内",+ "1d": "最近一天内",+ "7d": "近 7 天内",+ "30d": "近 30 天内",+ "90d": "近 90 天内",+ })[preset],+ errorsClearRangeCustom: (from: string, to: string): string => `在 ${from} 至 ${to} 区间内`,+ errorsClearScope: (count: number, range: string): string =>+ `将删除本 Project ${range}的 ${count} 条错误记录,其余时间段的记录保留。`,+ errorsClearScopeAgent: (count: number, range: string, agentId: string): string =>+ `将删除本 Project 中 Agent「${agentId}」${range}的 ${count} 条错误记录,其他 Agent 与其余时间段的记录保留。`,errorsClearIrreversible: "此操作不可恢复。",errorsClearDone: (count: number): string => `已删除 ${count} 条错误记录`,},diff --git a/packages/web/test/errors-panel.test.ts b/packages/web/test/errors-panel.test.tsindex 41954828..f1b32d64 100644--- a/packages/web/test/errors-panel.test.ts+++ b/packages/web/test/errors-panel.test.ts@@ -30,10 +30,9 @@ const item = (code: string): UsageErrorItem => ({message: `${code} went wrong`,});-function errorsOf(items: UsageErrorItem[], clearable = items.length): UsageErrors {+function errorsOf(items: UsageErrorItem[]): UsageErrors {return {total: items.length,- clearable,unexpected: items.length,topCode: null,recent: items,@@ -45,7 +44,6 @@ const FILTERS: ErrorsFilters = { from: "2026-08-01", to: "2026-08-27" };function render(opts: {items?: UsageErrorItem[];- clearable?: number;canClear?: boolean;filters?: ErrorsFilters;} = {},@@ -53,7 +51,7 @@ function render(const items = opts.items ?? [item("internal")];return renderToStaticMarkup(createElement(ErrorsPanel, {- errors: errorsOf(items, opts.clearable ?? items.length),+ errors: errorsOf(items),projectId: "p1",filters: opts.filters ?? FILTERS,canClear: opts.canClear ?? true,@@ -76,15 +74,6 @@ describe("ErrorsPanel clear action", () => {expect(empty).not.toContain(S.usage.errorsClear);});- it("is absent when every row in range is one no Project-scoped clear can take", () => {- // An admin's read includes unattributed rows (a login failure, a process crash); the delete- // never does. A window holding only those has rows on screen and nothing to clear, so the- // action must not be offered — it could only report "deleted 0".- expect(render({ items: [item("uncaught_exception")], clearable: 0 })).not.toContain(- S.usage.errorsClear,- );- });-it("is absent while a date bound is blank: the sentence could not describe that delete", () => {// A cleared date input sends no bound, which the route reads as unbounded on that side —// wider than anything the confirmation's "records outside that range are kept" can promise.@@ -100,9 +89,9 @@ describe("ErrorsPanel clear action", () => {describe("errorsClearScopeText", () => {for (const [locale, dict] of Object.entries({ zh, en })) {- it(`${locale}: names the date range, and the Agent when one is selected`, () => {+ it(`${locale}: a custom range is named by its dates, and the Agent when one is selected`, () => {setActiveStrings(dict);- const ranged = errorsClearScopeText(FILTERS, 12);+ const ranged = errorsClearScopeText(FILTERS, undefined, 12);expect(ranged).toContain("2026-08-01");expect(ranged).toContain("2026-08-27");expect(ranged).toContain("12");@@ -110,16 +99,30 @@ describe("errorsClearScopeText", () => {// than the one about to run.expect(ranged).not.toContain("agent-7");- const perAgent = errorsClearScopeText({ ...FILTERS, agentId: "agent-7" }, 3);+ const perAgent = errorsClearScopeText({ ...FILTERS, agentId: "agent-7" }, undefined, 3);expect(perAgent).toContain("agent-7");expect(perAgent).toContain("2026-08-01");expect(perAgent).toContain("3");});++ it(`${locale}: a quick preset is named as the picker names it, never as the dates behind it`, () => {+ setActiveStrings(dict);+ for (const preset of ["1h", "1d", "7d", "30d", "90d"] as const) {+ const text = errorsClearScopeText(FILTERS, preset, 12);+ expect(text).toContain(dict.usage.errorsClearRangePreset(preset));+ expect(text).not.toContain("2026-08-01");+ expect(text).not.toContain("2026-08-27");+ expect(text).toContain("12");+ }+ const perAgent = errorsClearScopeText({ ...FILTERS, agentId: "agent-7" }, "7d", 3);+ expect(perAgent).toContain("agent-7");+ expect(perAgent).toContain(dict.usage.errorsClearRangePreset("7d"));+ });}it("an empty agentId is no filter at all (the panel's own spelling of 'all agents')", () => {- expect(errorsClearScopeText({ ...FILTERS, agentId: "" }, 4)).toBe(- errorsClearScopeText(FILTERS, 4),+ expect(errorsClearScopeText({ ...FILTERS, agentId: "" }, "7d", 4)).toBe(+ errorsClearScopeText(FILTERS, "7d", 4),);});});diff --git a/packages/web/test/session-row-menu.test.ts b/packages/web/test/session-row-menu.test.tsindex 72abdd19..890018fc 100644--- a/packages/web/test/session-row-menu.test.ts+++ b/packages/web/test/session-row-menu.test.ts@@ -52,13 +52,13 @@ describe("HOVER_ROW_ACTIONS", () => {});describe("contextMenuActions", () => {- it("carries the whole set when the row can be pinned", () => {+ it("carries the whole set when the row can be pinned, with the id copy between archive and delete", () => {expect([...contextMenuActions(true)]).toEqual(["pin","rename",- "copy","messaging","archive",+ "copy","delete",]);});@@ -66,9 +66,9 @@ describe("contextMenuActions", () => {it("drops only pin on rows where pinning cannot reorder anything (folder rows)", () => {expect([...contextMenuActions(false)]).toEqual(["rename",- "copy","messaging","archive",+ "copy","delete",]);});@@ -128,7 +128,7 @@ describe("the hover buttons' CSS contract", () => {describe("sessionRowMenuItem", () => {it("gives every action a label, a glyph, and only delete the destructive treatment", () => {- const all: SessionRowAction[] = ["pin", "rename", "copy", "messaging", "archive", "delete"];+ const all: SessionRowAction[] = ["pin", "rename", "messaging", "archive", "copy", "delete"];for (const action of all) {const item = sessionRowMenuItem(action, RESTING);expect(item.label).toBeTruthy();@@ -139,7 +139,7 @@ describe("sessionRowMenuItem", () => {it("gives the actions distinct glyphs, so a row is not read by its label alone", () => {const icons = (- ["pin", "rename", "copy", "messaging", "archive", "delete"] as SessionRowAction[]+ ["pin", "rename", "messaging", "archive", "copy", "delete"] as SessionRowAction[]).map((a) => sessionRowMenuItem(a, RESTING).icon);expect(new Set(icons).size).toBe(icons.length);// Remote control wears the same paper plane the session row flies while it is relaying:@@ -147,10 +147,10 @@ describe("sessionRowMenuItem", () => {expect(icons).toEqual([PIN_ICON,PENCIL_ICON,- // The same glyph the details card's copy button shows, so one value has one mark.- STAT_ICONS.copy,MESSAGING_RELAY_ICON,ARCHIVE_ICON,+ // The same glyph the details card's copy button shows, so one value has one mark.+ STAT_ICONS.copy,TRASH_ICON,]);});