Skip to content

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

feat(web,server): 异常表能按类型过滤,清空也只清看到的那一类

lmliheng57d20417586f
diff --git a/changelog/unreleased/2026-10-27-errors-panel-category-filter.md b/changelog/unreleased/2026-10-27-errors-panel-category-filter.md
new file mode 100644
index 00000000..dbe2d91c
--- /dev/null
+++ b/changelog/unreleased/2026-10-27-errors-panel-category-filter.md
@@ -0,0 +1,45 @@
+# The cost center's error table can narrow to one category, and Clear follows it
+
+- **Date:** 2026-10-27
+- **Type:** feat
+- **Scope:** `web`, `server`, `docs`
+- **Breaking:** no
+
+[中文](2026-10-27-errors-panel-category-filter.zh.md)
+
+The **Errors** panel at the bottom of the cost center now carries a category filter above the table
+on the right: **All**, **Unexpected**, **Expected**. Choosing one narrows the table, its paging and
+**Clear** to that category, while the summary figures above keep counting both — they are the
+range's summary. Until now, looking at unexpected errors alone meant picking them out of a dozen
+rows by hand.
+
+The clear follows the filter: the confirmation names the category and says the other one is kept
+("Deletes this Project's 1 unexpected error record in the last 7 days. The other category and
+records outside that range are kept."), and the button really does take only that one — a **Clear**
+that also swept up a category the reader could not see is exactly what a confirmation exists to
+prevent.
+
+## Details
+
+- `packages/web/src/features/usage/errors-panel.tsx`: the panel keeps its own `kindFilter` state and
+ merges it with the page's date/agent filter into `activeFilters`, which the reads, the row count,
+ the pager and the clear all go by. The dashboard snapshot has no category-narrowed page 0, so once
+ a category is chosen even page 0 is read from the server; switching category goes back to page 1
+ (page 2's offset counts the previous category's rows). The empty state has two sentences now: "no
+ errors" for All, "no errors of this type" for one category.
+- `packages/server/src/http/routes/usage.ts`: `DELETE /usage/errors` takes `kind`, validated against
+ the same `ERROR_KINDS` set the reads use (an unrecognized value is a 400 — a category that matches
+ no rows would report "cleared" while the rows are still there).
+- `packages/server/src/services/usage-service.ts`: `UsageErrorsClearQuery` gains `kind` and passes it
+ into `ErrorsRepo.deleteFiltered`'s own `conds`, so the delete and the reads share one WHERE.
+- `packages/web/src/api/endpoints.ts`, `packages/web/src/lib/strings.ts` / `strings-en.ts`: the
+ `kind` parameter and four confirmation sentences (by category, and by category plus agent), plus
+ two new copy keys.
+- `packages/ui-gallery/src/app/mock/routes.ts`: the demo clear narrows by `kind` like the real route.
+ The sample data holds 2 expected and 1 unexpected record, enough to show the difference.
+- Docs: the error panel and the clear steps in `packages/docs/content/usage.zh.md` / `usage.en.md`.
+
+## Compatibility
+
+- No dependency, on-disk format or package-name change. `kind` is optional: a request without it
+ behaves exactly as before, so an older client is unaffected.
diff --git a/changelog/unreleased/2026-10-27-errors-panel-category-filter.zh.md b/changelog/unreleased/2026-10-27-errors-panel-category-filter.zh.md
new file mode 100644
index 00000000..b7df0c5f
--- /dev/null
+++ b/changelog/unreleased/2026-10-27-errors-panel-category-filter.zh.md
@@ -0,0 +1,36 @@
+# 成本中心的异常表能按类型过滤,清空也只清看到的那一类
+
+- **Date:** 2026-10-27
+- **Type:** feat
+- **Scope:** `web`, `server`, `docs`
+- **Breaking:** no
+
+[English](2026-10-27-errors-panel-category-filter.md)
+
+成本中心页面底部的**异常**面板,表格右上方多了一个类型筛选:**全部** / **未预期** / **预期内**。选一类,
+表格、翻页和**清空**都只认这一类;上面的汇总数字仍按两类合计,因为它是整段范围的摘要。此前要单独看
+未预期异常只能自己在十几行里找。
+
+清空跟着这个筛选走:确认框会写明是哪一类、另一类保留(例如「将删除本项目 近 7 天内的 1 条「未预期」
+错误记录,另一类与其余时间段的记录保留。」),按钮也确实只删这一类 —— 点了「清空」却把没显示在屏幕上的
+另一类一起带走,正是确认框要防的事。
+
+## 细节
+
+- `packages/web/src/features/usage/errors-panel.tsx`:面板自己新增一个 `kindFilter` 状态,与页面的日期 /
+ Agent 筛选合成 `activeFilters`,取数、行数、翻页与清空全部走它。仪表盘快照里没有按类型过滤的页 0,
+ 所以选了类型后连第 0 页也改为向服务端读;切类型时页码回到第 1 页(第 2 页的偏移量是按上一类的行数算的)。
+ 空表文案分两句:全部为空是「暂无异常」,某类为空是「该类型下暂无异常」。
+- `packages/server/src/http/routes/usage.ts`:`DELETE /usage/errors` 接受 `kind`,与读接口用同一个
+ `ERROR_KINDS` 闭集校验(非法值返回 400 —— 一个认不出的类型匹配不到任何行,静默「已清空」而记录还在)。
+- `packages/server/src/services/usage-service.ts`:`UsageErrorsClearQuery` 加 `kind`,透传给
+ `ErrorsRepo.deleteFiltered` 的同一个 `conds`,删除与读取共用一处 WHERE,不会两处走偏。
+- `packages/web/src/api/endpoints.ts`、`packages/web/src/lib/strings.ts` / `strings-en.ts`:`kind` 参数与
+ 四句确认文案(按类 / 按类加 Agent)、两个新文案键。
+- `packages/ui-gallery/src/app/mock/routes.ts`:演示数据里的清空接口也按 `kind` 过滤,与真路由一致。
+ 样例数据里有 2 条预期内、1 条未预期,刚好能看出收窄前后的差别。
+- 文档:`packages/docs/content/usage.zh.md` / `usage.en.md` 的异常面板与清空步骤补上这个筛选。
+
+## 兼容性
+
+- 不改依赖、不改磁盘格式、不改包名。`kind` 是可选参数:不带它的请求与以前完全一样,旧客户端不受影响。
diff --git a/docs/FORK-PROGRESS.md b/docs/FORK-PROGRESS.md
index 12bd3923..58ae270e 100644
--- a/docs/FORK-PROGRESS.md
+++ b/docs/FORK-PROGRESS.md
@@ -17121,3 +17121,68 @@ sandbox-dsh 21(+1 跳过)· sandbox-bwrap 29。
(`shared_env/xianyu-ops/feishu_send.py`,`text ok`,`message_id=om_x100b6135ef192cb8ddbb1e6ec0937f8`),
正文留底在 scratchpad 的 `r140/report.md`。下一轮开工再探一次,通了把积压的补发到
+
+## 第一百四十一轮:模型的 TokenDance 分组重核,成本中心的异常表能按类型过滤(2026-10-27,用户点单)
+
+### 开工自检
+
+- `/root/adelie-fork` 在 `main` 上,`HEAD` = **`f57bd90a`**,与 `origin/main` 齐;工作区里只有本会话自己
+ 第四笔与第三笔的改动(13 个跟踪文件 + 2 个新 changelog),没有别的会话写进来。
+- 两笔都不动依赖、不动磁盘格式、不动包名;全程没 `pnpm add`(避免换掉 `packages/{web,ui-gallery}/node_modules/@adelie/ui`
+ 那个指回 `../../ui` 的符号链接)、没切分支、没碰 `legacy/main`、没推上游。
+
+### 改了什么
+
+- **第三笔(模型库,`core` + `docs`)**:TokenDance 分组补四条(`deepseek-v4.1-flash-1017`、
+ `deepseek-v4-pro`、`kimi-k3.1-pro`、`glm-5.3-flashx`),并把整组 18 条的价格、窗口与促销按卖家当下的
+ 目录重核(`kimi-k3` 的 6 折与两条 DeepSeek 的 9 折都已停止,`seed-evolving` 窗口 25.6 万 → 100 万)。
+ 数据来源换成匿名可取的 `GET https://tokendance.space/portal/api/models/all`(含实收价、牌价与峰谷两档)。
+ `deepseek-v4-flash-0731` 与 `deepseek-v4-pro-0813` 的谷时只能近似(一条只放得下一个费率),已写明在代码
+ 与文档里。详见这一笔自己的 changelog。
+- **第四笔(异常表过滤,`server` + `web` + `ui-gallery` + `docs`)**:成本中心**异常**面板表格右上方加一个
+ 类型筛选(全部 / 未预期 / 预期内)。面板自己的 `kindFilter` 与页面的日期 / Agent 筛选合成
+ `activeFilters`,取数、行数、翻页、清空全部走它;选了类型后连第 0 页也改为向服务端读(仪表盘快照把两类
+ 折在一起)。`DELETE /usage/errors` 新增 `kind`,与读接口共用一个闭集校验与一处 WHERE。汇总数字仍按两类
+ 合计,它是整段范围的摘要。
+- 两笔各自的 changelog 一对(`changelog/unreleased/2026-10-27-tokendance-catalog-refresh.*`、
+ `2026-10-27-errors-panel-category-filter.*`)。
+
+### 验证(都不是推测)
+
+- **第三笔**:`core/test/model-catalog.test.ts` **65 passed**(TokenDance 那组的三处钉子跟到新事实,并新增
+ 一条「既无促销也无时段的条目实收就是公布价」的断言);`core` 全量 **1425 passed / 6 skipped**。
+ `pnpm --filter @adelie/core build` 后 `pnpm -r test` **退出码 0**。
+- **第四笔**:`web` 全量 **270 文件 / 3303 通过 / 2 跳过**;`server/test/errors.test.ts` **66 passed**(含新增
+ 「a category-narrowed clear leaves the other category alone」);`ui-gallery` **20 文件 / 140 通过**。
+- **门禁**:`pnpm format:check`(先对 `packages/ui-gallery/src/app/mock/routes.ts` 跑了一次 `prettier --write`)
+ **全部干净**;`pnpm lint` **0 警告 0 错误**(2305 文件);`pnpm typecheck` 六包 **`Done`**,
+ `gen:ifaces` 报 **`src/ifaces.json unchanged`**(195 接口 / 590 类型 —— 两笔都没动服务契约的形状)。
+- **真浏览器(第四笔的主证据)**:`pnpm dev:gallery` 起在 **7372**,Playwright 打开
+ `app.html?route=/usage&theme=github`:
+ - 中英文各一张全页截图,控件三标签(全部 / 未预期 / 预期内)都在统计行下方、表格上方右侧;
+ - 中文页:**全部 = 3 行 → 未预期 = 1 行**;
+ - 收窄后点**清空**,确认框原文 = 「将删除本项目 近 7 天内的 1 条「未预期」错误记录,另一类与其余时间段
+ 的记录保留。」,确认后 toast **「已删除 1 条错误记录」**、统计从 **总数 6 → 5** —— 另一类确实留着。
+ - 页面无 pageerror、无 console error;截图在 scratchpad 的 `shots/` 下。
+- 端口:本轮只用了 **7372**(跑完已停),3003 / 3004 / 4000 / 7364 / 7369 一个没碰。
+
+### 没做 / 还差什么
+
+- **模型库是源码**:新条目与更正后的价格要等下一版发出去才在现网可见;已存在的 Project 还要点一次
+ **同步预置**(自己改过价的条目保持用户自己的价)。
+- **卖家目录里有、本轮有意没收的候选**:`minimax-m3.1-flash`、`step-3.7-flash`、`ling-3.1-flash`、
+ `longcat-2.0`、`glm-5.2`、`qwen3.8-max-0902`(`qwen3.8-max` 的定版快照,主 id 已收录);TokenDance 组也没给
+ 任何一行加 `supportsVideo`(该组一向不写这个字段,尽管目录里几行支持视频)。等用户定要不要补。
+- **错误中心的「复制按钮」**(用户 2026-10-26 当场点的单,说下一轮做)本轮仍未做,记在记忆
+ `pending-error-center-copy-button` 里。
+- 发布树 `/tmp/rel-0.5.8` 与 `/tmp/adelie-release-0.5.8/` 仍在(本轮没用上),下一轮开工可清。
+
+### 版本:未到阈值
+
+- 上次发版 **`v0.5.8`**(2026-10-26 23:07 CST)。自那以后 `main` 上功能性的是 5.50 / 5.51 / 5.52 / 5.53 与本轮
+ 两笔,远不到 10。
+- 不动版本号、不发 npm、不发安装包。
+
+### 提交
+
+- 两笔:模型库一笔、异常表过滤 + 本台账一笔(提交号见下一轮开工自检)。跑完那两笔的 CI 收工。
diff --git a/packages/docs/content/usage.en.md b/packages/docs/content/usage.en.md
index 90f3999c..c81aff08 100644
--- a/packages/docs/content/usage.en.md
+++ b/packages/docs/content/usage.en.md
@@ -61,6 +61,7 @@ The **Errors** panel at the bottom of the page shows the errors the server recor
- Summary figures: **Total**, **Unexpected**, **Expected** and the **Most common** error code.
- A table of errors with their time, **Source · code**, **Type** and **Message**. Click a message to expand its full text. The table shows 10 rows a page and pages with **Newer** and **Older** instead of scrolling.
+- A **Type** filter above the table on the right: **All**, **Unexpected**, **Expected**. It narrows only the table below, its paging and **Clear**; the summary figures always count both categories.
- The same error recorded more than once on one day shares a row. The time is the latest one, hover it for the first, and ×N after the message counts the records. The summary figures count every record.
The model filter does not apply to this panel.
@@ -71,9 +72,9 @@ When unexpected errors were recorded in the last 7 days, a dot marks **Cost Cent
**Before you begin:** only a Project owner can clear errors.
-1. Set the date range and the agent filter to the rows you want to delete.
+1. Use the date range, the agent filter and the panel's own **Type** filter to make the panel list the rows you want to delete.
2. In the **Errors** panel, select **Clear**. It appears only when the panel lists errors and, for a custom range, both dates are set.
-3. Check the confirmation. It names a preset range the way the picker does, such as "in the last 7 days", and a custom range by its dates.
+3. Check the confirmation. It names a preset range the way the picker does, such as "in the last 7 days", a custom range by its dates, and the category when one is chosen — the other one is kept.
4. Confirm. The deletion cannot be undone.
When an admin clears errors, the deletion also removes the unattributed error rows that only admins can see.
diff --git a/packages/docs/content/usage.zh.md b/packages/docs/content/usage.zh.md
index df9a5fa8..1b32774f 100644
--- a/packages/docs/content/usage.zh.md
+++ b/packages/docs/content/usage.zh.md
@@ -61,6 +61,7 @@ description: 按 Agent、模型和时间范围查看 Token 用量、成本与服
- 汇总数字:**总数**、**未预期**、**预期内**和**最常见**的错误码。
- 异常明细表:时间、**来源 · 错误码**、**类型**和**消息**。点击消息可展开全文。每页 10 行,用**较新**和**更早**翻页,不滚动。
+- 表格右上方的**类型**筛选:**全部**、**未预期**、**预期内**。它只收窄下面的表格、翻页和**清空**,上面的汇总数字始终按两类合计。
- 同一天里多次记录的同一个异常合为一行:时间显示最近一次,悬停可看到首次;消息后的 ×N 是记录的条数。汇总数字按每条记录计。
模型筛选对这个面板不起作用。
@@ -71,9 +72,9 @@ description: 按 Agent、模型和时间范围查看 Token 用量、成本与服
**开始之前**:只有 Project owner 可以清空异常。
-1. 设置日期范围和 Agent 筛选,让面板列出要删除的记录。
+1. 用日期范围、Agent 筛选和面板自己的**类型**筛选,让面板列出要删除的记录。
2. 在**异常**面板中选择**清空**。只有面板列出了异常时才有这个按钮;自定义范围还要填好起止两个日期。
-3. 核对确认框。预设范围按选择器里的叫法写出,例如「近 7 天内」;自定义范围写出起止日期。
+3. 核对确认框。预设范围按选择器里的叫法写出,例如「近 7 天内」;自定义范围写出起止日期;选了类型时还会写出是哪一类,另一类保留。
4. 确认删除。此操作不可恢复。
管理员清空时,还会一并删除只有管理员能看到的未归属异常记录。
diff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.ts
index 035c97ce..4538d719 100644
--- a/packages/server/src/http/routes/usage.ts
+++ b/packages/server/src/http/routes/usage.ts
@@ -9,7 +9,7 @@
* of the error detail table, for paging back past the first page the dashboard already
* returns (both reads also take `utcOffsetMinutes`, the viewer's offset from UTC, whose
* calendar day the table folds a day's repeats by);
- * DELETE /api/projects/:p/usage/errors?from&to&fromTs&toTs&until&agentId — empties that table
+ * DELETE /api/projects/:p/usage/errors?from&to&fromTs&toTs&until&agentId&kind — 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; `until`
* stops at the newest record the confirmation counted);
@@ -184,12 +184,12 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {
);
});
- // 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.
+ // Empties the error table for the filter the panel is showing. Takes the same date, window,
+ // agent and category 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
+ // accepted because the panel now has that control: its table and its button read the same
+ // filter, so a reader narrowed to one category keeps the other one.
app.delete("/errors", (c) => {
const projectId = requireValidId(c, "projectId");
// Owner only, the rule Agent deletion applies to error rows already (it cascade-deletes
@@ -214,6 +214,17 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {
// boundary would remove rows the sentence said were kept.
const until = optionalTsParam(c.req.query("until"), "until");
const agentId = c.req.query("agentId");
+ const kindRaw = c.req.query("kind");
+ // Validated against the same closed set the read uses: an unrecognized category would
+ // otherwise match no rows, and a clear that silently matches nothing reads as "already
+ // empty" while the rows are still there.
+ if (
+ kindRaw !== undefined &&
+ kindRaw !== "" &&
+ !(ERROR_KINDS as readonly string[]).includes(kindRaw)
+ ) {
+ throw badRequest(`kind must be one of ${ERROR_KINDS.join(" / ")}.`);
+ }
// 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
@@ -225,6 +236,7 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {
...window,
...(until !== undefined ? { until } : {}),
...(agentId !== undefined && agentId !== "" ? { agentId } : {}),
+ ...(kindRaw !== undefined && kindRaw !== "" ? { kind: kindRaw } : {}),
});
return c.json({ deleted } satisfies UsageErrorsClearResponse);
});
diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.ts
index 0fd70087..ac318ab0 100644
--- a/packages/server/src/services/usage-service.ts
+++ b/packages/server/src/services/usage-service.ts
@@ -125,9 +125,10 @@ export interface UsageErrorsQuery {
/**
* 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.
+ * and the trailing window when one is on — Agent, and the category the panel is narrowed to,
+ * read with the same admin visibility the panel has. `kind` is here because the panel has the
+ * control: a reader looking at one category must not lose the other to a button that said
+ * "clear", so what the row offers and what this removes stay the same set.
*
* `until` is the boundary the confirmation counted: the newest record the dialog's own read
* could see. The delete stops there, so the sentence's number is the number that goes even
@@ -140,6 +141,8 @@ export interface UsageErrorsClearQuery {
toTs?: string;
until?: string;
agentId?: string;
+ /** Narrow to one category, the value the caller's reads carry; absent counts both. */
+ kind?: 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;
}
@@ -396,12 +399,12 @@ export class UsageService implements UsageQueries {
/**
* Empties the error table for the filter the panel is showing, and answers how many rows went.
*
- * 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).
+ * The filter is the same range (dates, and the trailing window when one is on), Agent and
+ * category 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, one week or one category does not lose the rest 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, {
@@ -411,6 +414,7 @@ export class UsageService implements UsageQueries {
...(q.fromTs !== undefined ? { fromTs: q.fromTs } : {}),
...(q.toTs !== undefined ? { toTs: q.toTs } : {}),
...(q.until !== undefined ? { until: q.until } : {}),
+ ...(q.kind !== undefined ? { kind: q.kind } : {}),
...(q.includeGlobalErrors === true ? { includeGlobal: true } : {}),
});
}
diff --git a/packages/server/test/errors.test.ts b/packages/server/test/errors.test.ts
index 5c1fc734..9aa71281 100644
--- a/packages/server/test/errors.test.ts
+++ b/packages/server/test/errors.test.ts
@@ -1398,6 +1398,40 @@ describe("HTTP onError persistence (integration)", () => {
).toEqual(["before_range", "after_range"]);
});
+ it("a category-narrowed clear leaves the other category alone", async () => {
+ const day = "2026-07-06";
+ seedRow({ date: day, code: "boom", kind: "unexpected" });
+ seedRow({ date: day, code: "missing", kind: "expected" });
+ const kept = () =>
+ errorRows()
+ .map((r) => r.code)
+ .filter((code) => code !== "bad_request");
+
+ // What the panel's narrowed table reads — the same `kind` its clear carries, which is the
+ // point: the button empties the table on screen, never the category filtered out of it.
+ const narrowed = (await (
+ await api.get(
+ `/api/projects/${projectId}/usage/errors?offset=0&limit=20&from=${day}&to=${day}&kind=unexpected`,
+ )
+ ).json()) as UsageErrorsPage;
+ expect(narrowed.items.map((e) => e.code)).toEqual(["boom"]);
+ expect(narrowed.total).toBe(1);
+
+ const cleared = await api.delete(
+ `/api/projects/${projectId}/usage/errors?from=${day}&to=${day}&kind=unexpected`,
+ );
+ expect(await cleared.json()).toEqual({ deleted: 1 });
+ expect(kept()).toEqual(["missing"]);
+
+ // A category outside the closed set is refused rather than matched against nothing: a clear
+ // that silently deleted none of them reads as "already empty" while they are all still there.
+ const refused = await api.delete(
+ `/api/projects/${projectId}/usage/errors?from=${day}&to=${day}&kind=oops`,
+ );
+ expect(refused.status).toBe(400);
+ expect(kept()).toEqual(["missing"]);
+ });
+
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` });
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index 9f9e1eb1..fb4a48a2 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -1847,10 +1847,13 @@ router
rows: items.length,
};
})
- .delete("/api/projects/:projectId/usage/errors", ({ store }): UsageErrorsClearResponse => {
- const deleted = store.f.usageErrors.length;
- store.f.usageErrors = [];
- return { deleted };
+ .delete("/api/projects/:projectId/usage/errors", ({ store, query }): UsageErrorsClearResponse => {
+ // Same narrowing as the read above: the panel's clear sends the category its table is
+ // showing, so the demo behaves the way the route does.
+ const kind = query.get("kind");
+ const going = kind ? store.f.usageErrors.filter((e) => e.kind === kind) : store.f.usageErrors;
+ store.f.usageErrors = kind ? store.f.usageErrors.filter((e) => e.kind !== kind) : [];
+ return { deleted: going.length };
})
.get("/api/projects/:projectId/usage/model-totals", ({ store }): UsageModelTotals => {
const totals = new Map<string, UsageModelTotals["totals"][number]>();
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 0f145d34..0b5f3a91 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -1493,9 +1493,9 @@ export const getUsageErrors = (
/**
* 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.
+ * trailing window, Agent and category 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.
*
* `until` is the newest record the confirmation's own read could see: the delete stops there,
* so the number the dialog named is the number that goes even when a record lands in between.
@@ -1509,6 +1509,8 @@ export const clearUsageErrors = (
toTs?: string;
until?: string;
agentId?: string;
+ /** Narrow to one category; the panel sends whatever its table is showing. */
+ kind?: UsageErrorKind;
},
) =>
apiFetch<UsageErrorsClearResponse>(
@@ -1522,6 +1524,7 @@ export const clearUsageErrors = (
toTs: params.toTs,
until: params.until,
agentId: params.agentId,
+ kind: params.kind,
},
},
);
diff --git a/packages/web/src/features/usage/errors-panel.tsx b/packages/web/src/features/usage/errors-panel.tsx
index 27c2a06a..c3a1fbc5 100644
--- a/packages/web/src/features/usage/errors-panel.tsx
+++ b/packages/web/src/features/usage/errors-panel.tsx
@@ -13,9 +13,9 @@
* exceptions) is a prominent rose; expected (HttpError, business 4xx) recedes into gray.
* The outer frame is provided by the caller's ChartCard (full width, below the four business charts).
*/
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import type { UsageErrorItem, UsageErrors } from "@adelie/server/api";
-import { Badge, ConfirmModal, Pager, toastError, toastSuccess } from "@adelie/ui";
+import { Badge, ConfirmModal, Pager, Segmented, toastError, toastSuccess } from "@adelie/ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
@@ -26,6 +26,9 @@ import { toneInk } from "../../lib/tone";
/** The two error categories. */
type ErrorKindKey = "unexpected" | "expected";
+/** The table's own category control: one of the two, or both. */
+type ErrorKindFilter = ErrorKindKey | "all";
+
/** The date/agent filter the panel reads through, and that a clear deletes through. */
export interface ErrorsFilters {
from?: string;
@@ -34,6 +37,13 @@ export interface ErrorsFilters {
fromTs?: string;
toTs?: string;
agentId?: string;
+ /**
+ * The table's category filter, when one is chosen. The panel owns this control rather than
+ * the page's filter bar, so it is merged in here — and read by the clear as well, because a
+ * button that emptied the category the reader had filtered OUT would be taking rows off a
+ * table they never saw.
+ */
+ kind?: ErrorKindKey;
}
/** The quick range presets the clear confirmation names by name; a custom range is named by its dates. */
@@ -47,8 +57,11 @@ export type ErrorsRangePreset = "1h" | "1d" | "7d" | "30d" | "90d";
* — 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.
+ * as its dates. The table's own category filter is part of that set too, so it is named here
+ * as well: the button empties what the table shows, and a sentence that left the category out
+ * would promise the reader keeps rows the delete is about to take. 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,
@@ -59,9 +72,15 @@ export function errorsClearScopeText(
preset !== undefined
? S.usage.errorsClearRangePreset(preset)
: S.usage.errorsClearRangeCustom(filters.from ?? "", filters.to ?? "");
- return filters.agentId !== undefined && filters.agentId !== ""
- ? S.usage.errorsClearScopeAgent(count, range, filters.agentId)
- : S.usage.errorsClearScope(count, range);
+ const kind = filters.kind !== undefined ? kindLabel(filters.kind) : undefined;
+ const agent =
+ filters.agentId !== undefined && filters.agentId !== "" ? filters.agentId : undefined;
+ if (kind !== undefined && agent !== undefined) {
+ return S.usage.errorsClearScopeKindAgent(count, range, kind, agent);
+ }
+ if (kind !== undefined) return S.usage.errorsClearScopeKind(count, range, kind);
+ if (agent !== undefined) return S.usage.errorsClearScopeAgent(count, range, agent);
+ return S.usage.errorsClearScope(count, range);
}
/**
@@ -140,6 +159,12 @@ function Th({ children, className = "" }: { children: React.ReactNode; className
* a floor to stay legible, so on a viewport narrower than that floor the table scrolls
* sideways inside its own box rather than dragging the page along with it.
*
+ * The panel brings one filter of its own: a category control (both / unexpected / expected)
+ * right above the table. The stats keep counting both categories — they are the range's summary,
+ * and the control says which slice of it the table below is showing — but the table, its pager,
+ * its row count and the clear all follow it, and page 0 of a narrowed table is read rather than
+ * taken from the dashboard snapshot, which folds both categories.
+ *
* The footer under the table carries the pager and, for a Project owner, the clear action.
* Clearing deletes the records the current filter selects — the set the reader is looking at,
* not the Project's whole history — and the confirmation says which set that is and how many
@@ -194,19 +219,32 @@ export function ErrorsPanel({
const [pagedRows, setPagedRows] = useState(rows);
const [pageError, setPageError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
+ // The table's own category filter. The stats above keep counting both categories — they are
+ // the range's summary, and the box that narrows the table is where it says so — so this state
+ // lives here rather than in the page's filter bar.
+ const [kindFilter, setKindFilter] = useState<ErrorKindFilter>("all");
+ // What the reads, the count and the clear all go by: the page's filter, plus this table's own
+ // category when one is chosen (see ErrorsFilters.kind).
+ const activeFilters = useMemo<ErrorsFilters>(
+ () => (kindFilter === "all" ? filters : { ...filters, kind: kindFilter }),
+ [filters, kindFilter],
+ );
// A new dashboard response invalidates the offsets being paged through, so paging goes back to
// page 0 — whose rows the effect below restores from that same response. Today the panel is
// remounted on every filter change, which resets this anyway; the reset does not rely on that.
- useEffect(() => setPage(0), [recent]);
+ // The category goes back with it: the offsets on page 2 count the previous category's rows.
+ useEffect(() => setPage(0), [recent, kindFilter]);
// Every value this effect reads is a dep, the page-0 branch's included: one left out would be
// served from a stale closure, and the repo has no lint rule that would catch it.
useEffect(() => {
- // Page 0 is restored, never fetched — the dashboard response already carries it. Restoring
- // is the whole point of the early return: leaving `items` untouched would keep the previous
- // page's rows and its error on screen under a "page 1" label, with no way out short of
- // changing a filter.
- if (page === 0) {
+ // Page 0 is restored, never fetched — the dashboard response already carries it, and it is
+ // the first page of exactly this filter. Restoring is the whole point of the early return:
+ // leaving `items` untouched would keep the previous page's rows and its error on screen
+ // under a "page 1" label, with no way out short of changing a filter. With a category chosen
+ // it cannot be, though: the dashboard folds both categories into that snapshot, so page 0 of
+ // a narrowed table has to be read like any other page.
+ if (page === 0 && kindFilter === "all") {
setItems(recent);
setPagedRows(rows);
setPageError(null);
@@ -216,7 +254,7 @@ export function ErrorsPanel({
setLoading(true);
setPageError(null);
api
- .getUsageErrors(projectId, { offset: page * pageSize, limit: pageSize, ...filters })
+ .getUsageErrors(projectId, { offset: page * pageSize, limit: pageSize, ...activeFilters })
.then((res) => {
if (cancelled) return;
setItems(res.items);
@@ -232,7 +270,7 @@ export function ErrorsPanel({
return () => {
cancelled = true;
};
- }, [page, pageSize, projectId, filters, recent, rows]);
+ }, [page, pageSize, projectId, activeFilters, recent, rows, kindFilter]);
const pageCount = Math.max(1, Math.ceil(pagedRows / pageSize));
const [confirmingClear, setConfirmingClear] = useState(false);
@@ -257,7 +295,7 @@ export function ErrorsPanel({
const openClear = async () => {
setCounting(true);
try {
- const res = await api.getUsageErrors(projectId, { offset: 0, limit: 1, ...filters });
+ const res = await api.getUsageErrors(projectId, { offset: 0, limit: 1, ...activeFilters });
const newest = res.items[0]?.ts;
if (res.total === 0 || newest === undefined) {
// Emptied between the dashboard's read and this click: nothing to confirm, so the
@@ -285,7 +323,7 @@ export function ErrorsPanel({
setClearing(true);
try {
const res = await api.clearUsageErrors(projectId, {
- ...filters,
+ ...activeFilters,
until: confirmTarget.until,
});
setConfirmingClear(false);
@@ -330,9 +368,27 @@ export function ErrorsPanel({
)}
</div>
+ {/* The table's own filter: one category or both. Right-aligned directly above the table it
+ narrows, so it reads as that table's control rather than as part of the stats row. It is
+ drawn whenever the panel has a table to narrow — an empty page keeps it, since it is the
+ only way back to the category the reader came from. */}
+ <div className="mt-3 flex justify-end">
+ <div className="w-56">
+ <Segmented
+ options={[
+ { value: "all", label: S.usage.errorsFilterAll },
+ { value: "unexpected", label: S.usage.errorsUnexpected },
+ { value: "expected", label: S.usage.errorsExpected },
+ ]}
+ value={kindFilter}
+ onChange={setKindFilter}
+ />
+ </div>
+ </div>
+
{/* Recent-errors table */}
{items.length === 0 ? (
- <Empty text={S.usage.errorsEmpty} />
+ <Empty text={kindFilter === "all" ? S.usage.errorsEmpty : S.usage.errorsEmptyKind} />
) : (
<div className="mt-2.5 overflow-x-auto overflow-y-clip border-t border-gray-200 dark:border-gray-800">
{/* The three leading columns are fixed-width and the message column takes the rest, so
@@ -423,7 +479,7 @@ export function ErrorsPanel({
<div className="mt-2 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
{/* 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) && (
+ {canClear && total > 0 && clearableFilter(activeFilters) && (
<button
type="button"
disabled={clearing || counting}
@@ -469,7 +525,7 @@ export function ErrorsPanel({
<div className="space-y-1.5 text-sm text-gray-700 dark:text-gray-300">
{confirmTarget !== null && (
<p className="break-words">
- {errorsClearScopeText(filters, preset, confirmTarget.total)}
+ {errorsClearScopeText(activeFilters, preset, confirmTarget.total)}
</p>
)}
<p className="text-xs text-gray-500 dark:text-gray-400">
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 4643c281..955dd170 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -4266,6 +4266,9 @@ export const en: Strings = {
errorsColKind: "Type",
errorsColMessage: "Message",
errorsEmpty: "No errors",
+ /** The table's category control: both categories, and the empty state once one is chosen. */
+ errorsFilterAll: "All",
+ errorsEmptyKind: "No errors of this type",
/** Time cell tooltip on a row that folds several of a day's records: when the first one was. */
errorsFirstAt: (time: string): string => `First at ${time}`,
/** Detail-table pager: newer/older step back through pages of the same filtered set; it counts rows, not records. */
@@ -4289,6 +4292,16 @@ export const en: Strings = {
`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.`,
+ /** The same sentence with the table's own category filter on: the other category is kept too. */
+ errorsClearScopeKind: (count: number, range: string, kind: string): string =>
+ `Deletes this Project's ${count} ${kind.toLowerCase()} error record${count === 1 ? "" : "s"} ${range}. The other category and records outside that range are kept.`,
+ errorsClearScopeKindAgent: (
+ count: number,
+ range: string,
+ kind: string,
+ agentId: string,
+ ): string =>
+ `Deletes this Project's ${count} ${kind.toLowerCase()} error record${count === 1 ? "" : "s"} for agent ${agentId} ${range}. The other category, 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.ts
index 0a9c47b8..e463b35f 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -4299,6 +4299,9 @@ export const zh = {
errorsColKind: "类型",
errorsColMessage: "消息",
errorsEmpty: "暂无异常",
+ /** The table's category control: both categories, and the empty state once one is chosen. */
+ errorsFilterAll: "全部",
+ errorsEmptyKind: "该类型下暂无异常",
/** Time cell tooltip on a row that folds several of a day's records: when the first one was. */
errorsFirstAt: (time: string): string => `首次出现于 ${time}`,
/** Detail-table pager: newer/older step back through pages of the same filtered set; it counts rows, not records. */
@@ -4323,6 +4326,16 @@ export const zh = {
`将删除本项目 ${range}的 ${count} 条错误记录,其余时间段的记录保留。`,
errorsClearScopeAgent: (count: number, range: string, agentId: string): string =>
`将删除本项目中 Agent「${agentId}」${range}的 ${count} 条错误记录,其他 Agent 与其余时间段的记录保留。`,
+ /** The same sentence with the table's own category filter on: the other category is kept too. */
+ errorsClearScopeKind: (count: number, range: string, kind: string): string =>
+ `将删除本项目 ${range}的 ${count} 条「${kind}」错误记录,另一类与其余时间段的记录保留。`,
+ errorsClearScopeKindAgent: (
+ count: number,
+ range: string,
+ kind: string,
+ agentId: string,
+ ): string =>
+ `将删除本项目中 Agent「${agentId}」${range}的 ${count} 条「${kind}」错误记录,另一类、其他 Agent 与其余时间段的记录保留。`,
errorsClearIrreversible: "此操作不可恢复。",
errorsClearDone: (count: number): string => `已删除 ${count} 条错误记录`,
},
diff --git a/packages/web/test/errors-panel.test.ts b/packages/web/test/errors-panel.test.ts
index 3664714a..0026ea52 100644
--- a/packages/web/test/errors-panel.test.ts
+++ b/packages/web/test/errors-panel.test.ts
@@ -170,4 +170,47 @@ describe("errorsClearScopeText", () => {
errorsClearScopeText(FILTERS, "7d", 4),
);
});
+
+ for (const [locale, dict] of Object.entries({ zh, en })) {
+ it(`${locale}: the table's category filter is named too, and the other category kept`, () => {
+ setActiveStrings(dict);
+ // The delete is scoped to what the table shows, so a sentence that left the category out
+ // would tell the reader they keep rows it is about to take. The sentence names the category
+ // as the control does; English drops the capital because it reads the word mid-sentence.
+ const name = (label: string) => label.toLowerCase();
+ const perKind = errorsClearScopeText({ ...FILTERS, kind: "unexpected" }, "7d", 5);
+ expect(name(perKind)).toContain(name(dict.usage.errorsUnexpected));
+ expect(perKind).toContain("5");
+
+ const both = errorsClearScopeText(
+ { ...FILTERS, kind: "expected", agentId: "agent-7" },
+ "7d",
+ 2,
+ );
+ expect(name(both)).toContain(name(dict.usage.errorsExpected));
+ expect(both).toContain("agent-7");
+ expect(both).toContain(dict.usage.errorsClearRangePreset("7d"));
+ });
+ }
+});
+
+describe("ErrorsPanel category control", () => {
+ it("is drawn with both categories and 'all', and narrows nothing until one is chosen", () => {
+ const html = render({ items: [item("internal")] });
+ for (const label of [
+ S.usage.errorsFilterAll,
+ S.usage.errorsUnexpected,
+ S.usage.errorsExpected,
+ ]) {
+ expect(html).toContain(label);
+ }
+ // Nothing chosen: the table is the unfiltered first page and says so.
+ expect(html).not.toContain(S.usage.errorsEmptyKind);
+ });
+
+ it("stays on screen while the table is empty, so its own choice can be undone", () => {
+ const html = render({ items: [] });
+ expect(html).toContain(S.usage.errorsFilterAll);
+ expect(html).toContain(S.usage.errorsUnexpected);
+ });
});