Skip to content

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

feat(web,server): 错误中心能忽略某一类报错,不再只能清空

lmliheng674ef7459842
diff --git a/changelog/unreleased/2026-11-08-errors-ignore-rules.md b/changelog/unreleased/2026-11-08-errors-ignore-rules.md
new file mode 100644
index 00000000..d9dce0fb
--- /dev/null
+++ b/changelog/unreleased/2026-11-08-errors-ignore-rules.md
@@ -0,0 +1,74 @@
+# The cost center can ignore a class of errors, and deletes nothing
+
+- **Date:** 2026-11-08
+- **Type:** feature
+- **Scope:** `server`, `web`
+- **Breaking:** no
+
+[中文](2026-11-08-errors-ignore-rules.zh.md)
+
+The error table has always been "watch it, or clear it". Clearing is a real delete: the rows the
+filter is showing leave the store for everyone, and nobody in the Project can look them up
+afterwards. For a class that retries hundreds of times an afternoon under one name
+(`[llm] llm_fatal`), that price is too high, so it stayed on the first page and pushed the three
+rows worth reading further down.
+
+A class can now be ignored on its own: every row grows an eye icon, and pressing it writes one rule
+for that row's **source + code**, which takes those records off this table — without deleting a
+single one. A rule can also be narrowed to "the message contains this text", so within one source
+and code only the records carrying that fragment are held back (the one 500 a class ever returned
+can stay while the afternoon of dropped sockets does not).
+
+Ignoring and un-ignoring are the Project owner's, the same line clearing draws: a rule changes the
+table everyone reads. Members still see the "已忽略 N" count in the stats and can still open the
+Ignored view and read those records — what a rule hides is never hidden from them.
+
+## Details
+
+- Server: a new table `error_ignore_rules` (per Project, `source` + `code` + an optional
+ `message_like`). Records are still written to `error_records` exactly as before; **the filtering
+ happens only on the read path** (one more condition in `ErrorsRepo.conds` — "no rule covers this
+ row", inverted under `ignored=1`), and deleting records still has exactly one road, the clear.
+ Three routes, all behind `requireProjectOwner`: `GET /api/projects/:p/usage/errors/ignores` (the
+ rules, each with how many records it covers and when the newest was),
+ `POST …/ignores?from&to&fromTs&toTs&agentId` (adds one and answers how many it hides in that range;
+ the same class twice is `409 ignore_rule_exists`), and `DELETE …/ignores/:id` (removing the rule is
+ the whole of the undo; `404 ignore_rule_not_found`). `GET/DELETE /usage/errors` take a new `ignored`
+ parameter (`1`/`0`, anything else a 400), and the dashboard carries a new `errors.ignored`. Rules
+ deliberately carry **no expiry**: they last until somebody removes them, and nothing anywhere reads
+ a "when does this lapse" field.
+- Web: the table's segmented control goes from three to four (all / unexpected / expected / ignored,
+ four chips on one row) and the stats row gains "已忽略 N". The row action is an eye icon named
+ 忽略这类异常; it opens a card that names the row's source and code and offers an optional "only
+ ignore records whose message contains…". After ignoring, a **reversible** strip stays above the
+ table ("已忽略 … · 本次隐藏 N 条记录" with 撤销) — it stands where the table is, because the row the
+ button lived on is gone; the notification region carries the same sentence and dismisses itself
+ after six seconds, the strip does not. The Ignored view draws the rules above its table: each rule
+ says what it covers, how many records it holds back, when the newest was, and offers 取消忽略.
+- Clearing still takes exactly the rows on screen, but its confirmation now says the ignored ones are
+ not among them ("另有 N 条已忽略的记录不在此列。"); standing on the Ignored view, the sentence names
+ that view's own rows, because those are what its table shows.
+
+## Tests
+
+- `packages/server/test/errors.test.ts` (+391 lines): the covered count within the range, `message_like`
+ matching, the 409 on a duplicate rule, the 404 with no such rule, the 400 on a malformed id, the
+ `ignored` parameter's validation, filtering staying on the read path (not one record fewer, and all
+ of them back after the rule goes), and the three routes answering the owner only (a member reads
+ `errors.ignored` but neither reads nor writes rules).
+- `packages/web/test/errors-panel.test.ts` (+151 lines): `errorsClearScopeText` on the Ignored view,
+ `errorsClearKeepsIgnoredText` (present where the ignored records must be called out, absent on their
+ own view), `IgnoreRulesBox`'s three states, and how `ignoreRuleText` words a narrowed rule.
+- `packages/web/e2e/errors-ignore.spec.mjs` (new, 2 cases, real server + real browser): one drives the
+ row action — the table loses the class, the notification and the strip both say how many rows went,
+ and the API still hands the record back (same id), gone from the default read and present under
+ `ignored=1`; the rules list holds exactly that class; 撤销 leaves no rule and puts the record back on
+ the default view. The other drives the Ignored view — the clear confirmation's extra sentence, the
+ rules list naming the class and its hidden count, that view's table holding those records, and
+ 取消忽略 clearing the rules and returning the records to the All view.
+
+## Compatibility
+
+A new table and new routes; no existing interface changes shape (the error reads gain one optional
+parameter, the dashboard one field). Existing data is untouched, and a Project with no rules reads a
+table identical to before, row for row. No new dependency, no Project config change.
diff --git a/changelog/unreleased/2026-11-08-errors-ignore-rules.zh.md b/changelog/unreleased/2026-11-08-errors-ignore-rules.zh.md
new file mode 100644
index 00000000..1e0a1216
--- /dev/null
+++ b/changelog/unreleased/2026-11-08-errors-ignore-rules.zh.md
@@ -0,0 +1,59 @@
+# 错误中心能忽略某一类报错,记录一条都不删
+
+- **日期:** 2026-11-08
+- **类型:** 新功能
+- **范围:** `server`, `web`
+- **破坏性变更:** 无
+
+[English](2026-11-08-errors-ignore-rules.md)
+
+成本中心的错误表一直是「要么看着,要么清空」。而清空是真删:按当前筛选把整批记录从库里抹掉,全项目的人
+此后都查不到 —— 对一个下午重试几百次、每次都叫 `[llm] llm_fatal` 的那类噪音来说,代价太大,于是它就一直
+躺在表的第一页,把真正要看的那三条挤到后面。
+
+现在可以只忽略某一类:每一行多一颗眼睛图标,按下后按它那一行的**来源 + 错误码**立一条规则,这类记录就从
+这张表里消失 —— 一条都没删。想连「同一类里的另一种声音」一起留下也行:规则可以再窄到「消息包含某段文字」,
+于是同一来源与错误码里只有带那段的记录被隐藏(`llm_fatal` 一次 500 的报错可以留着,整下午的套接字断流不用看)。
+
+忽略与取消是项目主人(owner)的事,和清空同一条线:规则改的是所有人看到的表。成员照样看得到统计行里那个
+「已忽略 N」,也照样能切到「已忽略」视图读那批记录 —— 被规则挡住的东西,从不对他们隐身。
+
+## 细节
+
+- 服务端:新表 `error_ignore_rules`(按项目存,`source` + `code` + 可选的 `message_like`),记录照旧照常写进
+ `error_records`;**过滤只发生在读路径上**(`ErrorsRepo.conds` 里多一个「不被任何规则覆盖」的条件,`ignored=1`
+ 时反过来只取被覆盖的),删除记录仍然只有清空一条路。三条路由,都走 `requireProjectOwner`:
+ `GET /api/projects/:p/usage/errors/ignores`(规则+各自覆盖多少条、最近一条何时)、
+ `POST …/ignores?from&to&fromTs&toTs&agentId`(新增,回一句「在这个范围内隐藏了几条」;同一类已有规则即
+ 409 `ignore_rule_exists`)、`DELETE …/ignores/:id`(删规则本身就是撤销,404 `ignore_rule_not_found`)。
+ `GET/DELETE /usage/errors` 新增 `ignored` 参数(`1`/`0`,其余取值 400),仪表盘多一个 `errors.ignored`。
+ 规则有意**不设过期时间**:永久,直到有人取消 —— 现在没有任何地方读「什么时候失效」(见 changelog 的
+ 「没做」一节)。
+- Web:错误表的分段控件从三个变成四个(全部 / 未预期 / 预期内 / 已忽略,四颗排一行),统计行多一格
+ 「已忽略 N」。行里那颗眼睛按钮叫「忽略这类异常」,按下弹一张卡:写着这一行的来源与错误码,给一个可留空的
+ 「只忽略消息包含以下内容的记录」。忽略之后,表上方留一条**可撤销**的横条(「已忽略 … · 本次隐藏 N 条记录」
+ + 「撤销」)——它落在表的位置上,因为那颗按钮原来所在的行已经消失了;通知区那条同样的句子会自己在六秒后
+ 走掉,撤销不会。规则列表画在「已忽略」视图的表上方:每条规则念自己覆盖什么、已隐藏多少条、最近一条何时,
+ 带「取消忽略」。
+- 清空照旧只清屏幕上那一批,但它的确认句现在会说清被忽略的那批不在其内(「另有 N 条已忽略的记录不在此列。」);
+ 站在「已忽略」视图上按清空,句子说的就是那一批已忽略的记录 —— 那正是该视图的表所显示的。
+
+## 测试
+
+- `packages/server/test/errors.test.ts`(+391 行):规则在范围内覆盖多少条的计数、`message_like` 的匹配、
+ 重复规则的 409、没有这条规则的 404、id 非法 400、`ignored` 参数的校验、过滤只发生在读路径(记录一条不少、
+ 取消后全部回来)、以及三条路由对主人的要求(成员读得到 `errors.ignored`,但读不到规则、也立不了规则)。
+- `packages/web/test/errors-panel.test.ts`(+151 行):`errorsClearScopeText` 在「已忽略」视图上的句子、
+ `errorsClearKeepsIgnoredText`(被忽略的记录要在此列的句子里出现,在它自己那个视图上不出现)、
+ `IgnoreRulesBox` 的三种状态(还没读、没有规则、有规则时每条念什么),以及 `ignoreRuleText` 对窄化过的
+ 规则的念法。
+- `packages/web/e2e/errors-ignore.spec.mjs`(新增 2 条,真服务端 + 真浏览器):一条走行内按钮 —— 忽略后表里
+ 不再有它、通知与横条都说隐藏了几条,而 API 读回来那条记录**还在**(同一个 id)、默认视图读不到它、`ignored=1`
+ 读得到;规则列表里正是这一类;按「撤销」后规则没了、那条记录回到默认视图。另一条走「已忽略」视图 ——
+ 清空确认句里那句「另有 N 条已忽略的记录不在此列。」、规则列表念出这一类与已隐藏多少条、表里就是那批记录,
+ 按「取消忽略」后规则清空、记录回到「全部」视图。
+
+## 兼容性
+
+新增表与路由,不改已有接口的形状:`GET/DELETE /usage/errors` 只是多一个可选参数,仪表盘多一个字段。升级后
+老数据一条不动,没有规则的项目读到的表与以前逐行相同。不引入新依赖,不改 Project 配置。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index f3cbf2e2..5a651bb3 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -4327,6 +4327,13 @@ export interface UsageErrors {
total: number;
/** Count of unexpected ones (500 / runtime exceptions) among them — the part the frontend highlights. */
unexpected: number;
+ /**
+ * How many of the range's records an ignore rule is currently keeping out of all of the above:
+ * counted under the same date/agent filter, but on the other side of the ignore axis (the ones
+ * the panel's stats and table do not show). The panel reports it so a silenced error class is
+ * never invisible twice over — the numbers above say what is shown, never a bare zero.
+ */
+ ignored: number;
/** The most frequent source · code (null when there are no errors). */
topCode: UsageErrorCount | null;
/** Most recent N rows (reverse chronological) — the first page; older ones come from `GET /usage/errors`. */
@@ -4335,6 +4342,60 @@ export interface UsageErrors {
rows: number;
}
+/**
+ * One rule keeping a class of errors out of the panel's default view. The records stay in the
+ * table; the reads stop selecting them (see {@link UsageErrors.ignored}, and the ErrorsRepo's own
+ * note on why filtering happens on read rather than on insert).
+ */
+export interface UsageErrorIgnoreRule {
+ id: number;
+ /** The `error_records.source` it covers. */
+ source: string;
+ /** The `error_records.code` it covers. */
+ code: string;
+ /** The message fragment a covered record must contain; null covers the whole source · code class. */
+ messageLike: string | null;
+ /** Why it was silenced, in the owner's words; null when they wrote none. */
+ note: string | null;
+ /** The Project owner who made it. */
+ createdBy: string;
+ createdAt: string;
+ /** How many of the Project's records it covers, all time. */
+ hidden: number;
+ /** The newest one it covers; null while it covers none yet — the figure that says "it stopped". */
+ lastTs: string | null;
+}
+
+/** What `POST /usage/errors/ignores` takes: the class to silence, and why. */
+export interface UsageErrorIgnoreWrite {
+ source: string;
+ code: string;
+ /**
+ * The message fragment, or null/absent for the whole class. Blank reads as the whole class:
+ * `instr(x, '')` is > 0 for every row, so an empty fragment would mean "cover everything".
+ */
+ messageLike?: string | null;
+ note?: string | null;
+}
+
+/**
+ * `POST /usage/errors/ignores` — the rule that was made, and how much it took off screen.
+ *
+ * `hidden` counts the records the new rule covers **within the range the request carried** (all
+ * time when it carried none), which is what the caller says it just hid. It is deliberately not
+ * the rule's own `hidden`, which is always all time: one answers "what did this button do", the
+ * other "what does this rule hold back".
+ */
+export interface UsageErrorIgnoreAdded {
+ rule: UsageErrorIgnoreRule;
+ hidden: number;
+}
+
+/** `GET /usage/errors/ignores` — the Project's rules, oldest first. */
+export interface UsageErrorIgnores {
+ rules: UsageErrorIgnoreRule[];
+}
+
/**
* 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
diff --git a/packages/server/src/db/repos/errors.ts b/packages/server/src/db/repos/errors.ts
index af40ae94..d17de9f8 100644
--- a/packages/server/src/db/repos/errors.ts
+++ b/packages/server/src/db/repos/errors.ts
@@ -19,6 +19,16 @@
* deleteByProject removes rows, id and row count diverge, and the approximation would
* wrongly delete still-valid data within the cap. The first line of defense is
* ErrorRecorder's short-window deduplication.
+ *
+ * **Ignoring** (error_ignore_rules) keeps recurring-by-design noise — an engine that
+ * reconnects, a tool that reports a missing file — off the panel without losing it: a rule
+ * says which records are covered, and `ErrorFilter.ignored` picks one side of it. The
+ * filtering happens **on read, never on insert**: the recorder sits on the error-handling
+ * path and must not grow a table lookup that can fail, the records stay answerable ("has
+ * this stopped?"), and the engine's own dedup and the row cap already bound the storm. The
+ * axis narrows every read and the clear together, exactly as `kind` does, so a clear still
+ * takes exactly what its caller was looking at — including, from the ignored view, the
+ * covered rows themselves.
*/
import { Component, Use } from "@adelie/core/kernel";
import type { Db } from "../../hmr/capabilities.js";
@@ -70,6 +80,13 @@ export interface ErrorFilter {
agentId?: string;
/** One error category (`unexpected` / `expected`); absent counts both, which is what the panel shows. */
kind?: string;
+ /**
+ * Which side of the ignore rules to read: `true` = only the records a rule covers (the panel's
+ * "ignored" view), absent or `false` = only the records no rule covers (its default view). One
+ * axis among the others — it narrows `summary` / `topCode` / `recent` / `rowCount` and
+ * `deleteFiltered` alike, so what a clear takes stays exactly what its caller read.
+ */
+ ignored?: boolean;
/** Whether to include unattributed errors (`project_id IS NULL`): admins only, defaults to false (see file header). */
includeGlobal?: boolean;
}
@@ -105,6 +122,50 @@ export interface ErrorItem {
firstTs: string;
}
+/**
+ * One rule that keeps a class of errors out of the panel's default view. A record is covered
+ * when its source and code equal the rule's, and — when the rule carries a fragment — its
+ * message contains it. The record itself is untouched: only the reads stop selecting it.
+ */
+export interface ErrorIgnoreRule {
+ id: number;
+ source: string;
+ code: string;
+ /** NULL = the whole source · code class; otherwise only messages containing this substring. Never an empty string (see the schema). */
+ messageLike: string | null;
+ /** Why it was silenced, in the owner's words; NULL when they wrote none. */
+ note: string | null;
+ /** The Project owner who made it. */
+ createdBy: string;
+ createdAt: string;
+ /** How many of this Project's records the rule covers, all time — the rule list's figure. */
+ hidden: number;
+ /** The newest one it covers; NULL while it covers none (a rule made ahead of the noise). */
+ lastTs: string | null;
+}
+
+/** What `addIgnoreRule` writes (the id and the two derived figures come from the table). */
+export interface ErrorIgnoreRuleInsert {
+ source: string;
+ code: string;
+ /**
+ * The message fragment, or null/absent for the whole class. An empty or blank string is read
+ * as the whole class: `instr(x, '')` is > 0 for every row, so keeping the empty string would
+ * mean a rule that covers everything.
+ */
+ messageLike?: string | null;
+ note?: string | null;
+ createdBy: string;
+ createdAt: string;
+}
+
+/** The part of a rule that decides which records it covers — a saved rule's own two columns, or one a caller is only counting. */
+export interface ErrorIgnoreRuleMatch {
+ source: string;
+ code: string;
+ messageLike: string | null;
+}
+
/**
* The calendar day a record falls on in the table: the viewer's, from their offset east of UTC
* applied to `ts`, or — with no offset given — the `date` column, which is the server's own.
@@ -122,6 +183,22 @@ function dayOf(utcOffsetMinutes: number | undefined): {
};
}
+/**
+ * The predicate a record must satisfy to be covered by one of its Project's rules: an EXISTS over
+ * the rules, correlated on the OUTER `error_records` row. The inner `r.source` / `r.code` are the
+ * rule's own columns, so they have to be qualified — written as `r.source = source` the right-hand
+ * name would resolve to `r` and the comparison would be the rule against itself, covering every
+ * record in sight. The fragment test is `instr`, not LIKE: a fragment is literal text, and a LIKE
+ * would first have to escape whatever `%` and `_` it happens to contain.
+ */
+const COVERED_BY_A_RULE = `EXISTS (
+ SELECT 1 FROM error_ignore_rules r
+ WHERE r.project_id = error_records.project_id
+ AND r.source = error_records.source
+ AND r.code = error_records.code
+ AND (r.message_like IS NULL OR instr(error_records.message, r.message_like) > 0)
+ )`;
+
@Component()
export class ErrorsRepo implements ErrorLog {
private readonly maxRows: number = MAX_ROWS;
@@ -170,11 +247,31 @@ export class ErrorsRepo implements ErrorLog {
.run({ excess });
}
- /** WHERE fragment and named params: this Project (admins additionally get unattributed errors), plus optional date/agent filter. */
+ /**
+ * WHERE fragment and named params: everything the caller filtered by — this Project (admins
+ * additionally get unattributed errors), the dates, the window, the Agent, the category — and
+ * then the one axis that is not a column on the table, `ignored`, resolved against the rules.
+ */
private conds(
projectId: string,
f: ErrorFilter,
): { where: string; params: Record<string, string> } {
+ const { conds, params } = this.scopeConds(projectId, f);
+ // The default view is what no rule covers; the ignored view is what one does. Both sides are
+ // the same predicate, so neither can drift from the other or from `ignoreRuleMatches`.
+ conds.push(f.ignored === true ? COVERED_BY_A_RULE : `NOT ${COVERED_BY_A_RULE}`);
+ return { where: conds.join(" AND "), params };
+ }
+
+ /**
+ * `conds` without the ignore axis: the Project, the dates, the window, the Agent and the
+ * category. Kept apart for the two callers that must NOT be narrowed by a rule — counting what
+ * one rule covers, and matching a rule against the rows it will cover from now on.
+ */
+ private scopeConds(
+ projectId: string,
+ f: ErrorFilter,
+ ): { conds: string[]; params: Record<string, string> } {
// Unattributed errors (login failures, process crashes, ...) are visible only to admins; otherwise it's a cross-tenant leak — see file header.
const conds = [
f.includeGlobal === true ? "(project_id = :pid OR project_id IS NULL)" : "project_id = :pid",
@@ -209,7 +306,7 @@ export class ErrorsRepo implements ErrorLog {
conds.push("kind = :kind");
params.kind = f.kind;
}
- return { where: conds.join(" AND "), params };
+ return { conds, params };
}
/** Total count + how many are unexpected. */
@@ -327,8 +424,109 @@ export class ErrorsRepo implements ErrorLog {
.run(projectId, agentId);
}
- /** Cascading cleanup on Project deletion (unattributed errors belong to no Project and are unaffected). */
+ /**
+ * Cascading cleanup on Project deletion (unattributed errors belong to no Project and are
+ * unaffected). The Project's ignore rules go with it: they name its errors and mean nothing
+ * once those are gone.
+ */
deleteByProject(projectId: string): void {
this.db.prepare("DELETE FROM error_records WHERE project_id = ?").run(projectId);
+ this.db.prepare("DELETE FROM error_ignore_rules WHERE project_id = ?").run(projectId);
+ }
+
+ /**
+ * The rules keeping this Project's errors out of its default view, oldest first, each with what
+ * it covers right now. The two figures are correlated subqueries rather than a join: a rule that
+ * covers nothing yet still belongs in the list ("I silenced this before it came back"), and a
+ * rule list is a handful of rows that the panel draws whole.
+ */
+ ignoreRules(projectId: string): ErrorIgnoreRule[] {
+ const rows = this.db
+ .prepare(
+ `SELECT r.id, r.source, r.code, r.message_like, r.note, r.created_by, r.created_at,
+ (SELECT COUNT(*) FROM error_records e
+ WHERE e.project_id = r.project_id AND e.source = r.source AND e.code = r.code
+ AND (r.message_like IS NULL OR instr(e.message, r.message_like) > 0)) AS hidden,
+ (SELECT MAX(e.ts) FROM error_records e
+ WHERE e.project_id = r.project_id AND e.source = r.source AND e.code = r.code
+ AND (r.message_like IS NULL OR instr(e.message, r.message_like) > 0)) AS last_ts
+ FROM error_ignore_rules r
+ WHERE r.project_id = ? ORDER BY r.id`,
+ )
+ .all(projectId);
+ return rows.map((r) => ({
+ id: r.id as number,
+ source: r.source as string,
+ code: r.code as string,
+ messageLike: (r.message_like ?? null) as string | null,
+ note: (r.note ?? null) as string | null,
+ createdBy: r.created_by as string,
+ createdAt: r.created_at as string,
+ hidden: r.hidden as number,
+ lastTs: (r.last_ts ?? null) as string | null,
+ }));
+ }
+
+ /**
+ * Adds one rule, or answers null when the Project already has a rule for that class — the same
+ * (source, code, fragment) is one rule, not two, and the answer is the caller's to turn into a
+ * refusal. Checked here rather than left to the unique index so the ordinary case is a value
+ * and not a caught constraint error; the index remains the backstop.
+ */
+ addIgnoreRule(projectId: string, r: ErrorIgnoreRuleInsert): ErrorIgnoreRule | null {
+ const fragment = blankToNull(r.messageLike);
+ const duplicate = this.db
+ .prepare(
+ `SELECT 1 FROM error_ignore_rules
+ WHERE project_id = ? AND source = ? AND code = ? AND ifnull(message_like, '') = ifnull(?, '')`,
+ )
+ .get(projectId, r.source, r.code, fragment);
+ if (duplicate) return null;
+ const res = this.db
+ .prepare(
+ `INSERT INTO error_ignore_rules
+ (project_id, source, code, message_like, note, created_by, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run(projectId, r.source, r.code, fragment, blankToNull(r.note), r.createdBy, r.createdAt);
+ return this.ignoreRules(projectId).find((rule) => rule.id === Number(res.lastInsertRowid))!;
+ }
+
+ /** Removes one rule from this Project; false when there was no such rule in it. */
+ removeIgnoreRule(projectId: string, id: number): boolean {
+ const res = this.db
+ .prepare("DELETE FROM error_ignore_rules WHERE project_id = ? AND id = ?")
+ .run(projectId, id);
+ return Number(res.changes) > 0;
+ }
+
+ /**
+ * How many of this Project's records one class covers — `ignoreRules`' own figure, but read
+ * against a caller's range instead of all time, and against a class that need not be saved yet.
+ * Deliberately not narrowed by the ignore axis: what it counts is exactly the records the rule
+ * will take off a panel showing that range.
+ */
+ ignoreRuleMatches(
+ projectId: string,
+ rule: ErrorIgnoreRuleMatch,
+ f: Omit<ErrorFilter, "ignored"> = {},
+ ): number {
+ const { conds, params } = this.scopeConds(projectId, f);
+ const scoped: Record<string, string> = { ...params, rSource: rule.source, rCode: rule.code };
+ conds.push("source = :rSource", "code = :rCode");
+ if (rule.messageLike !== null) {
+ conds.push("instr(message, :rMessage) > 0");
+ scoped.rMessage = rule.messageLike;
+ }
+ const row = this.db
+ .prepare(`SELECT COUNT(*) AS n FROM error_records WHERE ${conds.join(" AND ")}`)
+ .get(scoped)!;
+ return row.n as number;
}
}
+
+/** An absent, empty or whitespace-only string is no string at all — the two columns where that distinction is the whole meaning. */
+function blankToNull(value: string | null | undefined): string | null {
+ const trimmed = value?.trim();
+ return trimmed ? trimmed : null;
+}
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index 519ab112..889f3650 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -130,6 +130,18 @@ CREATE TABLE IF NOT EXISTS error_records ( -- server-side error capture (the
message TEXT NOT NULL -- truncated to 500 chars (no stack stored: stacks go to logs only)
);
CREATE INDEX IF NOT EXISTS idx_error_project_date ON error_records(project_id, date);
+CREATE TABLE IF NOT EXISTS error_ignore_rules ( -- what the error panel's "ignore" leaves out: the records stay in error_records and the reads stop selecting them (ErrorsRepo.conds); NOT rebuildable from files, and only a person makes one
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ project_id TEXT NOT NULL,
+ source TEXT NOT NULL, -- the error_records.source this rule covers
+ code TEXT NOT NULL, -- the error_records.code this rule covers
+ message_like TEXT, -- NULL = the whole source · code class; otherwise only messages containing this substring. Never "": instr(x, '') is > 0 for every row, so the empty string would silently mean "everything"
+ note TEXT, -- why it was silenced, in the owner's own words; shown in the rule list
+ created_by TEXT NOT NULL, -- the Project owner who made it
+ created_at TEXT NOT NULL
+);
+-- One rule per (source, code, message fragment): re-adding one is what this refuses. ifnull maps the NULL fragment (the whole class) onto '' so the two spellings of "no fragment" cannot both exist; the index also serves the per-Project read, whose only other predicate is the (source, code) pair.
+CREATE UNIQUE INDEX IF NOT EXISTS idx_error_ignore_rule ON error_ignore_rules(project_id, source, code, ifnull(message_like, ''));
CREATE TABLE IF NOT EXISTS schedule_state ( -- schedule runtime state (files are declarative intent; the system never writes back)
project_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
diff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.ts
index 4538d719..ad4ad657 100644
--- a/packages/server/src/http/routes/usage.ts
+++ b/packages/server/src/http/routes/usage.ts
@@ -5,26 +5,44 @@
* 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&fromTs&toTs&agentId&kind — one page
+ * GET /api/projects/:p/usage/errors?offset&limit&from&to&fromTs&toTs&agentId&kind&ignored — one page
* 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&kind — empties that table
+ * calendar day the table folds a day's repeats by; `ignored` reads the other side of the
+ * Project's ignore rules);
+ * DELETE /api/projects/:p/usage/errors?from&to&fromTs&toTs&until&agentId&kind&ignored — 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);
+ * GET /api/projects/:p/usage/errors/ignores — the Project's ignore rules, each with what it
+ * covers (owner only);
+ * POST /api/projects/:p/usage/errors/ignores?from&to&fromTs&toTs&agentId — adds one rule, and
+ * answers how many records it covers in that range (owner only; `source` and `code` required,
+ * `messageLike` narrows it to messages containing that fragment; 409 when the class is already
+ * ignored);
+ * DELETE /api/projects/:p/usage/errors/ignores/:id — removes one rule (owner only; 404 when this
+ * Project has none);
* GET /api/projects/:p/usage/model-totals — lifetime Token total per Model, unfiltered.
*/
import { Hono } from "hono";
import type { Context } from "hono";
import type {
+ UsageErrorIgnoreAdded,
+ UsageErrorIgnores,
UsageErrorKind,
UsageErrorsClearResponse,
UsageGranularity,
UsageGroupBy,
} from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
-import { badRequest, optionalDateParam, paginationQuery, requireValidId } from "../validate.js";
+import {
+ badRequest,
+ optionalDateParam,
+ paginationQuery,
+ parseNonNegativeInt,
+ requireValidId,
+} from "../validate.js";
+import { HttpError } from "../errors.js";
import type { UsageQueries } from "../../mechanisms/observability.js";
import type { Access } from "../../mechanisms/projects.js";
@@ -89,6 +107,41 @@ function tsWindowQuery(c: Context<AppEnv>): { fromTs?: string; toTs?: string } {
return { ...(fromTs !== undefined ? { fromTs } : {}), ...(toTs !== undefined ? { toTs } : {}) };
}
+/**
+ * The error panel's range: the dates, the trailing window and the Agent every error read and write
+ * shares. One parser for all four, so "the range on screen" means the same thing to the reads, to a
+ * clear, and to the count a new ignore rule reports having hidden.
+ */
+function errorRangeQuery(c: Context<AppEnv>): {
+ from?: string;
+ to?: string;
+ fromTs?: string;
+ toTs?: string;
+ agentId?: string;
+} {
+ const from = optionalDateParam(c.req.query("from"), "from");
+ const to = optionalDateParam(c.req.query("to"), "to");
+ const agentId = c.req.query("agentId");
+ return {
+ ...(from !== undefined ? { from } : {}),
+ ...(to !== undefined ? { to } : {}),
+ ...tsWindowQuery(c),
+ ...(agentId !== undefined && agentId !== "" ? { agentId } : {}),
+ };
+}
+
+/**
+ * Which side of the Project's ignore rules to read or clear: `1` the records a rule covers, `0`
+ * (or nothing) the ones no rule covers. Validated like `kind` and for the same reason — a typo
+ * that passed through would silently read the other side and report the wrong table as empty.
+ */
+function ignoredQuery(c: Context<AppEnv>): boolean | undefined {
+ const raw = c.req.query("ignored");
+ if (raw === undefined || raw === "" || raw === "0" || raw === "false") return undefined;
+ if (raw === "1" || raw === "true") return true;
+ throw badRequest("ignored must be 0 or 1.");
+}
+
export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@@ -151,11 +204,8 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {
const projectId = requireValidId(c, "projectId");
deps.access.requireProjectAccess(c.var.user.userId, projectId);
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 range = errorRangeQuery(c);
const utcOffsetMinutes = utcOffsetQuery(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
// validated against that closed set rather than passed through, so a typo asks for
@@ -167,6 +217,7 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {
) {
throw badRequest(`kind must be one of ${ERROR_KINDS.join(" / ")}.`);
}
+ const ignored = ignoredQuery(c);
return c.json(
deps.usageService.queryErrors(projectId, {
offset,
@@ -174,46 +225,42 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {
// Same admin-only rule as the dashboard: a regular member seeing another tenant's
// unattributed errors would be a cross-tenant leak.
includeGlobalErrors: c.var.user.isAdmin,
- ...(from !== undefined ? { from } : {}),
- ...(to !== undefined ? { to } : {}),
- ...window,
+ ...range,
...(utcOffsetMinutes !== undefined ? { utcOffsetMinutes } : {}),
- ...(agentId !== undefined && agentId !== "" ? { agentId } : {}),
...(kindRaw !== undefined && kindRaw !== "" ? { kind: kindRaw } : {}),
+ ...(ignored !== undefined ? { ignored } : {}),
}),
);
});
// 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.
+ // agent, category and ignore side 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` and
+ // `ignored` are accepted because the panel has those controls: its table and its button read the
+ // same filter, so a reader narrowed to one category keeps the other one, and a reader standing
+ // on the ignored view is the one person who may delete those rows.
app.delete("/errors", (c) => {
const projectId = requireValidId(c, "projectId");
// Owner only, the rule Agent deletion applies to error rows already (it cascade-deletes
// them): membership is enough to READ the panel, but these rows are the Project's shared
// history and one member emptying them takes them from everyone.
deps.access.requireProjectOwner(c.var.user.userId, projectId);
- const from = optionalDateParam(c.req.query("from"), "from");
- const to = optionalDateParam(c.req.query("to"), "to");
+ const range = errorRangeQuery(c);
// 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) {
+ if (range.from === undefined || range.to === undefined) {
throw badRequest("from and to are both required.");
}
- const window = tsWindowQuery(c);
// The boundary the confirmation counted, optional: without it the clear takes everything
// the filter matches, which is what a caller that never showed a count is asking for. A
// malformed instant is refused rather than dropped — a clear that quietly ignores its
// 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
@@ -225,21 +272,87 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {
) {
throw badRequest(`kind must be one of ${ERROR_KINDS.join(" / ")}.`);
}
+ const ignored = ignoredQuery(c);
// 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, {
includeGlobalErrors: c.var.user.isAdmin,
- from,
- to,
- ...window,
+ ...range,
...(until !== undefined ? { until } : {}),
- ...(agentId !== undefined && agentId !== "" ? { agentId } : {}),
...(kindRaw !== undefined && kindRaw !== "" ? { kind: kindRaw } : {}),
+ ...(ignored !== undefined ? { ignored } : {}),
});
return c.json({ deleted } satisfies UsageErrorsClearResponse);
});
+ // The Project's ignore rules: the error classes its owner has taken out of the panel's default
+ // view. Owner only, the line the clear draws and for the same reason — a rule changes what
+ // everyone reading this Project sees. The panel reports the count to members on its own (the
+ // dashboard's `errors.ignored`), so reading the rules themselves is management, not disclosure.
+ app.get("/errors/ignores", (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
+ return c.json({ rules: deps.usageService.errorIgnores(projectId) } satisfies UsageErrorIgnores);
+ });
+
+ // Adds one rule. The records are not touched — the rule only decides which ones the reads select
+ // — so this is undoable, and the answer carries how many records it covers in the range the
+ // caller was looking at: what the caller says it just hid. The range is the same one the reads
+ // and the clear take, so the number matches the table it came from.
+ app.post("/errors/ignores", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
+ const body = (await c.req.json().catch(() => null)) as {
+ source?: unknown;
+ code?: unknown;
+ messageLike?: unknown;
+ note?: unknown;
+ } | null;
+ // A rule with no source or no code covers nothing while reading as a rule, so both are
+ // required rather than defaulted; the lengths are capped because they are matched against two
+ // columns and the note is drawn in a list row.
+ const source = typeof body?.source === "string" ? body.source.trim() : "";
+ const code = typeof body?.code === "string" ? body.code.trim() : "";
+ if (source === "" || code === "") throw badRequest("source and code are both required.");
+ if (source.length > 64 || code.length > 200) {
+ throw badRequest("source must be at most 64 characters and code at most 200.");
+ }
+ const messageLike = typeof body?.messageLike === "string" ? body.messageLike : null;
+ const note = typeof body?.note === "string" ? body.note : null;
+ if ((messageLike?.length ?? 0) > 200 || (note?.length ?? 0) > 200) {
+ throw badRequest("messageLike and note must be at most 200 characters.");
+ }
+ const added = deps.usageService.addErrorIgnore(
+ projectId,
+ { source, code, messageLike, note, createdBy: c.var.user.userId },
+ errorRangeQuery(c),
+ );
+ // Already ignored: the same (source, code, fragment) is one rule, and a second row covering the
+ // same records would leave the list saying the same thing twice.
+ if (added === null) {
+ throw new HttpError(
+ 409,
+ "ignore_rule_exists",
+ `This Project already ignores [${source}] ${code}.`,
+ );
+ }
+ return c.json(added satisfies UsageErrorIgnoreAdded, 201);
+ });
+
+ // Removes one rule, which re-exposes every record it covered — nothing was ever deleted, so this
+ // is the whole of the undo.
+ app.delete("/errors/ignores/:id", (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
+ const id = parseNonNegativeInt(c.req.param("id") ?? "");
+ if (id === null) throw badRequest("id must be a non-negative integer.");
+ if (!deps.usageService.removeErrorIgnore(projectId, id)) {
+ throw new HttpError(404, "ignore_rule_not_found", "No such ignore rule in this Project.");
+ }
+ return c.json({ removed: true });
+ });
+
return app;
}
diff --git a/packages/server/src/mechanisms/observability.ts b/packages/server/src/mechanisms/observability.ts
index c6e48a6d..82b52a6a 100644
--- a/packages/server/src/mechanisms/observability.ts
+++ b/packages/server/src/mechanisms/observability.ts
@@ -6,6 +6,9 @@ import type { Opaque } from "@adelie/core/kernel";
import type {
ErrorCodeCount,
ErrorFilter,
+ ErrorIgnoreRule,
+ ErrorIgnoreRuleInsert,
+ ErrorIgnoreRuleMatch,
ErrorItem,
ErrorRecordInsert,
ErrorSummary,
@@ -22,6 +25,9 @@ import type {
UnsettledUsageRow,
} from "../db/repos/usage.js";
import type {
+ UsageErrorIgnoreAdded,
+ UsageErrorIgnoreRule,
+ UsageErrorIgnoreWrite,
UsageErrorsPage,
UsageGroupBy,
UsageResponse,
@@ -56,6 +62,7 @@ import type {
ToolListReadyPayload,
} from "@adelie/core";
import type {
+ ErrorIgnoreAddInput,
UsageQuery,
UsageErrorsClearQuery,
UsageErrorsQuery,
@@ -78,6 +85,14 @@ export abstract class ErrorLog {
abstract deleteFiltered(projectId: string, f?: Omit<ErrorFilter, "includeGlobal">): number;
abstract deleteByAgent(projectId: string, agentId: string): void;
abstract deleteByProject(projectId: string): void;
+ abstract ignoreRules(projectId: string): ErrorIgnoreRule[];
+ abstract addIgnoreRule(projectId: string, r: ErrorIgnoreRuleInsert): ErrorIgnoreRule | null;
+ abstract removeIgnoreRule(projectId: string, id: number): boolean;
+ abstract ignoreRuleMatches(
+ projectId: string,
+ rule: ErrorIgnoreRuleMatch,
+ f?: Omit<ErrorFilter, "ignored">,
+ ): number;
}
/** Errors: the mechanism ErrorRecorder implements. */
@@ -126,6 +141,14 @@ export abstract class UsageQueries {
abstract query(projectId: string, q: UsageQuery): Promise<UsageResponse>;
abstract queryErrors(projectId: string, q: UsageErrorsQuery): UsageErrorsPage;
abstract clearErrors(projectId: string, q: UsageErrorsClearQuery): number;
+ abstract errorIgnores(projectId: string): UsageErrorIgnoreRule[];
+ /** Adds one rule; null when the Project already has one for that class (the route answers 409). */
+ abstract addErrorIgnore(
+ projectId: string,
+ input: ErrorIgnoreAddInput,
+ range?: Omit<UsageErrorsClearQuery, "until" | "kind" | "includeGlobalErrors">,
+ ): UsageErrorIgnoreAdded | null;
+ abstract removeErrorIgnore(projectId: string, id: number): boolean;
abstract modelTotals(projectId: string): UsageModelTotals;
/** Fixes the cost of every usage row that has none yet; returns how many it settled. */
abstract settleUnsettledCosts(): Promise<number>;
diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.ts
index ac318ab0..705ff958 100644
--- a/packages/server/src/services/usage-service.ts
+++ b/packages/server/src/services/usage-service.ts
@@ -19,6 +19,9 @@
import type {
UsageAgentSeries,
UsageBucket,
+ UsageErrorIgnoreAdded,
+ UsageErrorIgnoreRule,
+ UsageErrorIgnoreWrite,
UsageErrors,
UsageErrorsPage,
UsageGranularity,
@@ -29,7 +32,7 @@ import type {
UsageResponse,
UsageSeriesPoint,
} from "../api/types.js";
-import type { ErrorFilter } from "../db/repos/errors.js";
+import type { ErrorFilter, ErrorIgnoreRule } from "../db/repos/errors.js";
import type {
UsageModelSums,
UsageGroupModelSums,
@@ -117,6 +120,12 @@ export interface UsageErrorsQuery {
agentId?: string;
/** Narrow to one category — `unexpected` (500s / runtime exceptions) or `expected`; absent counts both. */
kind?: string;
+ /**
+ * Which side of the ignore rules to read: true = only the records a rule covers (the panel's
+ * "ignored" view), absent = only the records no rule covers, which is every other view. One more
+ * narrowing of the same filter, so a page never widens what the summary above it counted.
+ */
+ ignored?: boolean;
/** Admin only: include errors with no Project attribution (see the ErrorsRepo file header). */
includeGlobalErrors?: boolean;
/** The viewer's offset east of UTC, in minutes (see {@link UsageQuery}). */
@@ -143,6 +152,8 @@ export interface UsageErrorsClearQuery {
agentId?: string;
/** Narrow to one category, the value the caller's reads carry; absent counts both. */
kind?: string;
+ /** The ignore side the caller's reads carry: true clears the rows a rule covers (the "ignored" view's own table), absent clears the rows no rule covers. */
+ ignored?: boolean;
/** Admin only, the value the caller's reads carry: an admin's clear takes the unattributed rows an admin's panel shows. */
includeGlobalErrors?: boolean;
}
@@ -165,6 +176,37 @@ function refKey(provider: string, modelId: string): string {
return `${provider}\0${modelId}`;
}
+/**
+ * What {@link UsageService.addErrorIgnore} takes: the caller's own input plus the owner the route
+ * resolved from the session. `createdBy` is deliberately not part of the wire type — a body that
+ * could name its own author would let one Project's owner file a rule under someone else's name.
+ */
+export interface ErrorIgnoreAddInput extends UsageErrorIgnoreWrite {
+ createdBy: string;
+}
+
+/**
+ * The range half of a clear or ignore query, as the repo's filter. The two writes share it because
+ * both answer for the range the caller was looking at: what a clear removes, and what a new rule
+ * takes off the screen.
+ */
+function rangeFilter(
+ q: Omit<UsageErrorsClearQuery, "until" | "kind" | "includeGlobalErrors">,
+): Omit<ErrorFilter, "ignored"> {
+ return {
+ ...(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 } : {}),
+ };
+}
+
+/** The repo's rule row as the API contract spells it. The contract is a separate declaration because it is what the frontend imports; the shape is the repo's. */
+function toIgnoreRuleDto(rule: ErrorIgnoreRule): UsageErrorIgnoreRule {
+ return { ...rule };
+}
+
@Component()
export class UsageService implements UsageQueries {
@Use() private readonly usage!: UsageStore;
@@ -387,6 +429,7 @@ export class UsageService implements UsageQueries {
...(q.fromTs !== undefined ? { fromTs: q.fromTs } : {}),
...(q.toTs !== undefined ? { toTs: q.toTs } : {}),
...(q.kind !== undefined ? { kind: q.kind } : {}),
+ ...(q.ignored === true ? { ignored: true } : {}),
...(q.includeGlobalErrors === true ? { includeGlobal: true } : {}),
};
return {
@@ -415,16 +458,63 @@ export class UsageService implements UsageQueries {
...(q.toTs !== undefined ? { toTs: q.toTs } : {}),
...(q.until !== undefined ? { until: q.until } : {}),
...(q.kind !== undefined ? { kind: q.kind } : {}),
+ ...(q.ignored === true ? { ignored: true } : {}),
...(q.includeGlobalErrors === true ? { includeGlobal: true } : {}),
});
}
+ /** The Project's ignore rules, oldest first, each with what it currently covers. */
+ errorIgnores(projectId: string): UsageErrorIgnoreRule[] {
+ return this.errors.ignoreRules(projectId).map(toIgnoreRuleDto);
+ }
+
+ /**
+ * Silences one class of errors for this Project. Records are not touched — the rule only changes
+ * which ones the reads select — so this is undoable and answers with how many records it covers
+ * in the range the caller was looking at, which is what a caller reports having just hidden.
+ *
+ * `null` when the Project already has a rule for that class: the same (source, code, fragment)
+ * is one rule, and re-adding it is a refusal rather than a second row covering the same records.
+ */
+ addErrorIgnore(
+ projectId: string,
+ input: ErrorIgnoreAddInput,
+ range: Omit<UsageErrorsClearQuery, "until" | "kind" | "includeGlobalErrors"> = {},
+ ): UsageErrorIgnoreAdded | null {
+ const fragment = input.messageLike?.trim() ? input.messageLike.trim() : null;
+ const rule = this.errors.addIgnoreRule(projectId, {
+ source: input.source,
+ code: input.code,
+ messageLike: fragment,
+ note: input.note ?? null,
+ createdBy: input.createdBy,
+ createdAt: this.clock.now().toISOString(),
+ });
+ if (rule === null) return null;
+ return {
+ rule: toIgnoreRuleDto(rule),
+ hidden: this.errors.ignoreRuleMatches(
+ projectId,
+ { source: rule.source, code: rule.code, messageLike: rule.messageLike },
+ rangeFilter(range),
+ ),
+ };
+ }
+
+ /** Removes one rule, re-exposing the records it covered (they were never deleted); false when this Project has no such rule. */
+ removeErrorIgnore(projectId: string, id: number): boolean {
+ return this.errors.removeIgnoreRule(projectId, id);
+ }
+
/** Error statistics: summary info (total / unexpected / most common error code) + the table's first N rows and its row count, all filtered by the selected range. */
private foldErrors(projectId: string, f: ErrorFilter, utcOffsetMinutes?: number): UsageErrors {
const { total, unexpected } = this.errors.summary(projectId, f);
return {
total,
unexpected,
+ // The other side of the same filter, so the panel can report what its rules hold back rather
+ // than showing a bare zero: counted under the caller's range, on the ignored side of the axis.
+ ignored: this.errors.summary(projectId, { ...f, ignored: true }).total,
topCode: this.errors.topCode(projectId, f),
recent: this.errors.recent(projectId, f, ERROR_RECENT_N, 0, utcOffsetMinutes),
rows: this.errors.rowCount(projectId, f, utcOffsetMinutes),
diff --git a/packages/server/test/errors.test.ts b/packages/server/test/errors.test.ts
index 9aa71281..0d949fbf 100644
--- a/packages/server/test/errors.test.ts
+++ b/packages/server/test/errors.test.ts
@@ -9,6 +9,9 @@
* and the row count are rows, the summary still counts records.
* - A clear follows the caller's read: a member's leaves the unattributed rows, an admin's
* takes them; another Project's rows are out of reach either way.
+ * - An ignore rule (a source · code, optionally narrowed by a message fragment) takes that class
+ * off every read's default side without deleting a row: the reads, the clear and the rule's own
+ * coverage count all take the same axis; rules are per Project and go with it.
* - Past its cap the log evicts its oldest rows by count, never misled by id gaps.
*
* The recorder (ErrorRecorder):
@@ -42,6 +45,8 @@
* offset no clock uses is a 400.
* - Clearing takes exactly the filter or trailing window on screen, never an unbounded range;
* a member may not clear; an admin's clear takes the unattributed rows it showed.
+ * - The owner silences a class (never a member, and never a non-member's Project), the panel then
+ * reports it under `ignored` and reads it back on request, and removing the rule restores it.
* - Deleting a Project deletes its error records and nobody else's.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -62,7 +67,13 @@ import {
withOrigin,
} from "@adelie/core";
import type { OmniMessage, StopReason } from "@adelie/core";
-import type { ProjectCreateResponse, UsageErrorsPage, UsageResponse } from "../src/api/types.js";
+import type {
+ ProjectCreateResponse,
+ UsageErrorIgnoreAdded,
+ UsageErrorIgnores,
+ UsageErrorsPage,
+ UsageResponse,
+} from "../src/api/types.js";
import { openDatabase } from "../src/db/database.js";
import { ErrorsRepo } from "../src/db/repos/errors.js";
import type { ErrorRecordInsert } from "../src/db/repos/errors.js";
@@ -247,6 +258,161 @@ describe("errors-repo", () => {
expect(remaining()).toEqual(["other tenant"]);
});
+ // —— Ignoring: rules that keep a class off the panel's default view, on read, without losing a row ——
+
+ it("an ignore rule takes a whole class out of every read, while the records stay in the table", () => {
+ // Three of the class to silence, two of another one that must keep showing.
+ for (let i = 0; i < 3; i++) repo.insert(row("2026-07-06", { code: "internal" }));
+ for (let i = 0; i < 2; i++)
+ repo.insert(row("2026-07-06", { source: "messaging", code: "messaging_connect_failed" }));
+
+ const rule = repo.addIgnoreRule("p1", {
+ source: "http",
+ code: "internal",
+ createdBy: "owner",
+ createdAt: "2026-07-06T10:00:00.000Z",
+ });
+ expect(rule).toMatchObject({ source: "http", code: "internal", messageLike: null, hidden: 3 });
+
+ // Every read not asked for the ignored side leaves the class out …
+ expect(repo.summary("p1")).toEqual({ total: 2, unexpected: 2 });
+ expect(repo.topCode("p1")).toMatchObject({ source: "messaging", count: 2 });
+ expect(repo.recent("p1").map((r) => r.source)).toEqual(["messaging"]);
+ expect(repo.rowCount("p1")).toBe(1);
+ // … and the other side reads exactly it, which is what the panel's "ignored" view shows.
+ expect(repo.summary("p1", { ignored: true })).toEqual({ total: 3, unexpected: 3 });
+ expect(repo.recent("p1", { ignored: true }).map((r) => r.source)).toEqual(["http"]);
+ // Nothing was deleted: the rule changes which rows the reads select, not what is stored.
+ expect(
+ db.prepare("SELECT COUNT(*) AS n FROM error_records WHERE code = 'internal'").get(),
+ ).toEqual({ n: 3 });
+ });
+
+ it("a fragment narrows a rule to the messages that contain it", () => {
+ const at = (message: string) => repo.insert(row("2026-07-06", { code: "internal", message }));
+ at("other side closed");
+ at("other side closed (again)");
+ at("disk full");
+ repo.addIgnoreRule("p1", {
+ source: "http",
+ code: "internal",
+ messageLike: "other side closed",
+ createdBy: "owner",
+ createdAt: "2026-07-06T10:00:00.000Z",
+ });
+
+ // A literal substring, not a pattern: the two sharing it go, the third stays.
+ expect(repo.recent("p1").map((r) => r.message)).toEqual(["disk full"]);
+ expect(repo.summary("p1")).toEqual({ total: 1, unexpected: 1 });
+ expect(repo.summary("p1", { ignored: true })).toEqual({ total: 2, unexpected: 2 });
+ });
+
+ it("a blank fragment means the whole class, not a rule that swallows every record", () => {
+ repo.insert(row("2026-07-06", { code: "internal", message: "boom" }));
+ repo.insert(
+ row("2026-07-06", { source: "session", code: "session_run_failed", message: "nope" }),
+ );
+ // instr(x, '') is > 0 for every row: keeping the empty string would make this one rule cover
+ // every record in the table, so a blank fragment has to read as "no fragment".
+ const rule = repo.addIgnoreRule("p1", {
+ source: "http",
+ code: "internal",
+ messageLike: " ",
+ createdBy: "owner",
+ createdAt: "2026-07-06T10:00:00.000Z",
+ });
+ expect(rule?.messageLike).toBeNull();
+ expect(repo.summary("p1")).toEqual({ total: 1, unexpected: 1 });
+ expect(repo.recent("p1").map((r) => r.source)).toEqual(["session"]);
+ });
+
+ it("one rule per class: the same (source, code, fragment) is refused, a different fragment is another rule", () => {
+ const make = (messageLike: string | null) =>
+ repo.addIgnoreRule("p1", {
+ source: "http",
+ code: "internal",
+ messageLike,
+ createdBy: "owner",
+ createdAt: "2026-07-06T10:00:00.000Z",
+ });
+
+ expect(make(null)).not.toBeNull();
+ // The same class is one rule, not two rows saying it twice.
+ expect(make(null)).toBeNull();
+ expect(make("other side closed")).not.toBeNull();
+ // A blank fragment is the whole class, so it collides with the whole-class rule above.
+ expect(make(" ")).toBeNull();
+ expect(repo.ignoreRules("p1")).toHaveLength(2);
+ });
+
+ it("rules are per Project, and deleting a Project takes its rules with it", () => {
+ repo.insert(row("2026-07-06", { projectId: "p1", code: "internal" }));
+ repo.insert(row("2026-07-06", { projectId: "p2", code: "internal" }));
+ const rule = (projectId: string) =>
+ repo.addIgnoreRule(projectId, {
+ source: "http",
+ code: "internal",
+ createdBy: "owner",
+ createdAt: "2026-07-06T10:00:00.000Z",
+ });
+ rule("p1");
+ rule("p2");
+
+ // p2's rule silences p2's records only, so the same class in p1 reads untouched.
+ expect(repo.summary("p1")).toEqual({ total: 0, unexpected: 0 });
+ expect(repo.summary("p1", { ignored: true })).toEqual({ total: 1, unexpected: 1 });
+ expect(repo.summary("p2", { ignored: true })).toEqual({ total: 1, unexpected: 1 });
+
+ // A rule names one Project's errors and means nothing once they are gone.
+ repo.deleteByProject("p1");
+ expect(repo.ignoreRules("p1")).toEqual([]);
+ expect(repo.ignoreRules("p2")).toHaveLength(1);
+ expect(repo.summary("p2", { ignored: true })).toEqual({ total: 1, unexpected: 1 });
+ });
+
+ it("a clear on either side takes only that side's rows", () => {
+ for (let i = 0; i < 2; i++)
+ repo.insert(row("2026-07-06", { code: "internal", message: "silenced" }));
+ repo.insert(
+ row("2026-07-06", { source: "session", code: "session_run_failed", message: "shown" }),
+ );
+ repo.addIgnoreRule("p1", {
+ source: "http",
+ code: "internal",
+ createdBy: "owner",
+ createdAt: "2026-07-06T10:00:00.000Z",
+ });
+
+ // Default side: the rows the panel shows, and no other.
+ expect(repo.deleteFiltered("p1")).toBe(1);
+ expect(repo.summary("p1", { ignored: true })).toEqual({ total: 2, unexpected: 2 });
+
+ // Standing on the ignored view, the same button is the one that may take the covered rows.
+ expect(repo.deleteFiltered("p1", { ignored: true })).toBe(2);
+ expect(db.prepare("SELECT COUNT(*) AS n FROM error_records").get()).toEqual({ n: 0 });
+ });
+
+ it("ignoreRuleMatches counts a class against a range, saved or not", () => {
+ repo.insert(row("2026-07-05", { code: "internal" }));
+ repo.insert(row("2026-07-06", { code: "internal" }));
+ repo.insert(row("2026-07-06", { code: "internal", message: "other side closed" }));
+ repo.insert(row("2026-07-07", { code: "internal" }));
+
+ const wholeClass = { source: "http", code: "internal", messageLike: null };
+ expect(repo.ignoreRuleMatches("p1", wholeClass)).toBe(4);
+ // Against a caller's range, which is what a new rule reports having just hidden.
+ expect(repo.ignoreRuleMatches("p1", wholeClass, { from: "2026-07-06", to: "2026-07-06" })).toBe(
+ 2,
+ );
+ expect(repo.ignoreRuleMatches("p1", wholeClass, { from: "2026-07-06", to: "2026-07-07" })).toBe(
+ 3,
+ );
+ // A fragment narrows it; the axis is never applied here — it counts what a rule will take off.
+ expect(repo.ignoreRuleMatches("p1", { ...wholeClass, messageLike: "other side closed" })).toBe(
+ 1,
+ );
+ });
+
// —— Row cap (the second line of defense against error storms; the first is ErrorRecorder's short-window dedup) ——
const messages = () =>
@@ -1578,6 +1744,229 @@ describe("HTTP onError persistence (integration)", () => {
expect(del.status).toBe(204);
expect(errorRows().map((r) => r.project_id)).toEqual([null]);
});
+
+ // —— Ignoring: the owner silences a class, the panel reads one side or the other, nothing is lost ——
+
+ it("an ignore rule takes a class off the panel while its records stay in the table", async () => {
+ // Seeded directly so the repeats are exact — going through HTTP would collapse them into the
+ // recorder's dedup window.
+ const repo = wire(ErrorsRepo, { db: t.deps.db });
+ const seed = (code: string, message: string, ts: string) =>
+ repo.insert({
+ ts,
+ date: ts.slice(0, 10),
+ projectId,
+ agentId: null,
+ sessionId: null,
+ source: "http",
+ kind: "unexpected",
+ code,
+ status: 500,
+ message,
+ });
+ seed("internal", "other side closed", "2026-07-27T01:00:00.000Z");
+ seed("internal", "other side closed", "2026-07-27T02:00:00.000Z");
+ seed("agent_not_found", "no such agent", "2026-07-27T03:00:00.000Z");
+
+ const added = await api.post(`/api/projects/${projectId}/usage/errors/ignores`, {
+ source: "http",
+ code: "internal",
+ note: "engine reconnects by design",
+ });
+ expect(added.status).toBe(201);
+ const body = (await added.json()) as UsageErrorIgnoreAdded;
+ expect(body.hidden).toBe(2);
+ expect(body.rule).toMatchObject({
+ source: "http",
+ code: "internal",
+ messageLike: null,
+ hidden: 2,
+ });
+
+ // The dashboard drops it from what it shows and reports it once under `ignored`: a silenced
+ // class is not invisible twice over.
+ const dashboard = (await (
+ await api.get(`/api/projects/${projectId}/usage?groupBy=date`)
+ ).json()) as UsageResponse;
+ expect(dashboard.errors).toMatchObject({ total: 1, ignored: 2 });
+ expect(dashboard.errors.recent.map((e) => e.code)).toEqual(["agent_not_found"]);
+
+ // The page follows the same axis, and asking for the ignored side reads exactly the covered rows.
+ const shown = (await (
+ await api.get(`/api/projects/${projectId}/usage/errors?offset=0&limit=20`)
+ ).json()) as UsageErrorsPage;
+ expect(shown.total).toBe(1);
+ expect(shown.items.map((e) => e.code)).toEqual(["agent_not_found"]);
+ const ignored = (await (
+ await api.get(`/api/projects/${projectId}/usage/errors?offset=0&limit=20&ignored=1`)
+ ).json()) as UsageErrorsPage;
+ expect(ignored.total).toBe(2);
+ expect(ignored.items.map((e) => e.code)).toEqual(["internal"]);
+
+ // The records were never touched: the rule decides which rows the reads select, not what is stored.
+ expect(errorRows().filter((r) => r.code === "internal")).toHaveLength(2);
+ });
+
+ it("a new rule's hidden figure counts the records it takes off the range it was made from", async () => {
+ const repo = wire(ErrorsRepo, { db: t.deps.db });
+ const seed = (ts: string, agentId: string) =>
+ repo.insert({
+ ts,
+ date: ts.slice(0, 10),
+ projectId,
+ agentId,
+ sessionId: null,
+ source: "http",
+ kind: "unexpected",
+ code: "internal",
+ status: 500,
+ message: "boom",
+ });
+ seed("2026-07-27T01:00:00.000Z", "a1");
+ seed("2026-07-27T02:00:00.000Z", "a2");
+ seed("2026-07-29T01:00:00.000Z", "a1");
+
+ // The range is the panel's own — the one its reads carry — so the number matches the table it
+ // came from; the rule itself is permanent and covers all three. A body that names its own
+ // author is ignored: the owner is the session's, so a rule can never be filed under someone else.
+ const added = (await (
+ await api.post(
+ `/api/projects/${projectId}/usage/errors/ignores?from=2026-07-27&to=2026-07-27&agentId=a1`,
+ { source: "http", code: "internal", createdBy: "someone_else" },
+ )
+ ).json()) as UsageErrorIgnoreAdded;
+ expect(added.hidden).toBe(1);
+ expect(added.rule.hidden).toBe(3);
+ expect(added.rule).toMatchObject({ createdBy: "err_user", note: null });
+ });
+
+ it("ignoring the same class twice is refused, and unignoring puts the rows back", async () => {
+ const repo = wire(ErrorsRepo, { db: t.deps.db });
+ repo.insert({
+ ts: "2026-07-27T01:00:00.000Z",
+ date: "2026-07-27",
+ projectId,
+ agentId: null,
+ sessionId: null,
+ source: "http",
+ kind: "unexpected",
+ code: "internal",
+ status: 500,
+ message: "boom",
+ });
+ const write = { source: "http", code: "internal" };
+ // The refusals below are recorded by app.onError like any other, so the seeded row is read
+ // back by code rather than by counting the table.
+ const visible = async () =>
+ (
+ (await (
+ await api.get(`/api/projects/${projectId}/usage/errors?offset=0&limit=20`)
+ ).json()) as UsageErrorsPage
+ ).items
+ .map((e) => e.code)
+ .filter((code) => code === "internal");
+
+ const first = await api.post(`/api/projects/${projectId}/usage/errors/ignores`, write);
+ expect(first.status).toBe(201);
+ const ruleId = ((await first.json()) as UsageErrorIgnoreAdded).rule.id;
+ expect(await visible()).toEqual([]);
+
+ // The same (source, code, fragment) is one rule: a second row covering the same records would
+ // only say the same thing twice.
+ const again = await api.post(`/api/projects/${projectId}/usage/errors/ignores`, write);
+ expect(again.status).toBe(409);
+ expect(((await again.json()) as { error: { code: string } }).error.code).toBe(
+ "ignore_rule_exists",
+ );
+
+ const listed = (await (
+ await api.get(`/api/projects/${projectId}/usage/errors/ignores`)
+ ).json()) as UsageErrorIgnores;
+ expect(listed.rules.map((r) => r.id)).toEqual([ruleId]);
+ expect(listed.rules[0]!.hidden).toBe(1);
+
+ const removed = await api.delete(`/api/projects/${projectId}/usage/errors/ignores/${ruleId}`);
+ expect(await removed.json()).toEqual({ removed: true });
+ // Nothing was ever deleted, so removing the rule is the whole of the undo.
+ expect(await visible()).toEqual(["internal"]);
+
+ // A rule this Project does not have is a 404, not a silent success.
+ expect(
+ (await api.delete(`/api/projects/${projectId}/usage/errors/ignores/${ruleId}`)).status,
+ ).toBe(404);
+ expect(
+ (await api.delete(`/api/projects/${projectId}/usage/errors/ignores/not-a-number`)).status,
+ ).toBe(400);
+ });
+
+ it("the default view's clear leaves the ignored rows; standing on the ignored view it takes them", async () => {
+ const repo = wire(ErrorsRepo, { db: t.deps.db });
+ const seed = (code: string, ts: string) =>
+ repo.insert({
+ ts,
+ date: ts.slice(0, 10),
+ projectId,
+ agentId: null,
+ sessionId: null,
+ source: "http",
+ kind: "unexpected",
+ code,
+ status: 500,
+ message: code,
+ });
+ seed("internal", "2026-07-27T01:00:00.000Z");
+ seed("internal", "2026-07-27T02:00:00.000Z");
+ seed("agent_not_found", "2026-07-27T03:00:00.000Z");
+ await api.post(`/api/projects/${projectId}/usage/errors/ignores`, {
+ source: "http",
+ code: "internal",
+ });
+
+ // The button empties the table on screen: the ignored rows are not on it, so they stay.
+ const cleared = await api.delete(
+ `/api/projects/${projectId}/usage/errors?from=2026-07-27&to=2026-07-27`,
+ );
+ expect(await cleared.json()).toEqual({ deleted: 1 });
+ expect(errorRows().filter((r) => r.code === "internal")).toHaveLength(2);
+
+ // Standing on the ignored view, the same button is the one that may take those rows.
+ const clearedIgnored = await api.delete(
+ `/api/projects/${projectId}/usage/errors?from=2026-07-27&to=2026-07-27&ignored=1`,
+ );
+ expect(await clearedIgnored.json()).toEqual({ deleted: 2 });
+ expect(errorRows().filter((r) => r.code === "internal")).toHaveLength(0);
+ });
+
+ it("ignore management is the owner's, like the clear; a member still reads the panel and sees the count", async () => {
+ seedRow({ date: "2026-07-27", code: "internal", kind: "unexpected" });
+ const write = { source: "http", code: "internal" };
+ const member = await provisionUser(t.app, "member_user");
+ expect(member.user.isAdmin).toBe(false);
+ await api.post(`/api/projects/${projectId}/members`, { userId: "member_user" });
+ const memberApi = apiClient(t.app, member.cookie);
+ const outsiderApi = apiClient(t.app, (await provisionUser(t.app, "outsider_user")).cookie);
+ const rulesPath = `/api/projects/${projectId}/usage/errors/ignores`;
+
+ // The owner silences the seeded class; the member then reads its effect as a count, without the
+ // rule list. Read before the refusals below, whose own 403 / 404 are recorded like any error.
+ expect((await api.post(rulesPath, write)).status).toBe(201);
+ const memberView = (await (
+ await memberApi.get(`/api/projects/${projectId}/usage?groupBy=date`)
+ ).json()) as UsageResponse;
+ expect(memberView.errors).toMatchObject({ total: 0, ignored: 1 });
+
+ // Reading the panel is a member's right; managing what it hides is the owner's.
+ expect((await memberApi.get(`/api/projects/${projectId}/usage/errors?offset=0`)).status).toBe(
+ 200,
+ );
+ expect((await memberApi.get(rulesPath)).status).toBe(403);
+ expect((await memberApi.post(rulesPath, write)).status).toBe(403);
+ expect((await memberApi.delete(`${rulesPath}/1`)).status).toBe(403);
+ // A non-member is not told the Project exists, let alone allowed to silence its errors.
+ expect((await outsiderApi.get(rulesPath)).status).toBe(404);
+ expect((await outsiderApi.post(rulesPath, write)).status).toBe(404);
+ expect((await outsiderApi.delete(`${rulesPath}/1`)).status).toBe(404);
+ });
});
describe("HTTP error attribution (only when the requester actually has Project access)", () => {
diff --git a/packages/web/e2e/errors-ignore.spec.mjs b/packages/web/e2e/errors-ignore.spec.mjs
new file mode 100644
index 00000000..c54e8a6a
--- /dev/null
+++ b/packages/web/e2e/errors-ignore.spec.mjs
@@ -0,0 +1,234 @@
+/**
+ * Ignoring a class of errors: the table stops showing it while every record stays in the store.
+ *
+ * The panel's only way to make a noisy class go away used to be 清空 — which deletes rows for
+ * everyone, irreversibly. The ignore rules are the reversible alternative, and the exact claim
+ * they make is "nothing is deleted": these tests drive the row action, the notice it leaves
+ * behind, and the ignored view that manages the rules, and they read the store through the API
+ * on both sides of every step. A regression that quietly deleted the records would still draw
+ * the right table, so only the API reads can tell the two apart.
+ *
+ * The errors are real ones the server recorded itself: the mock rejects the auth prompt with 401
+ * (`unauthorized`, an `unexpected` record), reaching `error_records` through the server's own
+ * recorder. Every assertion below reads numbers out of responses, so a rerun holds.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const P = "password123";
+
+/**
+ * The error table read straight from the API, with `extra` on top (e.g. the ignored side). Read
+ * without a range on purpose: the page's own range is a preset the panel applies, and a read wider
+ * than it can only make the two assertions below stronger — the record is there whatever the range,
+ * and the default side hands back no trace of it.
+ */
+async function readTable(page, projectId, extra = {}) {
+ const u = new URL(`${BASE}/api/projects/${projectId}/usage/errors`);
+ u.searchParams.set("offset", "0");
+ u.searchParams.set("limit", "50");
+ for (const [key, value] of Object.entries(extra)) u.searchParams.set(key, value);
+ const res = await page.request.get(u.toString());
+ expect(res.ok(), `read ${u.toString()}`).toBeTruthy();
+ return await res.json();
+}
+
+/** The owner's rules list, straight from the route the panel reads it through. */
+async function readRules(page, projectId) {
+ const res = await page.request.get(`${BASE}/api/projects/${projectId}/usage/errors/ignores`);
+ expect(res.ok(), "read ignore rules").toBeTruthy();
+ return (await res.json()).rules;
+}
+
+/** Provision the user, point the Project at the mock (a key the mock rejects), open one Session. */
+async function prepare(page, userId) {
+ await provisionAndLogin(page.request, userId, P);
+ const { projects } = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects[0].projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-auth-bad",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+ return { projectId, sessionId: await newSession(page, projectId) };
+}
+
+function newSession(page, projectId) {
+ return page.request
+ .post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {
+ data: { provider: "custom", modelId: "claude-4-8" },
+ })
+ .then(async (res) => {
+ expect(res.ok(), "create session").toBeTruthy();
+ return (await res.json()).session.sessionId;
+ });
+}
+
+/** One failed turn through the API; resolves once the Trace holds its terminal `request_end`. */
+async function failedTurn(page, sessionId, text, code) {
+ const res = await page.request.post(`${BASE}/api/sessions/${sessionId}/tasks`, {
+ data: { input: [{ type: "text", text }] },
+ });
+ expect(res.status(), "start task").toBe(202);
+ await expect
+ .poll(
+ async () => {
+ const { messages } = await (
+ await page.request.get(`${BASE}/api/sessions/${sessionId}/messages`)
+ ).json();
+ return messages.some(
+ (m) => m.payload.type === "request_end" && m.payload.error_code === code,
+ );
+ },
+ { timeout: 30_000 },
+ )
+ .toBe(true);
+}
+
+/** One failed turn on the books, and the record the panel will offer to silence. Read before the
+ * App loads, so the only record so far is this one (the shell's own 403 lands later). */
+async function seedError(page, projectId, sessionId) {
+ await failedTurn(page, sessionId, "auth dead test", "auth");
+ const { items } = await readTable(page, projectId);
+ expect(items.length, "one failed turn is on the books").toBeGreaterThan(0);
+ return items[0];
+}
+
+/** Silences `target`'s class from its own row; returns the write's answer. */
+async function ignoreFromRow(page, target) {
+ const row = page.locator("tbody tr").filter({ hasText: target.code }).first();
+ await expect(row).toBeVisible();
+ await row.getByRole("button", { name: "忽略这类异常", exact: true }).click();
+ const dialog = page.getByRole("dialog");
+ await expect(dialog).toBeVisible();
+ await expect(dialog).toContainText(target.code);
+ const posted = page.waitForResponse(
+ (r) => r.url().includes("/usage/errors/ignores") && r.request().method() === "POST",
+ );
+ await dialog.getByRole("button", { name: "忽略", exact: true }).click();
+ const res = await posted;
+ expect(res.ok(), "ignore the class").toBeTruthy();
+ return await res.json();
+}
+
+test("a row action silences its class, leaves every record in the store, and 撤销 puts it back", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const { projectId, sessionId } = await prepare(page, "ignorerow");
+ const target = await seedError(page, projectId, sessionId);
+
+ await page.goto("/usage");
+ await expect(page.locator("tbody tr").first()).toBeVisible();
+
+ const answer = await ignoreFromRow(page, target);
+
+ // The table loses the class, the notice says how many rows went with it, and the count the
+ // stats report comes from the server rather than from the notice.
+ await expect(row(page, target)).toHaveCount(0);
+ // The same sentence twice: once as the toast that goes on its own, once as the notice that
+ // stays with the way back.
+ await expect(page.getByRole("button", { name: /本次隐藏 \d+ 条记录/ })).toBeVisible();
+ await expect(page.locator("[data-ignore-notice]")).toContainText(
+ /已忽略 .* · 本次隐藏 \d+ 条记录/,
+ );
+ await expect(page.getByRole("button", { name: "撤销", exact: true })).toBeVisible();
+ expect(answer.hidden).toBeGreaterThan(0);
+
+ // Nothing was deleted: the records are exactly where they were, behind the rule. The default
+ // read leaves them out and the ignored side hands them back — the same rows, same ids.
+ const hidden = await readTable(page, projectId, { ignored: "1" });
+ const stillThere = hidden.items.filter((i) => i.code === target.code);
+ expect(stillThere.length, "the ignored read still sees the record").toBeGreaterThan(0);
+ expect(stillThere[0].id).toBe(target.id);
+ const plain = await readTable(page, projectId);
+ expect(plain.items.some((i) => i.code === target.code)).toBe(false);
+
+ // One rule, this class, and it covers records.
+ const [rule] = await readRules(page, projectId);
+ expect(rule).toMatchObject({
+ source: target.source,
+ code: target.code,
+ messageLike: null,
+ });
+ expect(rule.hidden).toBeGreaterThan(0);
+
+ // 撤销 removes the rule itself; every record it covered is back with no write to the store.
+ await page.getByRole("button", { name: "撤销", exact: true }).click();
+ await expect(page.getByText(/^已恢复 .* 的异常$/)).toBeVisible();
+ await expect(row(page, target).first()).toBeVisible();
+ await expect(page.getByRole("button", { name: "撤销", exact: true })).toHaveCount(0);
+ expect(await readRules(page, projectId)).toHaveLength(0);
+ const after = await readTable(page, projectId);
+ expect(after.items.some((i) => i.code === target.code)).toBe(true);
+});
+
+test("the ignored view names the rules, and 取消忽略 re-exposes every record", async ({ page }) => {
+ test.setTimeout(120_000);
+ const { projectId, sessionId } = await prepare(page, "ignoreview");
+ const target = await seedError(page, projectId, sessionId);
+
+ await page.goto("/usage");
+ await expect(page.locator("tbody tr").first()).toBeVisible();
+
+ // The row's dialog offers the narrowing before the rule exists — the fragment is what the row
+ // button alone cannot express. Left blank here: this test is about the whole class.
+ const rowButton = page
+ .locator("tbody tr")
+ .filter({ hasText: target.code })
+ .first()
+ .getByRole("button", { name: "忽略这类异常", exact: true });
+ await rowButton.click();
+ await expect(page.getByRole("dialog").getByLabel("只忽略消息包含以下内容的记录")).toBeVisible();
+ await page.getByRole("dialog").getByRole("button", { name: "取消", exact: true }).click();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+
+ await ignoreFromRow(page, target);
+
+ // A clear still names only what a clear deletes: the records behind the rule are neither
+ // counted nor hidden — the sentence says so rather than leaving them out silently.
+ await page.getByRole("button", { name: "清空", exact: true }).click();
+ const clearDialog = page.getByRole("dialog");
+ await expect(clearDialog).toBeVisible();
+ await expect(clearDialog).toContainText(/另有 \d+ 条已忽略的记录不在此列。/);
+ await clearDialog.getByRole("button", { name: "取消", exact: true }).click();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+
+ // The fourth view is where the rules live, and it reads the other side of them: the rule, what
+ // it covers, and the rows it holds back — which is also what its own 清空 would take.
+ await page.getByRole("button", { name: "已忽略", exact: true }).click();
+ await expect(page.locator("[data-ignore-rule]")).toHaveCount(1);
+ const rule = page.locator("[data-ignore-rule]").first();
+ await expect(rule).toContainText(target.code);
+ await expect(rule).toContainText(/已隐藏 \d+ 条/);
+ await expect(page.getByText("被忽略的记录仍在库里,只是不再出现在其他视图里。")).toBeVisible();
+ await expect(page.locator("tbody tr").filter({ hasText: target.code }).first()).toBeVisible();
+
+ // 取消忽略 is the same act as 撤销, from the list instead of the notice: rules gone, rows back.
+ await rule.getByRole("button", { name: "取消忽略", exact: true }).click();
+ await expect(page.getByText(/^已恢复 .* 的异常$/)).toBeVisible();
+ await expect(page.getByText("还没有忽略规则。")).toBeVisible();
+ expect(await readRules(page, projectId)).toHaveLength(0);
+
+ await page.getByRole("button", { name: "全部", exact: true }).click();
+ await expect(page.locator("tbody tr").filter({ hasText: target.code }).first()).toBeVisible();
+ const back = await readTable(page, projectId);
+ expect(back.items.some((i) => i.code === target.code)).toBe(true);
+});
+
+/** The table row standing for a record: the panel folds repeats of a class into one row. */
+function row(page, target) {
+ return page.locator("tbody tr").filter({ hasText: target.code });
+}
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index fa6a3111..c795281f 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -248,6 +248,9 @@ import type {
DesktopTrayPatch,
DesktopTrayStatusResponse,
HookArchiveInstallRequest,
+ UsageErrorIgnoreAdded,
+ UsageErrorIgnoreWrite,
+ UsageErrorIgnores,
UsageErrorKind,
UsageErrorsClearResponse,
UsageErrorsPage,
@@ -1531,6 +1534,8 @@ export const getUsageErrors = (
agentId?: string;
/** Narrow to one category; the cost-center badge asks for `unexpected` with `limit: 1`. */
kind?: UsageErrorKind;
+ /** Read the other side of the Project's ignore rules: the records a rule covers, which every other read leaves out. */
+ ignored?: boolean;
},
) =>
apiFetch<UsageErrorsPage>(`/api/projects/${encodeURIComponent(projectId)}/usage/errors`, {
@@ -1543,6 +1548,7 @@ export const getUsageErrors = (
toTs: params.toTs,
agentId: params.agentId,
kind: params.kind,
+ ignored: params.ignored === true ? "1" : undefined,
utcOffsetMinutes: viewerUtcOffsetMinutes(),
},
});
@@ -1567,6 +1573,8 @@ export const clearUsageErrors = (
agentId?: string;
/** Narrow to one category; the panel sends whatever its table is showing. */
kind?: UsageErrorKind;
+ /** The ignore side the table is showing: `true` clears the rows a rule covers, absent the rows no rule covers. */
+ ignored?: boolean;
},
) =>
apiFetch<UsageErrorsClearResponse>(
@@ -1581,10 +1589,58 @@ export const clearUsageErrors = (
until: params.until,
agentId: params.agentId,
kind: params.kind,
+ ignored: params.ignored === true ? "1" : undefined,
},
},
);
+/**
+ * The Project's ignore rules — the error classes nothing in the panel's default view shows, each
+ * with how many records it covers and when the newest of them was. Owner only: the panel reports
+ * the count to everyone (the dashboard's `errors.ignored`), but managing the rules is the same
+ * kind of act as clearing, so it draws the same line.
+ */
+export const getUsageErrorIgnores = (projectId: string) =>
+ apiFetch<UsageErrorIgnores>(
+ `/api/projects/${encodeURIComponent(projectId)}/usage/errors/ignores`,
+ );
+
+/**
+ * Silences one class of errors. Nothing is deleted — the rule only decides which records the reads
+ * select — so this is undoable, and the answer says how many records it covers in the range the
+ * caller was looking at, which is what the caller reports having just hidden. A class the Project
+ * already ignores is a 409.
+ *
+ * The range rides along because the number is scoped to it: the same range the table on screen
+ * was read with, so "隐藏 349 条" names the rows that just left it.
+ */
+export const ignoreUsageErrors = (
+ projectId: string,
+ body: UsageErrorIgnoreWrite,
+ params: { from?: string; to?: string; fromTs?: string; toTs?: string; agentId?: string } = {},
+) =>
+ apiFetch<UsageErrorIgnoreAdded>(
+ `/api/projects/${encodeURIComponent(projectId)}/usage/errors/ignores`,
+ {
+ method: "POST",
+ body,
+ query: {
+ from: params.from,
+ to: params.to,
+ fromTs: params.fromTs,
+ toTs: params.toTs,
+ agentId: params.agentId,
+ },
+ },
+ );
+
+/** Removes one rule, re-exposing every record it covered — the whole of the undo, since nothing was deleted. */
+export const unignoreUsageErrors = (projectId: string, id: number) =>
+ apiFetch<{ removed: boolean }>(
+ `/api/projects/${encodeURIComponent(projectId)}/usage/errors/ignores/${String(id)}`,
+ { method: "DELETE" },
+ );
+
/**
* Lifetime Token total per Model, unfiltered. The models page shows each card what it has
* spent; it is a separate request from the model list so a stats failure costs the figure and
diff --git a/packages/web/src/features/usage/errors-panel.tsx b/packages/web/src/features/usage/errors-panel.tsx
index b61f2260..ba307f60 100644
--- a/packages/web/src/features/usage/errors-panel.tsx
+++ b/packages/web/src/features/usage/errors-panel.tsx
@@ -14,11 +14,14 @@
* The outer frame is provided by the caller's ChartCard (full width, below the four business charts).
*/
import { useEffect, useMemo, useState } from "react";
-import type { UsageErrorItem, UsageErrors } from "@adelie/server/api";
+import type { UsageErrorIgnoreRule, UsageErrorItem, UsageErrors } from "@adelie/server/api";
import {
Badge,
ConfirmModal,
CopyButton,
+ GlyphIcon,
+ ICONS,
+ Input,
Pager,
Segmented,
toastError,
@@ -34,8 +37,14 @@ 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 table's own control: one of the two categories, both, or the ignored view. The last is not a
+ * category — it is the other side of the ignore rules, which is why the table's kinds are still
+ * both drawn there (see activeFilters) — but it is the same kind of choice: which slice of the
+ * filtered set the table below shows, and therefore what its pager, its row count and the clear
+ * act on.
+ */
+type ErrorKindFilter = ErrorKindKey | "all" | "ignored";
/** The date/agent filter the panel reads through, and that a clear deletes through. */
export interface ErrorsFilters {
@@ -52,6 +61,12 @@ export interface ErrorsFilters {
* table they never saw.
*/
kind?: ErrorKindKey;
+ /**
+ * The ignored view: true reads the records the Project's rules cover, which every other view
+ * leaves out. Merged in here like `kind`, and for the same reason — the clear takes what the
+ * table shows, and on this view that is exactly the ignored rows.
+ */
+ ignored?: boolean;
}
/** The quick range presets the clear confirmation names by name; a custom range is named by its dates. */
@@ -80,9 +95,17 @@ export function errorsClearScopeText(
preset !== undefined
? S.usage.errorsClearRangePreset(preset)
: S.usage.errorsClearRangeCustom(filters.from ?? "", filters.to ?? "");
- const kind = filters.kind !== undefined ? kindLabel(filters.kind) : undefined;
const agent =
filters.agentId !== undefined && filters.agentId !== "" ? filters.agentId : undefined;
+ // The ignored view reads its own set, and what it keeps is every record no rule covers — not
+ // "the other category". Naming it with the category sentence would describe the wrong delete, so
+ // it has its own.
+ if (filters.ignored === true) {
+ return agent !== undefined
+ ? S.usage.errorsClearScopeIgnoredAgent(count, range, agent)
+ : S.usage.errorsClearScopeIgnored(count, range);
+ }
+ const kind = filters.kind !== undefined ? kindLabel(filters.kind) : undefined;
if (kind !== undefined && agent !== undefined) {
return S.usage.errorsClearScopeKindAgent(count, range, kind, agent);
}
@@ -91,6 +114,22 @@ export function errorsClearScopeText(
return S.usage.errorsClearScope(count, range);
}
+/**
+ * The line a clear's confirmation adds when the range holds records an ignore rule is keeping off
+ * the table — null when there is none to add. Without it, the sentence above reads as the whole
+ * range while the ignored records are neither counted nor shown; on the ignored view those records
+ * ARE that sentence's subject, so adding this would count them twice. Pure and exported for the
+ * reason `errorsClearScopeText` is: this package's vitest runs in `node`, so an opened dialog is
+ * not something a test can inspect.
+ */
+export function errorsClearKeepsIgnoredText(
+ ignored: number,
+ filters: ErrorsFilters,
+): string | null {
+ if (ignored <= 0 || filters.ignored === true) return null;
+ return S.usage.errorsClearKeepsIgnored(ignored);
+}
+
/**
* Whether the filter on screen is one a clear may be offered for.
*
@@ -148,6 +187,91 @@ export function errorCopyText(e: UsageErrorItem): string {
return `${head.join(" · ")}\n${e.message}`;
}
+/**
+ * One ignore rule as the panel words it: the bracketed class the table's own column shows, plus
+ * the fragment when the rule covers only part of that class — because a rule that says
+ * `[llm] llm_retried` while in fact covering only its socket drops would be claiming more than it
+ * does, and "why is this particular record still here" is the question the list exists to answer.
+ *
+ * Pure and exported for the same reason the two text builders beside it are: this package's vitest
+ * runs in `node`, where a rendered list is readable but a click is not.
+ */
+export function ignoreRuleText(rule: UsageErrorIgnoreRule): string {
+ const label = sourceCode(rule.source, rule.code);
+ return rule.messageLike !== null
+ ? `${label} · ${S.usage.errorsIgnoreRuleFragment(rule.messageLike)}`
+ : label;
+}
+
+/**
+ * The ignored view's own explanation: the rules that put those rows there, each with what it covers
+ * and how new the newest of it is, and the way back out. Drawn above the table because it is the
+ * answer to the question that table raises ("why is this hidden?").
+ *
+ * A component of its own rather than a block inside the panel for the reason the text builders are
+ * functions: this package's vitest runs in `node`, the panel fetches the rules in an effect, and
+ * `renderToStaticMarkup` never runs effects — so a list drawn inline could only ever be asserted as
+ * "no rules yet". Exported, it is renderable with rules in hand.
+ */
+export function IgnoreRulesBox({
+ rules,
+ onUnignore,
+}: {
+ /** null while the list is not read yet (never fetched, or a read that failed) — drawn as the empty state, which is also what a Project with no rules shows. */
+ rules: UsageErrorIgnoreRule[] | null;
+ onUnignore: (rule: UsageErrorIgnoreRule) => void;
+}) {
+ return (
+ <div className="mt-3 rounded-lg border border-gray-200 px-3 py-2 text-xs dark:border-gray-800">
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="font-medium text-gray-700 dark:text-gray-300">
+ {S.usage.errorsIgnoreRules}
+ </span>
+ <span className="text-gray-400 dark:text-gray-500">{S.usage.errorsIgnoreNotice}</span>
+ </div>
+ {rules === null || rules.length === 0 ? (
+ <p className="mt-1 text-gray-400 dark:text-gray-500">{S.usage.errorsIgnoreRuleNone}</p>
+ ) : (
+ <ul className="mt-1 space-y-1">
+ {rules.map((rule) => (
+ <li
+ key={rule.id}
+ className="flex flex-wrap items-baseline gap-x-3 gap-y-1"
+ data-ignore-rule={rule.id}
+ >
+ <span className="break-words font-mono text-gray-500 dark:text-gray-400">
+ {ignoreRuleText(rule)}
+ </span>
+ <span className="text-gray-400 dark:text-gray-500">
+ {rule.hidden > 0
+ ? S.usage.errorsIgnoreRuleHidden(rule.hidden)
+ : S.usage.errorsIgnoreRuleHiddenNone}
+ </span>
+ {rule.lastTs !== null && (
+ <span className="text-gray-400 dark:text-gray-500">
+ {S.usage.errorsIgnoreRuleLast(formatDateTime(rule.lastTs))}
+ </span>
+ )}
+ <button
+ type="button"
+ onClick={() => onUnignore(rule)}
+ className="rounded-md border border-gray-200 px-2 py-0.5 text-gray-500 transition-colors duration-150 hover:border-gray-300 hover:text-gray-700 dark:border-gray-800 dark:hover:border-gray-700 dark:hover:text-gray-300"
+ >
+ {S.usage.errorsUnignore}
+ </button>
+ {/* The owner's own words for why it is silenced, when they wrote any. Muted, and last:
+ it explains a rule that is already fully described without it. */}
+ {rule.note !== null && (
+ <span className="text-gray-400 dark:text-gray-500">{rule.note}</span>
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
+
/** A single small stat: name + value, one row side by side (not turned into a chart). */
function Stat({
label,
@@ -209,6 +333,7 @@ export function ErrorsPanel({
filters,
preset,
canClear,
+ canIgnore,
onReload,
}: {
errors: UsageErrors;
@@ -226,6 +351,13 @@ export function ErrorsPanel({
* from offering an action that can only end in a 403.
*/
canClear: boolean;
+ /**
+ * Whether this viewer may manage the ignore rules (Project owner, the same line the clear
+ * draws). A member still sees the ignored view and the count in the stats — what a rule hides
+ * must never be hidden from them — but not the rules themselves, which are the management
+ * surface.
+ */
+ canIgnore: boolean;
/**
* Reload the dashboard — the stats above the table are the caller's data, not this panel's.
* Called after a clear, and when the confirmation opens: the sentence names a count read at
@@ -234,7 +366,7 @@ export function ErrorsPanel({
*/
onReload: () => void;
}) {
- const { total, unexpected, topCode, recent, rows } = errors;
+ const { total, unexpected, ignored, topCode, recent, rows } = 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.)
@@ -255,9 +387,15 @@ export function ErrorsPanel({
// 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).
+ // control when one is chosen (see ErrorsFilters.kind / .ignored). The ignored view is the other
+ // side of the same axis and covers both categories — a rule does not care which one it hides.
const activeFilters = useMemo<ErrorsFilters>(
- () => (kindFilter === "all" ? filters : { ...filters, kind: kindFilter }),
+ () =>
+ kindFilter === "all"
+ ? filters
+ : kindFilter === "ignored"
+ ? { ...filters, ignored: true }
+ : { ...filters, kind: kindFilter },
[filters, kindFilter],
);
// A new dashboard response invalidates the offsets being paged through, so paging goes back to
@@ -368,6 +506,100 @@ export function ErrorsPanel({
setClearing(false);
}
};
+ // The Project's ignore rules, read only on the view that manages them: the other views never draw
+ // them, and a request whose answer is not on screen is a request not worth making. A member never
+ // asks — the route is the owner's, and the ignored rows and the count are theirs to see anyway.
+ const [rules, setRules] = useState<UsageErrorIgnoreRule[] | null>(null);
+ // Bumped after a rule is added or removed, so the list above re-reads without a second state
+ // machine: the version is the effect's dependency, and the effect is what fetches.
+ const [rulesVersion, setRulesVersion] = useState(0);
+ // The class the dialog is about to silence, with the two fields it may narrow by.
+ const [ignoreTarget, setIgnoreTarget] = useState<UsageErrorItem | null>(null);
+ const [ignoreFragment, setIgnoreFragment] = useState("");
+ const [ignoring, setIgnoring] = useState(false);
+ // The rule just made, kept so the panel can offer the undo in place: the row it stood for is
+ // already gone from the table below, so a notice floating elsewhere would point at nothing. The
+ // count is the answer the write carried, not the stats above — those are still the dashboard's
+ // older snapshot until the reload lands.
+ const [justIgnored, setJustIgnored] = useState<{
+ id: number;
+ label: string;
+ hidden: number;
+ } | null>(null);
+
+ useEffect(() => {
+ if (kindFilter !== "ignored" || !canIgnore) {
+ setRules(null);
+ return;
+ }
+ let cancelled = false;
+ api
+ .getUsageErrorIgnores(projectId)
+ .then((res) => {
+ if (!cancelled) setRules(res.rules);
+ })
+ .catch((e: unknown) => {
+ // Leave the list out rather than blanking it under an error: the table below is the
+ // reader's actual answer, and the rules are the explanation of it.
+ if (!cancelled) {
+ setRules(null);
+ toastError(apiErrorText(e));
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId, kindFilter, canIgnore, rulesVersion]);
+
+ /**
+ * Silences a class. What the dialog adds over the row is the fragment: the same source · code
+ * often carries both the noise and the one line worth seeing (`llm_retried` drops its socket all
+ * afternoon and once returns a 500), so the narrowing has to be reachable from the row it is
+ * about, not only from an API.
+ *
+ * The range rides along so the answer can say how many records just left the screen, and the
+ * notice stays until it is undone or the panel is remounted — the action is reversible, so this
+ * is where the caller's "撤销" lives rather than in a confirmation it does not need.
+ */
+ const runIgnore = async () => {
+ if (ignoreTarget === null) return;
+ const { source, code } = ignoreTarget;
+ setIgnoring(true);
+ try {
+ const added = await api.ignoreUsageErrors(
+ projectId,
+ { source, code, messageLike: ignoreFragment },
+ activeFilters,
+ );
+ const label = sourceCode(source, code);
+ setIgnoreTarget(null);
+ setIgnoreFragment("");
+ setJustIgnored({ id: added.rule.id, label, hidden: added.hidden });
+ setRulesVersion((v) => v + 1);
+ toastSuccess(S.usage.errorsIgnoreDone(label, added.hidden));
+ // The stats above the table are the dashboard's own numbers, so the whole response is
+ // refetched: the ignored count and the table's own first page both move with this.
+ onReload();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setIgnoring(false);
+ }
+ };
+
+ /** Removes a rule, whichever side of the panel asked — the rule list or the notice left by the row. */
+ const unignore = async (id: number, label: string) => {
+ try {
+ await api.unignoreUsageErrors(projectId, id);
+ setJustIgnored((current) => (current?.id === id ? null : current));
+ setRulesVersion((v) => v + 1);
+ toastSuccess(S.usage.errorsUnignoreDone(label));
+ onReload();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ }
+ };
+
// Message rows expanded to their full text (index into the current page); one line each by default.
const [expanded, setExpanded] = useState<ReadonlySet<number>>(new Set());
useEffect(() => setExpanded(new Set()), [items]);
@@ -391,6 +623,10 @@ export function ErrorsPanel({
muted={unexpected === 0}
/>
<Stat label={S.usage.errorsExpected} value={String(total - unexpected)} muted />
+ {/* The other side of the same range: what the rules are holding back. Drawn always, so the
+ numbers above are never read as the whole truth — a zero above with a number here says
+ "nothing loud is left", not "nothing is happening". */}
+ <Stat label={S.usage.errorsIgnored} value={String(ignored)} muted />
{topCode && (
<Stat
label={S.usage.errorsTopCode}
@@ -399,27 +635,71 @@ 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. */}
+ {/* The table's own filter: one category, both, or the ignored view. 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 view the reader came from. */}
<div className="mt-3 flex justify-end">
- <div className="w-56">
+ <div className="w-72">
<Segmented
options={[
{ value: "all", label: S.usage.errorsFilterAll },
{ value: "unexpected", label: S.usage.errorsUnexpected },
{ value: "expected", label: S.usage.errorsExpected },
+ { value: "ignored", label: S.usage.errorsIgnored },
]}
value={kindFilter}
onChange={setKindFilter}
+ // Four ways to slice the table, so four chips on one row: the default of three would
+ // wrap the ignored view onto a line of its own and read as a footnote to the others.
+ cols={4}
/>
</div>
</div>
+ {/* The ignored view's own explanation (see IgnoreRulesBox), drawn only for the owner: managing
+ the rules is the owner's, exactly as clearing is. Every other reader still gets the view
+ and the count in the stats — what a rule hides is never hidden from them. */}
+ {kindFilter === "ignored" && canIgnore && (
+ <IgnoreRulesBox
+ rules={rules}
+ onUnignore={(rule) => void unignore(rule.id, ignoreRuleText(rule))}
+ />
+ )}
+
+ {/* What the last row action did, with the way back. The row it names is already gone from the
+ table below, so the undo has to stand where the table is — a toast would have dismissed
+ itself before the reader decided they wanted it back. */}
+ {justIgnored !== null && (
+ <div
+ data-ignore-notice={justIgnored.id}
+ className="mt-2 flex flex-wrap items-baseline gap-x-3 gap-y-1 rounded-md bg-surface-muted px-2.5 py-1.5 text-xs text-gray-500 dark:text-gray-400"
+ >
+ <span className="break-words">
+ {S.usage.errorsIgnoreDone(justIgnored.label, justIgnored.hidden)}
+ </span>
+ <button
+ type="button"
+ onClick={() => void unignore(justIgnored.id, justIgnored.label)}
+ className="inline-flex items-center gap-1 rounded-sm text-fg-subtle transition-colors duration-150 hover:text-fg-muted"
+ >
+ <GlyphIcon d={ICONS.undo} size={12} />
+ {S.usage.errorsIgnoreUndo}
+ </button>
+ </div>
+ )}
+
{/* Recent-errors table */}
{items.length === 0 ? (
- <Empty text={kindFilter === "all" ? S.usage.errorsEmpty : S.usage.errorsEmptyKind} />
+ <Empty
+ text={
+ kindFilter === "all"
+ ? S.usage.errorsEmpty
+ : kindFilter === "ignored"
+ ? S.usage.errorsEmptyIgnored
+ : S.usage.errorsEmptyKind
+ }
+ />
) : (
<div className="mt-2.5 overflow-x-auto overflow-y-clip border-t border-gray-200 dark:border-gray-800">
{/* The columns beside the message are fixed-width and the message column takes the rest, so
@@ -427,9 +707,10 @@ export function ErrorsPanel({
zero width and pushes the others past the edge. `min-w` states that floor, and
this box scrolls it sideways when the viewport is narrower — the page itself must
never scroll sideways (styles.css). `overflow-y-clip` keeps browsers from reserving
- a vertical scrollbar gutter beside the horizontal one. 752 = the old floor plus the
- copy column's 32, so that column costs the message column nothing. */}
- <table className="w-full min-w-[752px] table-fixed text-xs">
+ a vertical scrollbar gutter beside the horizontal one. 784 = the old floor plus the
+ copy column's 32 and the ignore column's 32, so those two cost the message column
+ nothing. */}
+ <table className="w-full min-w-[784px] table-fixed text-xs">
<thead className="text-left text-gray-400 dark:text-gray-500">
<tr>
<Th className="w-32">{S.common.time}</Th>
@@ -439,8 +720,10 @@ export function ErrorsPanel({
<Th className="w-72">{S.usage.errorsColCode}</Th>
<Th className="w-20">{S.usage.errorsColKind}</Th>
<Th>{S.usage.errorsColMessage}</Th>
- {/* The copy column: the glyph names its action itself, so the header stays
- empty rather than repeating it for a screen reader twice per row. */}
+ {/* The two action columns: the copy glyph names its action itself, and so does the
+ ignore one, so both headers stay empty rather than repeating them for a screen
+ reader. */}
+ <Th className="w-8" />
<Th className="w-8" />
</tr>
</thead>
@@ -507,6 +790,27 @@ export function ErrorsPanel({
size="sm"
/>
</td>
+ {/* Silence this class: the row's own source · code, which is what the rule
+ covers. Offered to the owner only (the route is theirs) and only where
+ silencing something makes sense — on the ignored view every row already is.
+ The glyph's tooltip names the action, and the dialog that follows names the
+ consequence and lets it be narrowed to a message fragment. */}
+ <td className="py-1.5 pl-2 align-top">
+ {canIgnore && kindFilter !== "ignored" && (
+ <button
+ type="button"
+ aria-label={S.usage.errorsIgnoreAction}
+ data-tooltip={S.usage.errorsIgnoreAction}
+ onClick={() => {
+ setIgnoreTarget(e);
+ setIgnoreFragment("");
+ }}
+ className="inline-flex size-5 items-center justify-center rounded-sm text-fg-subtle transition-colors duration-150 hover:bg-surface-muted hover:text-fg-muted"
+ >
+ <GlyphIcon d={ICONS.eyeOff} />
+ </button>
+ )}
+ </td>
</tr>
);
})}
@@ -574,11 +878,54 @@ export function ErrorsPanel({
{errorsClearScopeText(activeFilters, preset, confirmTarget.total)}
</p>
)}
+ {/* The sentence above counts what the table showed, which on every view but this one
+ leaves the ignored records out — so the reader is told they exist rather than left to
+ read "N records" as the whole range. On the ignored view those rows ARE the sentence's
+ subject, and this would be counting them twice (see errorsClearKeepsIgnoredText). */}
+ {errorsClearKeepsIgnoredText(ignored, activeFilters) !== null && (
+ <p className="text-xs text-gray-500 dark:text-gray-400">
+ {errorsClearKeepsIgnoredText(ignored, activeFilters)}
+ </p>
+ )}
<p className="text-xs text-gray-500 dark:text-gray-400">
{S.usage.errorsClearIrreversible}
</p>
</div>
</ConfirmModal>
+
+ {/* Silencing a class. No danger tone and no "cannot be undone" here, because neither is true:
+ nothing is deleted, and the notice this leaves behind puts it back in one click. What the
+ card adds over the row button is the narrowing — the fragment — which is the difference
+ between hiding a class and hiding a class's noise. */}
+ <ConfirmModal
+ open={ignoreTarget !== null}
+ tone="primary"
+ glyph={ICONS.eyeOff}
+ title={S.usage.errorsIgnoreAction}
+ confirmLabel={S.usage.errorsIgnore}
+ cancelLabel={S.common.cancel}
+ busy={ignoring}
+ onClose={() => {
+ setIgnoreTarget(null);
+ setIgnoreFragment("");
+ }}
+ onConfirm={() => void runIgnore()}
+ >
+ <div className="space-y-2 text-sm text-gray-700 dark:text-gray-300">
+ {ignoreTarget !== null && (
+ <p className="break-words font-mono text-gray-500 dark:text-gray-400">
+ {sourceCode(ignoreTarget.source, ignoreTarget.code)}
+ </p>
+ )}
+ <Input
+ label={S.usage.errorsIgnoreFragment}
+ hint={S.usage.errorsIgnoreFragmentHint}
+ value={ignoreFragment}
+ onChange={(e) => setIgnoreFragment(e.target.value)}
+ maxLength={200}
+ />
+ </div>
+ </ConfirmModal>
</div>
);
}
diff --git a/packages/web/src/features/usage/usage-page.tsx b/packages/web/src/features/usage/usage-page.tsx
index fac37914..76fed12f 100644
--- a/packages/web/src/features/usage/usage-page.tsx
+++ b/packages/web/src/features/usage/usage-page.tsx
@@ -491,6 +491,9 @@ export function UsagePage() {
// 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"}
+ // The ignore rules draw the same line, and for the same reason: a rule changes what
+ // everyone reading this Project sees.
+ canIgnore={currentProject?.role === "owner"}
// Reload the table, its stats and its notice: after clearing the log, and when
// the clear confirmation opens (so the panel behind it agrees with its sentence).
onReload={() => {
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 76a68b5d..144d8fba 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -4680,6 +4680,41 @@ export const en: Strings = {
errorsClearIrreversible: "This cannot be undone.",
errorsClearDone: (count: number): string =>
`Deleted ${count} error record${count === 1 ? "" : "s"}`,
+ /**
+ * Ignoring: the fourth view of the table, the row action that silences a class, and the rule
+ * list that says what is being held back. The records are never deleted — which is why this
+ * action takes no confirmation where clearing does, and why the notice below says so outright.
+ */
+ errorsIgnored: "Ignored",
+ errorsEmptyIgnored: "No ignored errors",
+ errorsIgnoreAction: "Ignore this kind",
+ /** The dialog's confirm button: the action's own verb. */
+ errorsIgnore: "Ignore",
+ errorsIgnoreFragment: "Only ignore records whose message contains",
+ errorsIgnoreFragmentHint: "Leave empty to ignore every record with this source and code.",
+ errorsIgnoreRules: "Ignore rules",
+ errorsIgnoreRuleNone: "No ignore rules yet.",
+ /** A rule narrowed to a message fragment says so; a whole-class rule says nothing extra. */
+ errorsIgnoreRuleFragment: (fragment: string): string => `message contains "${fragment}"`,
+ errorsIgnoreRuleHidden: (count: number): string =>
+ `${count} record${count === 1 ? "" : "s"} hidden`,
+ errorsIgnoreRuleHiddenNone: "No records hidden yet",
+ errorsIgnoreRuleLast: (time: string): string => `newest ${time}`,
+ errorsUnignore: "Stop ignoring",
+ errorsIgnoreNotice: "The records are still stored — they are only left out of the other views.",
+ errorsUnignoreDone: (label: string): string => `Showing ${label} again`,
+ /** After ignoring: which class went, and how many records the range on screen just lost. */
+ errorsIgnoreDone: (label: string, count: number): string =>
+ `Ignoring ${label} · hid ${count} record${count === 1 ? "" : "s"}`,
+ errorsIgnoreUndo: "Undo",
+ /** The clear sentence on the ignored view: what goes is that view's own table, and nothing else is touched. */
+ errorsClearScopeIgnored: (count: number, range: string): string =>
+ `Deletes this Project's ${count} ignored error record${count === 1 ? "" : "s"} ${range}. Records that are not ignored and records outside that range are kept.`,
+ errorsClearScopeIgnoredAgent: (count: number, range: string, agentId: string): string =>
+ `Deletes this Project's ${count} ignored error record${count === 1 ? "" : "s"} for agent ${agentId} ${range}. Records that are not ignored, other agents and records outside that range are kept.`,
+ /** Shown in the clear confirmation when the range holds ignored records: the sentence above never counts them. */
+ errorsClearKeepsIgnored: (count: number): string =>
+ `${count} ignored record${count === 1 ? "" : "s"} is not included.`,
},
/** The Trace panel's own view of a Trace file (trace-file-view / timeline-chart); the standalone browsing page these once also served is gone. */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 663f057a..dbf9ba6c 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -4741,6 +4741,39 @@ export const zh = {
`将删除本项目中 Agent「${agentId}」${range}的 ${count} 条「${kind}」错误记录,另一类、其他 Agent 与其余时间段的记录保留。`,
errorsClearIrreversible: "此操作不可恢复。",
errorsClearDone: (count: number): string => `已删除 ${count} 条错误记录`,
+ /**
+ * Ignoring: the fourth view of the table, the row action that silences a class, and the rule
+ * list that says what is being held back. The records are never deleted — which is why this
+ * action takes no confirmation where clearing does, and why the notice below says so outright.
+ */
+ errorsIgnored: "已忽略",
+ errorsEmptyIgnored: "暂无被忽略的异常",
+ errorsIgnoreAction: "忽略这类异常",
+ /** The dialog's confirm button: the action's own verb. */
+ errorsIgnore: "忽略",
+ errorsIgnoreFragment: "只忽略消息包含以下内容的记录",
+ errorsIgnoreFragmentHint: "留空则忽略这一来源与错误码下的全部记录。",
+ errorsIgnoreRules: "忽略规则",
+ errorsIgnoreRuleNone: "还没有忽略规则。",
+ /** A rule narrowed to a message fragment says so; a whole-class rule says nothing extra. */
+ errorsIgnoreRuleFragment: (fragment: string): string => `消息含「${fragment}」`,
+ errorsIgnoreRuleHidden: (count: number): string => `已隐藏 ${count} 条`,
+ errorsIgnoreRuleHiddenNone: "尚未隐藏任何记录",
+ errorsIgnoreRuleLast: (time: string): string => `最近一条 ${time}`,
+ errorsUnignore: "取消忽略",
+ errorsIgnoreNotice: "被忽略的记录仍在库里,只是不再出现在其他视图里。",
+ errorsUnignoreDone: (label: string): string => `已恢复 ${label} 的异常`,
+ /** After ignoring: which class went, and how many records the range on screen just lost. */
+ errorsIgnoreDone: (label: string, count: number): string =>
+ `已忽略 ${label} · 本次隐藏 ${count} 条记录`,
+ errorsIgnoreUndo: "撤销",
+ /** The clear sentence on the ignored view: what goes is that view's own table, and nothing else is touched. */
+ errorsClearScopeIgnored: (count: number, range: string): string =>
+ `将删除本项目 ${range}的 ${count} 条已忽略的错误记录,未被忽略的记录与其余时间段的记录保留。`,
+ errorsClearScopeIgnoredAgent: (count: number, range: string, agentId: string): string =>
+ `将删除本项目中 Agent「${agentId}」${range}的 ${count} 条已忽略的错误记录,未被忽略的记录、其他 Agent 与其余时间段的记录保留。`,
+ /** Shown in the clear confirmation when the range holds ignored records: the sentence above never counts them. */
+ errorsClearKeepsIgnored: (count: number): string => `另有 ${count} 条已忽略的记录不在此列。`,
},
/** The Trace panel's own view of a Trace file (trace-file-view / timeline-chart); the standalone browsing page these once also served is gone. */
diff --git a/packages/web/test/errors-panel.test.ts b/packages/web/test/errors-panel.test.ts
index 7c412240..60a9ada4 100644
--- a/packages/web/test/errors-panel.test.ts
+++ b/packages/web/test/errors-panel.test.ts
@@ -8,17 +8,21 @@
* The other is the confirmation's wording, which is the whole safety mechanism here: the delete
* is scoped to the filter on screen, so a dialog that named the Project's whole history, or
* only the visible page, would send someone into an irreversible action describing the wrong
- * set. That sentence is a pure function for exactly this reason — this package's vitest runs in
- * `node`, deliberately, so an opened dialog is not something a test can read.
+ * set — as would one that left out the records an ignore rule is holding back. Those sentences
+ * are pure functions for exactly this reason — this package's vitest runs in `node`,
+ * deliberately, so an opened dialog is not something a test can read.
*/
import { afterEach, describe, expect, it } from "vitest";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
-import type { UsageErrorItem, UsageErrors } from "@adelie/server/api";
+import type { UsageErrorIgnoreRule, UsageErrorItem, UsageErrors } from "@adelie/server/api";
import {
ErrorsPanel,
+ IgnoreRulesBox,
errorCopyText,
+ errorsClearKeepsIgnoredText,
errorsClearScopeText,
+ ignoreRuleText,
} from "../src/features/usage/errors-panel";
import type { ErrorsFilters } from "../src/features/usage/errors-panel";
import { formatDateTime } from "../src/lib/format";
@@ -37,11 +41,12 @@ const item = (code: string): UsageErrorItem => ({
firstTs: "2026-08-27T10:00:00.000Z",
});
-function errorsOf(items: UsageErrorItem[]): UsageErrors {
+function errorsOf(items: UsageErrorItem[], ignored = 0): UsageErrors {
const total = items.reduce((sum, e) => sum + e.count, 0);
return {
total,
unexpected: total,
+ ignored,
topCode: null,
recent: items,
rows: items.length,
@@ -53,17 +58,20 @@ const FILTERS: ErrorsFilters = { from: "2026-08-01", to: "2026-08-27" };
function render(
opts: {
items?: UsageErrorItem[];
+ ignored?: number;
canClear?: boolean;
+ canIgnore?: boolean;
filters?: ErrorsFilters;
} = {},
): string {
const items = opts.items ?? [item("internal")];
return renderToStaticMarkup(
createElement(ErrorsPanel, {
- errors: errorsOf(items),
+ errors: errorsOf(items, opts.ignored ?? 0),
projectId: "p1",
filters: opts.filters ?? FILTERS,
canClear: opts.canClear ?? true,
+ canIgnore: opts.canIgnore ?? true,
onReload: () => {},
}),
);
@@ -124,10 +132,11 @@ describe("ErrorsPanel rows", () => {
const recent = Array.from({ length: 10 }, (_, i) => item(`code_${i}`));
const html = renderToStaticMarkup(
createElement(ErrorsPanel, {
- errors: { total: 40, unexpected: 40, topCode: null, recent, rows: 25 },
+ errors: { total: 40, unexpected: 40, ignored: 0, topCode: null, recent, rows: 25 },
projectId: "p1",
filters: FILTERS,
canClear: true,
+ canIgnore: true,
onReload: () => {},
}),
);
@@ -282,3 +291,133 @@ describe("ErrorsPanel copy action", () => {
expect(text).not.toContain("undefined");
});
});
+
+/** The rule list, rendered on its own: the panel fetches it in an effect, which `renderToStaticMarkup` never runs. */
+describe("IgnoreRulesBox", () => {
+ const rule = (over: Partial<UsageErrorIgnoreRule> = {}): UsageErrorIgnoreRule => ({
+ id: 7,
+ source: "llm",
+ code: "llm_retried",
+ messageLike: null,
+ note: null,
+ createdBy: "owner",
+ createdAt: "2026-08-27T10:00:00.000Z",
+ hidden: 349,
+ lastTs: "2026-08-27T09:00:00.000Z",
+ ...over,
+ });
+
+ const box = (rules: UsageErrorIgnoreRule[] | null): string =>
+ renderToStaticMarkup(createElement(IgnoreRulesBox, { rules, onUnignore: () => {} }));
+
+ it("draws the empty state when the Project has no rules yet, rather than an empty list", () => {
+ for (const rules of [null, []]) {
+ const html = box(rules);
+ expect(html).toContain(S.usage.errorsIgnoreRules);
+ expect(html).toContain(S.usage.errorsIgnoreRuleNone);
+ }
+ });
+
+ it("gives each rule what it covers, how much and how new, and the way back out", () => {
+ const html = box([rule()]);
+ expect(html).toContain("[llm] llm_retried");
+ expect(html).toContain(S.usage.errorsIgnoreRuleHidden(349));
+ expect(html).toContain(S.usage.errorsIgnoreRuleLast(formatDateTime(rule().lastTs!)));
+ expect(html).toContain(S.usage.errorsUnignore);
+ expect(html).toContain(S.usage.errorsIgnoreNotice);
+ });
+
+ it("a rule that covers nothing yet says so instead of standing for a zero", () => {
+ const html = box([rule({ hidden: 0, lastTs: null })]);
+ expect(html).toContain(S.usage.errorsIgnoreRuleHiddenNone);
+ expect(html).not.toContain(S.usage.errorsIgnoreRuleHidden(0));
+ });
+
+ it("carries the owner's own reason when they wrote one", () => {
+ expect(box([rule({ note: "引擎每次都会自己重连" })])).toContain("引擎每次都会自己重连");
+ });
+
+ // The one sentence a rule must not overstate: `[llm] llm_retried` covers every record of that
+ // code, and one narrowed to a fragment covers only part of it — the list has to say which.
+ for (const [locale, dict] of Object.entries({ zh, en })) {
+ it(`${locale}: a fragment-narrowed rule names the fragment, a whole-class one does not`, () => {
+ setActiveStrings(dict);
+ const narrowed = ignoreRuleText(rule({ messageLike: "UND_ERR_SOCKET" }));
+ expect(narrowed).toContain("[llm] llm_retried");
+ expect(narrowed).toContain("UND_ERR_SOCKET");
+ expect(narrowed).toContain(dict.usage.errorsIgnoreRuleFragment("UND_ERR_SOCKET"));
+
+ const whole = ignoreRuleText(rule());
+ expect(whole).toBe("[llm] llm_retried");
+ expect(whole).not.toContain(dict.usage.errorsIgnoreRuleFragment(""));
+ });
+ }
+});
+
+describe("ErrorsPanel ignore action", () => {
+ it("is offered to the Project owner only: the route refuses a member, so the panel does not promise it", () => {
+ expect(render({ canIgnore: true })).toContain(S.usage.errorsIgnoreAction);
+ expect(render({ canIgnore: false })).not.toContain(S.usage.errorsIgnoreAction);
+ });
+
+ it("is drawn once per row, and goes with the rows", () => {
+ const html = render({ items: [item("internal"), item("tool_failed:exec_command")] });
+ expect(html.split(`aria-label="${S.usage.errorsIgnoreAction}"`).length - 1).toBe(2);
+ expect(render({ items: [] })).not.toContain(S.usage.errorsIgnoreAction);
+ });
+});
+
+describe("ErrorsPanel ignored view", () => {
+ it("is one of the control's four choices, beside the two categories and both", () => {
+ const html = render({ items: [item("internal")] });
+ for (const label of [
+ S.usage.errorsFilterAll,
+ S.usage.errorsUnexpected,
+ S.usage.errorsExpected,
+ S.usage.errorsIgnored,
+ ]) {
+ expect(html).toContain(label);
+ }
+ });
+
+ it("reports what the rules hold back, so the numbers beside it are never read as the whole range", () => {
+ const html = render({ items: [item("internal")], ignored: 261 });
+ expect(html).toContain(`>${S.usage.errorsIgnored}<`);
+ expect(html).toContain(">261<");
+ });
+
+ it("says in the clear confirmation that the ignored records are not the ones it counts", () => {
+ // The sentence names what the table showed; on any other view that leaves the ignored rows out,
+ // and a reader taking "42 records" for the whole range would be reading it wrong. The dialog is
+ // not renderable here (see the file header), so its own wording is asserted as a pure function.
+ expect(errorsClearKeepsIgnoredText(5, FILTERS)).toBe(S.usage.errorsClearKeepsIgnored(5));
+ // Nothing held back: nothing to add. On the ignored view those records are the sentence's own
+ // subject, so the note would count them twice.
+ expect(errorsClearKeepsIgnoredText(0, FILTERS)).toBeNull();
+ expect(errorsClearKeepsIgnoredText(5, { ...FILTERS, ignored: true })).toBeNull();
+ });
+});
+
+describe("errorsClearScopeText on the ignored view", () => {
+ for (const [locale, dict] of Object.entries({ zh, en })) {
+ it(`${locale}: names the ignored records as such, and keeps what is not ignored`, () => {
+ setActiveStrings(dict);
+ const text = errorsClearScopeText({ ...FILTERS, ignored: true }, "7d", 6);
+ // It says "ignored" in the interface's own word for it — the sentence names the set it takes.
+ expect(text.toLowerCase()).toContain(dict.usage.errorsIgnored.toLowerCase());
+ expect(text).toContain("6");
+ expect(text).toContain(dict.usage.errorsClearRangePreset("7d"));
+ // Not the category sentence: the ignored view is not a category, and what it keeps is every
+ // record no rule covers rather than "the other category".
+ expect(text).not.toContain(dict.usage.errorsClearRangeCustom(FILTERS.from!, FILTERS.to!));
+
+ const perAgent = errorsClearScopeText(
+ { ...FILTERS, ignored: true, agentId: "agent-7" },
+ "7d",
+ 2,
+ );
+ expect(perAgent).toContain("agent-7");
+ expect(perAgent).toContain(dict.usage.errorsClearRangePreset("7d"));
+ });
+ }
+});