A local-first multi-agent app development platform, built on PenguinHarness
Classify recoverable gateway closes, and let an owner clear the error table (#530)
Yaowei Zheng1503ec89c805
diff --git a/changelog/unreleased/2026-08-28-error-noise-and-clear.md b/changelog/unreleased/2026-08-28-error-noise-and-clear.mdnew file mode 100644index 00000000..9be34383--- /dev/null+++ b/changelog/unreleased/2026-08-28-error-noise-and-clear.md@@ -0,0 +1,57 @@+# A dropped QQ gateway stops counting as a defect, and the error table gains a clear action++- **Date:** 2026-08-28+- **Type:** feature+- **Scope:** `server`, `web`+- **PR:** [#530](https://github.com/Prism-Shadow/penguin-harness/pull/530)++[中文版](2026-08-28-error-noise-and-clear.zh.md)++Two changes to the cost center's error panel. A QQ gateway connection that the platform closed+and the connector brought straight back no longer files as an error needing a human, and a+Project owner can empty the table the panel is showing.++## Gateway closes are classified by what the connector does next++The QQ gateway session now reports a close as a typed `MessagingConnectionClosedError`, carrying+the platform's close code and whether the next handshake restores the connection with nothing+changed. `error-kind.ts` reads that verdict — never the message text, so the count does not+depend on how a platform words its own close. One outage still reports once, with one+exception: a routine close does not keep the slot, so an expired socket followed by a refusal+that repeats forever still records the refusal.++- `expected`: close code 4009 (the platform expiring a long-lived connection, which stays+ resumable, so the session replays from its sequence number) and the 4900–4913 internal-error+ band, whose documented handling is the re-identify the session already performs.+- `unexpected`, unchanged: 4006 and 4007, where only a fresh identify recovers and whatever+ arrived in the gap is lost; 4004, 4014 and every other refusal that repeats identically until+ a credential or a console setting changes; 4914 and 4915, where the session stops for good;+ and the failures that are not platform closes at all — a handshake that never completed, a+ gateway that stopped acknowledging heartbeats.++Records already stored keep the `kind` they were written with; the classification applies to+errors recorded from here on.++## Clearing the error table++`DELETE /api/projects/:projectId/usage/errors` empties the table for the filter the panel is+showing, and the panel's footer offers it behind a confirmation.++- **Scope**: the date range and Agent the panel actually read, the same window its rows and its+ later pages come from — the trailing presets compute theirs at load time rather than from the+ date pair the picker holds, so the clear follows what is on screen rather than what was picked+ before it. Rows outside it are kept, and the confirmation states the range, the Agent when one+ is selected, and how many rows will go. It is offered only where both bounds are real dates,+ since an open-ended range is wider than the sentence can promise.+- **Authorization**: Project owner only, the rule Agent deletion already applies to error rows.+ A member can read the panel and gets 403 on the delete; the panel does not show the action to+ one.+- Errors with no Project attribution — login failures, process crashes — are outside every+ clear, whoever asks. They belong to no Project and appear in every Project's admin view, so+ the delete's reach stays strictly narrower than any caller's read. The dashboard's error block+ gained a `clearable` count for exactly this: an admin's read includes those rows and the+ confirmation must not, or it would promise a number larger than what goes.+- `ErrorsRepo.deleteFiltered` builds its `WHERE` from the same clause the reads use, so a+ clear cannot select a row a matching read would not have returned.++Deleted rows are gone: an error record has no copy anywhere else, and nothing restores it.diff --git a/changelog/unreleased/2026-08-28-error-noise-and-clear.zh.md b/changelog/unreleased/2026-08-28-error-noise-and-clear.zh.mdnew file mode 100644index 00000000..2878ba5b--- /dev/null+++ b/changelog/unreleased/2026-08-28-error-noise-and-clear.zh.md@@ -0,0 +1,46 @@+# QQ 网关断开不再计为缺陷,错误表新增清空操作++- **Date:** 2026-08-28+- **Type:** feature+- **Scope:** `server`, `web`+- **PR:** [#530](https://github.com/Prism-Shadow/penguin-harness/pull/530)++[English](2026-08-28-error-noise-and-clear.md)++对成本中心错误面板的两项改动。QQ 网关被平台关闭、而连接器随即恢复的连接,不再计入「需要人处理」的错误;+Project owner 可以清空面板当前展示的错误表。++## 网关关闭按连接器的后续行为分类++QQ 网关会话现在以 `MessagingConnectionClosedError` 上报关闭,其中携带平台的 close code,以及下一次+握手能否在无人改动任何东西的情况下恢复连接。`error-kind.ts` 读取这个判定,而不读消息文本——计数因此不+依赖平台如何措辞自己的关闭。一次故障仍然只上报一次,但有一个例外:常规关闭不会占住这个名额,因此「连接过期+之后紧跟着一直重复的拒绝」仍会把那个拒绝记录下来。++- `expected`:close code 4009(平台让长连接过期,该关闭仍可 resume,会话据 seq 重放)与 4900–4913+ 内部错误段,其文档给出的处理正是会话已在执行的重新 identify。+- `unexpected`,保持不变:4006 与 4007,只能靠全新 identify 恢复,其间到达的消息会丢失;4004、4014+ 以及其他在凭据或控制台设置改动前会一模一样重复的拒绝;4914 与 4915,会话就此彻底停止;以及本就不属于+ 平台关闭的失败——未完成的握手、停止回应心跳的网关。++已存储的记录保留写入时的 `kind`;该分类只作用于此后记录的错误。++## 清空错误表++`DELETE /api/projects/:projectId/usage/errors` 清空面板当前筛选下的错误表,面板底栏在确认弹窗之后提供+该操作。++- **范围**:面板实际读取所用的时间范围与 Agent,也就是表中行与后续分页的同一个窗口——两个「最近」预设的+ 窗口在加载时计算,而不取日期选择器里留存的那一对,因此清空跟随屏幕上的内容,而非之前选过的范围。范围外+ 的记录保留;确认弹窗会说明时间范围、选中的 Agent(若有)以及将删除多少条。仅当两端都是有效日期时才提供+ 该操作——开区间比这句话所能承诺的范围更宽。+- **权限**:仅 Project owner,与删除 Agent 对错误记录已适用的规则一致。成员可以查看面板,删除会得到+ 403;面板也不会向成员展示该操作。+- 未归属到 Project 的错误——登录失败、进程崩溃——不在任何一次清空的范围内,无论发起者是谁。它们不属于+ 任何 Project,且会出现在每个 Project 的管理员视图中,因此删除的触及范围严格小于任何调用者的读取范围。+ 看板的错误块为此新增 `clearable` 计数:管理员的读取包含这些行,而确认弹窗不能包含,否则会承诺一个大于+ 实际删除量的数字。+- `ErrorsRepo.deleteFiltered` 的 `WHERE` 由读取所用的同一子句构建,因此一次清空无法选中匹配读取本不会+ 返回的行。++被删除的记录不可恢复:错误记录别处没有副本,也没有任何机制能还原它。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 39e5d236..22548925 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -229,6 +229,7 @@ On Session creation, `modelId` and `provider` are both-or-neither: send the comp| --- | --- | --- || GET | /usage | Usage statistics; query parameters `from`, `to`, `fromTs`/`toTs` (ISO timestamps bounding a trailing window, given together; required for `minute`), `groupBy`, `granularity` (`minute` / `hour` / `day` / `week` / `month` time-series precision, default `day`; oversized range × precision combinations are rejected), `agentId`, `provider`, `modelId` || GET | /usage/errors | One page of the error detail table (newest first): `offset`, `limit`, plus the same `from` / `to` / `agentId` filter and an optional `kind` (`unexpected` / `expected`) → `{items, total}` |+| DELETE | /usage/errors | Empties the error table for the filter on screen: `from` / `to` / `agentId`, the same pair the reads take (no `kind` — the panel offers no such control) → `{deleted}`. Project owner only; errors with no Project attribution are outside every clear, admin included || GET | /agents/:agentId/traces | Date → Session drill-down structure of Trace files || GET | /agents/:agentId/traces/:sessionId/:index | Read Trace events (`offset` / `limit` pagination) || GET | /agents/:agentId/traces/:sessionId/:index/analysis | Trace performance analysis |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 4eb250c7..927b10f3 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -229,6 +229,7 @@ Schedule 写操作仅限 Owner。新建 Session 模式的任务,`modelId` 与| --- | --- | --- || GET | /usage | 用量统计,查询参数 `from`、`to`、`fromTs`/`toTs`(ISO 时间戳界定的滑动窗口,须成对给出;`minute` 精度必需)、`groupBy`、`granularity`(时间序列精度 `minute` / `hour` / `day` / `week` / `month`,默认 `day`;范围 × 精度过大的组合会被拒绝)、`agentId`、`provider`、`modelId` || GET | /usage/errors | 异常明细表分页(按时间倒序):`offset`、`limit`,以及与看板一致的 `from` / `to` / `agentId` 过滤,另可选 `kind`(`unexpected` / `expected`)→ `{items, total}` |+| DELETE | /usage/errors | 清空当前筛选下的异常明细:`from` / `to` / `agentId`,与读取所用的同一组(不接受 `kind`,面板没有该控件)→ `{deleted}`。仅 Project owner;无 Project 归属的异常不在任何一次清空范围内,管理员亦然 || GET | /agents/:agentId/traces | Trace 文件的日期 → Session 下钻结构 || GET | /agents/:agentId/traces/:sessionId/:index | 读取 Trace 事件(`offset` / `limit` 分页) || GET | /agents/:agentId/traces/:sessionId/:index/analysis | Trace 性能分析结果 |diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 53467bd8..b361c6eb 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -2633,6 +2633,15 @@ export interface UsageErrorItem {*/export interface UsageErrors {total: number;+ /**+ * How many of {@link total} a clear would actually take (see {@link UsageErrorsClearResponse}).+ *+ * The same as `total` for an ordinary member, and smaller for an admin, whose reads include+ * unattributed rows that no Project-scoped clear removes. The confirmation is the only place+ * this matters, and it is the place it matters most: an irreversible delete has to name the+ * number that will really go, not the number on screen.+ */+ clearable: number;/** Count of unexpected ones (500 / runtime exceptions) among them — the part the frontend highlights. */unexpected: number;/** The most frequent source · code (null when there are no errors). */@@ -2656,6 +2665,19 @@ export interface UsageErrorsPage {total: number;}+/**+ * DELETE /api/projects/:projectId/usage/errors — empties the error table for the filter the+ * panel is showing (its date range and Agent), Project owner only.+ *+ * Scoped to the filter rather than the Project's whole history, so a clear takes exactly the+ * rows on screen. Errors with no Project attribution are never included, whoever asks: they+ * belong to no Project and are surfaced in every Project's admin view.+ */+export interface UsageErrorsClearResponse {+ /** How many rows were deleted, so the caller can say what went instead of guessing. */+ deleted: number;+}+export interface UsageResponse {summary: {today: UsageBucket;diff --git a/packages/server/src/db/repos/errors.ts b/packages/server/src/db/repos/errors.tsindex c7e06d36..2f92c4c0 100644--- a/packages/server/src/db/repos/errors.ts+++ b/packages/server/src/db/repos/errors.ts@@ -218,6 +218,30 @@ export class ErrorsRepo {}));}+ /**+ * Deletes the rows a matching read would have returned, and answers how many went.+ *+ * The WHERE comes from the same `conds` the SELECTs use, so the delete can never reach a row+ * the caller's own reads could not: narrowing a filter narrows both halves together, and+ * there is no second expression to drift.+ *+ * `includeGlobal` is deliberately not accepted. Unattributed rows belong to no Project and+ * appear in EVERY Project's admin view, so a Project-scoped clear that took them would empty+ * them out of every other Project's panel as well — the same line deleteByProject and+ * deleteByAgent already draw. Clearing them is an admin-wide act and needs an admin-wide+ * surface, not a side effect of tidying one Project.+ *+ * The `Omit` on the parameter says that, but it does not enforce it: excess-property checking+ * only fires on a fresh object literal, so a caller already holding an `ErrorFilter` could+ * forward one carrying `includeGlobal: true` and compile clean. Hence the explicit `false`+ * below — the guard is in the query, where a future caller cannot get around it.+ */+ deleteFiltered(projectId: string, f: Omit<ErrorFilter, "includeGlobal"> = {}): number {+ const { where, params } = this.conds(projectId, { ...f, includeGlobal: false });+ const res = this.db.prepare(`DELETE FROM error_records WHERE ${where}`).run(params);+ return Number(res.changes);+ }+/** Cascading cleanup on Agent deletion (unattributed errors carry no agent_id and are unaffected). */deleteByAgent(projectId: string, agentId: string): void {this.dbdiff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.tsindex a363863f..110121d6 100644--- a/packages/server/src/http/routes/usage.ts+++ b/packages/server/src/http/routes/usage.ts@@ -6,10 +6,17 @@* trailing window down to instants — required for minute — and must be given* together);* GET /api/projects/:p/usage/errors?offset&limit&from&to&agentId&kind — one page of the error- * detail table, for paging back past the first page the dashboard already returns.+ * detail table, for paging back past the first page the dashboard already returns;+ * DELETE /api/projects/:p/usage/errors?from&to&agentId — empties that table for the filter+ * the panel is showing (owner only).*/import { Hono } from "hono";-import type { UsageErrorKind, UsageGranularity, UsageGroupBy } from "../../api/types.js";+import type {+ UsageErrorKind,+ UsageErrorsClearResponse,+ UsageGranularity,+ UsageGroupBy,+} from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import { badRequest, optionalDateParam, paginationQuery, requireValidId } from "../validate.js";import type { AppDeps } from "../../app.js";@@ -120,5 +127,31 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {);});+ // Empties the error table for the filter the panel is showing. Takes the same date/agent+ // filter as the two reads above and no other: a clear removes exactly the rows the caller+ // was looking at, never the Project's whole history behind a narrowed view. `kind` is not+ // accepted — the panel has no control for it, so a clear can offer no narrowing its reader+ // could have seen on screen.+ app.delete("/errors", (c) => {+ 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.projectService.requireProjectOwner(c.var.user.userId, projectId);+ const from = optionalDateParam(c.req.query("from"), "from");+ const to = optionalDateParam(c.req.query("to"), "to");+ const agentId = c.req.query("agentId");+ // No `includeGlobalErrors` counterpart to the reads above, on purpose. Unattributed rows+ // (login failures, process crashes) are admin-only to READ, and are excluded from every+ // clear — so the delete's reach is strictly narrower than any caller's, and a clear can+ // never become a way to remove a row its caller was not allowed to see.+ const deleted = deps.usageService.clearErrors(projectId, {+ ...(from !== undefined ? { from } : {}),+ ...(to !== undefined ? { to } : {}),+ ...(agentId !== undefined && agentId !== "" ? { agentId } : {}),+ });+ return c.json({ deleted } satisfies UsageErrorsClearResponse);+ });+return app;}diff --git a/packages/server/src/runtime/messaging/error-kind.ts b/packages/server/src/runtime/messaging/error-kind.tsindex 470aaa16..1c57c55b 100644--- a/packages/server/src/runtime/messaging/error-kind.ts+++ b/packages/server/src/runtime/messaging/error-kind.ts@@ -23,7 +23,9 @@* this feature has — and this record is the only place it surfaces.** The rule is deliberately a small allowlist of TYPED failures at NAMED capture points rather- * than a message match. Anything the connectors have not classified stays `unexpected`, which+ * than a message match, plus one typed failure that arrives carrying its own verdict — a+ * connection the platform closed, where whether anything stayed broken is protocol state only+ * the connector holds. Anything the connectors have not classified stays `unexpected`, which* is the safe direction: a real fault miscounted as routine is invisible, while routine noise* miscounted as a fault is merely loud.*/@@ -33,6 +35,7 @@ import {MessagingPermissionError,MessagingUnsupportedError,} from "./media.js";+import { MessagingConnectionClosedError } from "./qq-api.js";/*** The capture points that put the refusal in front of the person in the chat.@@ -77,8 +80,20 @@ const CODES_EXPLAINED_IN_CHAT = new Set([* Everything else — a network failure, a 5xx from the platform, a bug here — is `unexpected`* and keeps its place on the dashboard, and so is any of the three caught where the chat hears* nothing: a refusal nobody was told about is still a refusal somebody has to notice.+ *+ * {@link MessagingConnectionClosedError} is the one `expected` case the chat is NOT told+ * about, and it answers the criterion the other way round: nobody needs telling, because+ * nothing stayed broken. A platform that expires a long-lived socket, or hits its own+ * internal error, is answered by the connector's next handshake within the backoff, and the+ * only trace is a record nobody can act on. It is `expected` only when the connector says the+ * close is one of those — `recovers` is decided where the reconnect is, and a close that+ * leaves the binding down until a credential or a console setting changes reports+ * `recovers: false` and stays a defect.*/export function messagingErrorKind(err: unknown, code: string): ErrorKind {+ if (err instanceof MessagingConnectionClosedError) {+ return err.recovers ? "expected" : "unexpected";+ }if (!CODES_EXPLAINED_IN_CHAT.has(code)) return "unexpected";if (err instanceof MessagingPermissionError ||diff --git a/packages/server/src/runtime/messaging/qq-api.ts b/packages/server/src/runtime/messaging/qq-api.tsindex 82d25537..ccd14b95 100644--- a/packages/server/src/runtime/messaging/qq-api.ts+++ b/packages/server/src/runtime/messaging/qq-api.ts@@ -214,6 +214,60 @@ function closeCodeIsFatal(code: number): boolean {return code === 4914 || code === 4915;}+/**+ * Close codes the next handshake clears on its own, with nothing for anyone to change.+ *+ * 4009 is the platform expiring a long-lived connection — its documented handling is+ * "reconnect", and it is the one drop that stays RESUMABLE (see closeCodeInvalidatesSession),+ * so the next HELLO replays from `seq` and no inbound event is missed. 4900-4913 is the+ * platform's own internal-error band, whose documented handling is the fresh identify this+ * session already performs; nothing an operator holds could have prevented it or can speed it+ * up.+ *+ * Deliberately narrower than "reconnects": nearly every close reconnects here, including the+ * ones that will never come up again. A rejected token (4004), an intent the bot was never+ * granted (4014) and a delisted or banned bot (4914 / 4915) all retry just as eagerly and+ * repeat the identical refusal until a human changes a credential or a console setting. 4006+ * and 4007 stay out too: they say the session state this client presented was refused, which+ * a fresh identify papers over — at the cost of whatever arrived during the gap — and which,+ * repeating, points at this client's own sequence bookkeeping.+ */+function closeCodeIsRoutine(code: number): boolean {+ return code === 4009 || (code >= 4900 && code <= 4913);+}++/**+ * A connection the platform itself closed, carrying the code it closed with.+ *+ * Its own class so the error recorder can tell a socket the gateway cycled from one that is+ * down until someone acts, WITHOUT reading the message text: a wording match would tie the+ * dashboard's "needs a human" count to how a platform phrases itself. error-kind.ts reads+ * `recovers` and nothing else.+ *+ * `recovers` carries the answer rather than the raw code because the reconnect decision is+ * protocol state this file already owns and nothing above it holds (see GatewaySession). It+ * is true only where the next handshake restores the connection with nothing changed+ * (closeCodeIsRoutine), and false where retrying repeats the same refusal or the session has+ * stopped for good.+ *+ * It lives beside the gateway rather than in a shared module because the gateway is the only+ * connection in this product that learns WHY it was closed: the Feishu long connection is the+ * vendor SDK's own reconnect loop and surfaces a plain failure, and Telegram's transport is a+ * long poll with no connection to close.+ */+export class MessagingConnectionClosedError extends Error {+ constructor(+ message: string,+ /** The platform's own WebSocket close code. */+ readonly closeCode: number,+ /** Whether the next handshake brings the connection back with nothing changed. */+ readonly recovers: boolean,+ ) {+ super(message);+ this.name = "MessagingConnectionClosedError";+ }+}+/*** How long a socket has to finish its handshake before it is dropped and retried.*@@ -521,8 +575,17 @@ class GatewaySession {private handshakeTimer: ReturnType<typeof setTimeout> | null = null;/** When the last HEARTBEAT_ACK arrived, against which the heartbeat tick measures silence. */private lastAckAt = 0;- /** This outage already reported; the retries stay quiet until a handshake succeeds. */- private reported = false;+ /**+ * What this outage has already reported; the retries stay quiet until a handshake succeeds.+ *+ * One report per outage is what keeps a backoff loop from filling the error table. A routine+ * close is now filed `expected`, though, so letting it claim the slot outright would silence+ * the outage behind it: a socket the platform expires at 4009 followed by an auth refusal on+ * every retry would leave the dashboard reading zero defects for a binding that is down until+ * a person acts. So a routine report is spent once more — by the first failure that is not+ * routine — and only then does the outage go quiet.+ */+ private reported: "none" | "routine" | "defect" = "none";constructor(private readonly client: ProductionClient,@@ -612,13 +675,21 @@ class GatewaySession {if (closeCodeIsFatal(evt.code)) {this.closed = true;this.handlers.onError?.(- new Error(+ new MessagingConnectionClosedError(`gateway refused this bot (close code ${evt.code}) — it is delisted or banned on the QQ open platform`,+ evt.code,+ false,),);return;}- this.fail(new Error(`gateway connection closed (code ${evt.code})`));+ this.fail(+ new MessagingConnectionClosedError(+ `gateway connection closed (code ${evt.code})`,+ evt.code,+ closeCodeIsRoutine(evt.code),+ ),+ );});}@@ -699,7 +770,7 @@ class GatewaySession {private onHandshake(): void {this.disarmHandshake();this.failures = 0;- this.reported = false;+ this.reported = "none";this.handlers.onReady?.();}@@ -765,12 +836,17 @@ class GatewaySession {}}- /** One report per outage, then retry with backoff — the Telegram poll loop's contract. */+ /**+ * One report per outage, then retry with backoff — the Telegram poll loop's contract, with+ * the one exception `reported` documents: a routine close does not get to be the whole story+ * of an outage that turns out to need a person.+ */private fail(err: unknown): void {if (this.closed) return;this.failures += 1;- if (!this.reported) {- this.reported = true;+ const routine = err instanceof MessagingConnectionClosedError && err.recovers;+ if (this.reported === "none" || (this.reported === "routine" && !routine)) {+ this.reported = routine ? "routine" : "defect";this.handlers.onError?.(err);}this.retryTimer = setTimeout(() => {diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.tsindex 2246ecd4..03a89c55 100644--- a/packages/server/src/services/usage-service.ts+++ b/packages/server/src/services/usage-service.ts@@ -102,6 +102,18 @@ export interface UsageErrorsQuery {includeGlobalErrors?: boolean;}+/**+ * What a clear removes (see {@link UsageService.clearErrors}): the panel's own date range and+ * Agent, and nothing else. No `kind` — the panel offers no such control, so a clear has no+ * narrowing the reader could have seen — and no `includeGlobalErrors`, since unattributed rows+ * are never a Project's to delete.+ */+export interface UsageErrorsClearQuery {+ from?: string;+ to?: string;+ agentId?: string;+}+/** Cost formula: sum of the three buckets, in USD per million Tokens. */function costOf(sums: UsageModelSums, rates: PricingRates): number {return (@@ -277,11 +289,38 @@ export class UsageService {};}+ /**+ * Empties the error table for the filter the panel is showing, and answers how many rows went.+ *+ * The filter is the same date range and Agent the dashboard and the paged route take, so a+ * clear removes exactly the set the caller was looking at and never a row outside it: a+ * reader who has narrowed to one Agent and one week does not lose the rest of the year to a+ * button that said "clear".+ *+ * Unattributed rows are outside every clear (see ErrorsRepo.deleteFiltered): they carry no+ * Project, so they are not this Project's to remove, and the delete's scope is therefore+ * strictly narrower than what any caller — admin included — is allowed to read.+ */+ clearErrors(projectId: string, q: UsageErrorsClearQuery): number {+ return this.errors.deleteFiltered(projectId, {+ ...(q.agentId !== undefined ? { agentId: q.agentId } : {}),+ ...(q.from !== undefined ? { from: q.from } : {}),+ ...(q.to !== undefined ? { to: q.to } : {}),+ });+ }+/** Error statistics: summary info (total / unexpected / most common error code) + the last N entries, all filtered by the selected range. */private foldErrors(projectId: string, f: ErrorFilter): UsageErrors {const { total, unexpected } = this.errors.summary(projectId, f);return {total,+ // Counted the way deleteFiltered selects — without the unattributed rows an admin's read+ // includes — so the clear confirmation states what will really go rather than what is on+ // screen. Identical to `total` for everyone whose read did not include them.+ clearable:+ f.includeGlobal === true+ ? this.errors.summary(projectId, { ...f, includeGlobal: false }).total+ : total,unexpected,topCode: this.errors.topCode(projectId, f),recent: this.errors.recent(projectId, f, ERROR_RECENT_N),diff --git a/packages/server/test/errors.test.ts b/packages/server/test/errors.test.tsindex 418dd883..b2e9dd21 100644--- a/packages/server/test/errors.test.ts+++ b/packages/server/test/errors.test.ts@@ -36,6 +36,8 @@ import {ErrorRecorder,MESSAGE_MAX,} from "../src/runtime/error-recorder.js";+import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";+import { MessagingConnectionClosedError } from "../src/runtime/messaging/qq-api.js";import { StreamErrorWatcher } from "../src/runtime/stream-error-watcher.js";import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -146,6 +148,43 @@ describe("errors-repo", () => {expect(rows[0]!.project_id).toBeNull();});+ it("deleteFiltered: takes exactly the rows the same filter would have read", () => {+ repo.insert(row("2026-07-05", { message: "before-range" }));+ repo.insert(row("2026-07-06", { agentId: "a1", message: "in-range-a1" }));+ repo.insert(row("2026-07-06", { agentId: "a2", message: "in-range-a2" }));+ repo.insert(row("2026-07-07", { message: "after-range" }));++ // Narrowed to one Agent inside the range: everything the reader could not see survives.+ expect(repo.deleteFiltered("p1", { from: "2026-07-06", to: "2026-07-06", agentId: "a1" })).toBe(+ 1,+ );+ expect(repo.recent("p1").map((r) => r.message)).toEqual([+ "after-range",+ "in-range-a2",+ "before-range",+ ]);++ // The range alone still spares the dates outside it.+ expect(repo.deleteFiltered("p1", { from: "2026-07-06", to: "2026-07-06" })).toBe(1);+ expect(repo.recent("p1").map((r) => r.message)).toEqual(["after-range", "before-range"]);+ });++ it("deleteFiltered: never reaches unattributed rows or another Project's", () => {+ // Unattributed rows appear in EVERY Project's admin view, so a Project-scoped clear that+ // took them would empty them out of every other Project's panel as well.+ repo.insert(row("2026-07-06", { projectId: null, source: "process", message: "crash" }));+ repo.insert(row("2026-07-06", { projectId: "p-other", message: "other tenant" }));+ repo.insert(row("2026-07-06", { message: "mine" }));++ expect(repo.deleteFiltered("p1")).toBe(1);+ expect(+ db+ .prepare("SELECT message FROM error_records ORDER BY id")+ .all()+ .map((r) => r.message),+ ).toEqual(["crash", "other tenant"]);+ });+// —— Row cap (the second line of defense against error storms; the first is ErrorRecorder's short-window dedup) ——const messages = () =>@@ -256,6 +295,34 @@ describe("error-recorder", () => {expect(rows[1]).toMatchObject({ kind: "unexpected", source: "llm", status: null });});+ it("a gateway close is filed by its own verdict: the routine one leaves the count alone", () => {+ // The path the messaging bridge takes for a dropped connection: the connector's typed+ // close, classified by messagingErrorKind, persisted under `messaging_connect_failed`.+ // Both rows land — the log keeps everything — but only the one a person has to act on+ // reaches the unexpected count the cost center highlights.+ const rec = new ErrorRecorder(repo, now);+ const closed = (message: string, code: number, recovers: boolean) =>+ new MessagingConnectionClosedError(message, code, recovers);+ for (const err of [+ closed("gateway connection closed (code 4009)", 4009, true),+ closed("gateway connection closed (code 4004)", 4004, false),+ ]) {+ rec.record({+ source: "messaging",+ err,+ code: "messaging_connect_failed",+ kind: messagingErrorKind(err, "messaging_connect_failed"),+ // Distinct Projects so the recorder's short-window dedup does not swallow the second.+ ctx: { projectId: err.recovers ? "p-routine" : "p-fault" },+ });+ }+ const rows = db.prepare("SELECT kind, code, message FROM error_records ORDER BY id").all();+ expect(rows[0]).toMatchObject({ kind: "expected", code: "messaging_connect_failed" });+ expect(rows[1]).toMatchObject({ kind: "unexpected", code: "messaging_connect_failed" });+ expect(repo.summary("p-routine")).toEqual({ total: 1, unexpected: 0 });+ expect(repo.summary("p-fault")).toEqual({ total: 1, unexpected: 1 });+ });+// —— Short-window dedup (the first line of defense against error storms) ——const count = () =>@@ -1064,6 +1131,11 @@ describe("HTTP onError persistence (integration)", () => {expect(adminBody.errors.total).toBe(1);expect(adminBody.errors.topCode).toMatchObject({ source: "http", code: "invalid_credentials" });expect(adminBody.errors.recent[0]).toMatchObject({ code: "invalid_credentials" });+ // …but not clear it. The clear confirmation states `clearable`, so what it promises is what+ // the delete can really take: the read reaches this row, no Project-scoped delete does.+ expect(adminBody.errors.clearable).toBe(0);+ // A member's read never included them, so the two numbers are the same one.+ expect(plainBody.errors.clearable).toBe(0);});it("the paged error route pages inside the caller's own tenant, at every offset", async () => {@@ -1170,6 +1242,111 @@ describe("HTTP onError persistence (integration)", () => {expect(all.total).toBe(4);});+ /** Seeds one row straight into the table, so a batch's dates and Agents are exact. */+ const seedRow = (o: Partial<ErrorRecordInsert> & { date: string; code: string }) =>+ new ErrorsRepo(t.deps.db).insert({+ ts: `${o.date}T00:00:00.000Z`,+ projectId,+ agentId: null,+ sessionId: null,+ source: "http",+ kind: "expected",+ status: 404,+ message: o.code,+ ...o,+ });++ it("clearing errors takes the filter on screen and nothing outside it", async () => {+ seedRow({ date: "2026-07-05", code: "before_range" });+ seedRow({ date: "2026-07-06", code: "in_range_a1", agentId: "a1" });+ seedRow({ date: "2026-07-06", code: "in_range_a2", agentId: "a2" });+ seedRow({ date: "2026-07-08", code: "after_range" });++ // Narrowed to one Agent inside the range: exactly the rows that filter reads.+ const narrow = await api.delete(+ `/api/projects/${projectId}/usage/errors?from=2026-07-06&to=2026-07-06&agentId=a1`,+ );+ expect(narrow.status).toBe(200);+ expect(await narrow.json()).toEqual({ deleted: 1 });+ expect(errorRows().map((r) => r.code)).toEqual(["before_range", "in_range_a2", "after_range"]);++ // The range on its own still spares the dates the reader was not looking at.+ const ranged = await api.delete(+ `/api/projects/${projectId}/usage/errors?from=2026-07-06&to=2026-07-07`,+ );+ expect(await ranged.json()).toEqual({ deleted: 1 });+ expect(errorRows().map((r) => r.code)).toEqual(["before_range", "after_range"]);++ // No filter clears the Project's whole history, which is what an unfiltered panel showed.+ expect(await (await api.delete(`/api/projects/${projectId}/usage/errors`)).json()).toEqual({+ deleted: 2,+ });+ expect(errorRows()).toHaveLength(0);+ });++ it("a member cannot clear the log, so it is no route to the unattributed rows", async () => {+ seedRow({ date: "2026-07-06", code: "project_row" });+ seedRow({ date: "2026-07-06", code: "unattributed_row", projectId: null, source: "process" });++ // The refusals below are recorded by app.onError like any other, so the seeded rows are+ // read back by code rather than by counting the table.+ const seeded = () =>+ errorRows()+ .map((r) => r.code as string)+ .filter((c) => c === "project_row" || c === "unattributed_row");++ const member = await provisionUser(t.app, "member_user");+ expect(member.user.isAdmin).toBe(false);+ const added = await api.post(`/api/projects/${projectId}/members`, { userId: "member_user" });+ expect(added.status).toBe(201);+ const memberApi = apiClient(t.app, member.cookie);++ // Reading the panel is a member's right; emptying it is the owner's, like deleting an Agent.+ expect((await memberApi.get(`/api/projects/${projectId}/usage/errors?offset=0`)).status).toBe(+ 200,+ );+ const refused = await memberApi.delete(`/api/projects/${projectId}/usage/errors`);+ expect(refused.status).toBe(403);+ expect(((await refused.json()) as { error: { code: string } }).error.code).toBe(+ "owner_required",+ );+ expect(seeded()).toEqual(["project_row", "unattributed_row"]);++ // A non-member is not told the Project exists, let alone allowed to empty it.+ const outsider = await provisionUser(t.app, "outsider_user");+ const outsiderApi = apiClient(t.app, outsider.cookie);+ expect((await outsiderApi.delete(`/api/projects/${projectId}/usage/errors`)).status).toBe(404);+ expect(seeded()).toEqual(["project_row", "unattributed_row"]);+ });++ it("unattributed rows survive every clear, including an admin's own", async () => {+ // They belong to no Project and show in EVERY Project's admin view, so a Project-scoped+ // clear taking them would empty them out of every other Project's panel too. That keeps+ // the delete strictly narrower than any caller's read, admin included.+ const adminApi = apiClient(t.app, (await loginAdmin(t.app)).cookie);+ new ErrorsRepo(t.deps.db).insert({+ ts: "2026-07-06T00:00:00.000Z",+ date: "2026-07-06",+ projectId: null,+ agentId: null,+ sessionId: null,+ source: "process",+ kind: "unexpected",+ code: "uncaught_exception",+ status: null,+ message: "crash",+ });+ // The admin can see it from their own Project, which is exactly the view being cleared.+ const before = (await (+ await adminApi.get(`/api/projects/default_project/usage/errors?offset=0&limit=20`)+ ).json()) as UsageErrorsPage;+ expect(before.items.map((e) => e.code)).toEqual(["uncaught_exception"]);++ const cleared = await adminApi.delete(`/api/projects/default_project/usage/errors`);+ expect(await cleared.json()).toEqual({ deleted: 0 });+ expect(errorRows().filter((r) => r.project_id === null)).toHaveLength(1);+ });+it("Project deletion cascade-cleans that Project's error records", async () => {await api.get(`/api/projects/${projectId}/agents/agent-nope/sessions`);expect(errorRows().filter((r) => r.project_id === projectId)).toHaveLength(1);diff --git a/packages/server/test/messaging-error-kind.test.ts b/packages/server/test/messaging-error-kind.test.tsindex cd65400d..dca070d3 100644--- a/packages/server/test/messaging-error-kind.test.ts+++ b/packages/server/test/messaging-error-kind.test.ts@@ -16,6 +16,7 @@ import {MessagingPermissionError,MessagingUnsupportedError,} from "../src/runtime/messaging/media.js";+import { MessagingConnectionClosedError } from "../src/runtime/messaging/qq-api.js";/** Feishu's 99991672, which every one of its calls throws alike — the point of the code half. */const scopeDenial = (): MessagingPermissionError =>@@ -63,4 +64,45 @@ describe("messagingErrorKind", () => {).toBe("unexpected");expect(messagingErrorKind(undefined, "messaging_connect_failed")).toBe("unexpected");});++ it("a platform close is read from its own verdict, not from the capture point", () => {+ // The one expected case the chat is never told about, and the one that crosses a capture+ // point the set above deliberately excludes: nobody needs telling because the connector's+ // next handshake already put the connection back.+ expect(+ messagingErrorKind(+ new MessagingConnectionClosedError("gateway connection closed (code 4009)", 4009, true),+ "messaging_connect_failed",+ ),+ ).toBe("expected");+ // A close that leaves the binding down until a person changes a credential or a console+ // setting keeps its place on the dashboard, whatever number it carries.+ expect(+ messagingErrorKind(+ new MessagingConnectionClosedError("gateway connection closed (code 4004)", 4004, false),+ "messaging_connect_failed",+ ),+ ).toBe("unexpected");+ expect(+ messagingErrorKind(+ new MessagingConnectionClosedError("gateway refused this bot", 4914, false),+ "messaging_connect_failed",+ ),+ ).toBe("unexpected");+ // The verdict travels with the type, so it holds wherever the failure is caught.+ expect(+ messagingErrorKind(+ new MessagingConnectionClosedError("gateway connection closed (code 4009)", 4009, true),+ "messaging_inbound_failed",+ ),+ ).toBe("expected");+ // And a plain Error that merely quotes the code is not one: matching on wording would tie+ // the count to how a platform phrases its own close.+ expect(+ messagingErrorKind(+ new Error("gateway connection closed (code 4009)"),+ "messaging_connect_failed",+ ),+ ).toBe("unexpected");+ });});diff --git a/packages/server/test/messaging-qq-transport.test.ts b/packages/server/test/messaging-qq-transport.test.tsindex 07442fbd..1725e7e4 100644--- a/packages/server/test/messaging-qq-transport.test.ts+++ b/packages/server/test/messaging-qq-transport.test.ts@@ -23,9 +23,11 @@ import type {import {QQ_API_BASE,QQ_INTENT_GROUP_AND_C2C,+ MessagingConnectionClosedError,QQApiError,createQQTransport,} from "../src/runtime/messaging/qq-api.js";+import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";import { waitFor } from "./helpers.js";const CREDS: QQCredentials = { appId: "102000001", appSecret: "qq-app-secret-ABCD-1234" };@@ -523,6 +525,96 @@ describe("the QQ gateway session", () => {});});+ it("types every close it reports, and calls only the self-clearing ones recovering", async () => {+ // The dashboard's "needs a human" count is read off `recovers` (error-kind.ts), and the+ // reconnect decision behind it lives here — so the verdict is asserted at the socket+ // rather than on a hand-built error, which would only prove the classifier can read a+ // boolean somebody else typed in.+ const verdictOf = async (code: number): Promise<MessagingConnectionClosedError> => {+ let closed: MessagingConnectionClosedError | undefined;+ await withFetch(defaults, async () => {+ const h = harnessOf();+ const conn = await h.open();+ try {+ handshake(h.sockets[0]!, "gw-1");+ h.sockets[0]!.drop(code);+ await waitFor(() => h.errors.length > 0);+ const err = h.errors[0];+ expect(err).toBeInstanceOf(MessagingConnectionClosedError);+ closed = err as MessagingConnectionClosedError;+ expect(closed.closeCode).toBe(code);+ } finally {+ conn.close();+ }+ });+ return closed!;+ };++ // The platform expiring a long-lived connection, and its own internal-error band: the+ // session is back inside one backoff step with nothing changed anywhere.+ expect((await verdictOf(4009)).recovers).toBe(true);+ expect((await verdictOf(4900)).recovers).toBe(true);+ expect((await verdictOf(4913)).recovers).toBe(true);+ // A rejected token and an intent the bot was never granted reconnect just as eagerly and+ // meet the identical refusal every time, so retrying is not recovery.+ expect((await verdictOf(4004)).recovers).toBe(false);+ expect((await verdictOf(4014)).recovers).toBe(false);+ // A refused session handle recovers only by identifying fresh, which loses whatever+ // arrived in the gap; a delisted bot stops the session outright.+ expect((await verdictOf(4006)).recovers).toBe(false);+ expect((await verdictOf(4007)).recovers).toBe(false);+ expect((await verdictOf(4914)).recovers).toBe(false);+ });++ it("a routine close does not silence the outage that follows it", async () => {+ // One report per outage keeps a backoff loop out of the error table, but a routine close is+ // filed `expected` — so if it kept the slot, a socket the platform expires at 4009 followed+ // by an auth refusal forever would leave the dashboard reading zero defects for a binding+ // that is down until someone changes a credential.+ await withFetch(defaults, async () => {+ const h = harnessOf();+ const conn = await h.open();+ try {+ handshake(h.sockets[0]!, "gw-1");+ h.sockets[0]!.drop(4009);+ await waitFor(() => h.errors.length === 1);+ expect((h.errors[0] as MessagingConnectionClosedError).recovers).toBe(true);++ // The retry meets a refusal that no reconnect clears: it gets its own record.+ await waitFor(() => h.sockets.length === 2);+ h.sockets[1]!.drop(4004);+ await waitFor(() => h.errors.length === 2);+ expect((h.errors[1] as MessagingConnectionClosedError).recovers).toBe(false);++ // And there it stops: the outage has said what it needed to say.+ await waitFor(() => h.sockets.length === 3);+ h.sockets[2]!.drop(4004);+ await settle(40);+ expect(h.errors).toHaveLength(2);+ } finally {+ conn.close();+ }+ });+ });++ it("what the socket reports is what the recorder classifies, with no help in between", async () => {+ // The two halves are each tested against this class; this is the seam. `messagingErrorKind`+ // is handed the object the gateway raised, exactly as bridge.ts hands it over — so wrapping+ // or re-throwing the error anywhere on that path fails here.+ await withFetch(defaults, async () => {+ const h = harnessOf();+ const conn = await h.open();+ try {+ handshake(h.sockets[0]!, "gw-1");+ h.sockets[0]!.drop(4009);+ await waitFor(() => h.errors.length === 1);+ expect(messagingErrorKind(h.errors[0], "messaging_connect_failed")).toBe("expected");+ } finally {+ conn.close();+ }+ });+ });+it("drops a socket that stops acknowledging heartbeats", async () => {await withFetch(defaults, async () => {const h = harnessOf();diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 66466258..51b17dd7 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -123,6 +123,7 @@ import type {UpdateRunResponse,DesktopUpdateStatusResponse,UsageErrorKind,+ UsageErrorsClearResponse,UsageErrorsPage,UsageGranularity,UsageGroupBy,@@ -842,6 +843,23 @@ export const getUsageErrors = (},});+/**+ * Empties the cost center's error table for the filter the panel is showing — the same+ * date/agent pair the reads take, so what goes is what was on screen. Owner only, and errors+ * with no Project attribution are never included. Answers how many rows were deleted.+ */+export const clearUsageErrors = (+ projectId: string,+ params: { from?: string; to?: string; agentId?: string },+) =>+ apiFetch<UsageErrorsClearResponse>(+ `/api/projects/${encodeURIComponent(projectId)}/usage/errors`,+ {+ method: "DELETE",+ query: { from: params.from, to: params.to, agentId: params.agentId },+ },+ );+export const getUsage = (projectId: string,params: {diff --git a/packages/web/src/features/usage/errors-panel.tsx b/packages/web/src/features/usage/errors-panel.tsxindex 8ba10454..6b179393 100644--- a/packages/web/src/features/usage/errors-panel.tsx+++ b/packages/web/src/features/usage/errors-panel.tsx@@ -16,12 +16,51 @@ import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { formatDateTime } from "../../lib/format";import { Badge } from "../../components/ui/badge";+import { ConfirmModal } from "../../components/ui/confirm-modal";+import { toastError, toastSuccess } from "../../components/ui/toast";import { Empty } from "./usage-charts";import { toneInk } from "../../lib/tone";/** The two error categories. */type ErrorKindKey = "unexpected" | "expected";+/** The date/agent filter the panel reads through, and that a clear deletes through. */+export interface ErrorsFilters {+ from?: string;+ to?: string;+ agentId?: string;+}++/**+ * The one sentence the clear confirmation has to get right: exactly which rows will go.+ *+ * The delete is scoped to the filter on screen, so a dialog naming a wider set (the Project's+ * whole history) or a narrower one (this page of rows) would misdescribe what the button does+ * — which is the entire failure a confirmation exists to prevent. Pure and exported so that is+ * asserted directly: this package's vitest runs in `node`, so an opened dialog is not+ * something a test can inspect.+ */+export function errorsClearScopeText(filters: ErrorsFilters, count: number): string {+ const from = filters.from ?? "";+ const to = filters.to ?? "";+ return filters.agentId !== undefined && filters.agentId !== ""+ ? S.usage.errorsClearScopeAgent(count, from, to, filters.agentId)+ : S.usage.errorsClearScope(count, from, to);+}++/**+ * Whether the filter on screen is one a clear may be offered for.+ *+ * Both bounds have to be real dates. A custom range with an emptied date input sends no bound+ * at all, which the route reads as "unbounded on that side" — so the delete would reach past+ * every row the reader saw while the sentence above still promised that records outside the+ * range are kept. Refusing to offer the action is the honest answer; the picker is one click+ * from a range that has both ends.+ */+export function clearableFilter(filters: ErrorsFilters): boolean {+ return Boolean(filters.from) && Boolean(filters.to);+}+/** Copy: S is a runtime live binding (switching language remounts the whole tree), so it must be read at render time. */function kindLabel(key: ErrorKindKey): string {return key === "unexpected" ? S.usage.errorsUnexpected : S.usage.errorsExpected;@@ -84,11 +123,18 @@ function Th({ children, className = "" }: { children: React.ReactNode; className* alone — the table never scrolls vertically (paging is the way past it). Its four columns need* a floor to stay legible, so on a viewport narrower than that floor the table scrolls* sideways inside its own box rather than dragging the page along with it.+ *+ * The footer under the table carries the pager and, for a Project owner, the clear action.+ * Clearing deletes the rows the current filter selects — the set the reader is looking at,+ * not the Project's whole history — and the confirmation says which set that is, because a+ * deleted error record has no other copy anywhere.*/export function ErrorsPanel({errors,projectId,filters,+ canClear,+ onCleared,}: {errors: UsageErrors;projectId: string;@@ -96,9 +142,17 @@ export function ErrorsPanel({* The dashboard's own date/agent filter — a page must never widen what the summary counted.* Memoize it at the call site: the fetch effect depends on the object's identity.*/- filters: { from?: string; to?: string; agentId?: string };+ filters: ErrorsFilters;+ /**+ * Whether this viewer may empty the table (Project owner). A member can read the panel but+ * not clear it, and the route enforces that on its own; hiding the button keeps the panel+ * from offering an action that can only end in a 403.+ */+ canClear: boolean;+ /** Reload the dashboard after a clear — the stats above the table are the caller's data. */+ onCleared: () => void;}) {- const { total, unexpected, topCode, recent } = errors;+ const { total, clearable, unexpected, topCode, recent } = errors;// Page size is read off the first page rather than duplicating the server's ERROR_RECENT_N:// whenever a second page exists at all, `recent` is exactly that many rows, so the two cannot// drift apart into skipping or repeating rows. (Empty means a single empty page anyway.)@@ -155,6 +209,24 @@ export function ErrorsPanel({}, [page, pageSize, projectId, filters, recent, total]);const pageCount = Math.max(1, Math.ceil(pagedTotal / pageSize));+ const [confirmingClear, setConfirmingClear] = useState(false);+ const [clearing, setClearing] = useState(false);++ const runClear = async () => {+ setClearing(true);+ try {+ const res = await api.clearUsageErrors(projectId, filters);+ setConfirmingClear(false);+ toastSuccess(S.usage.errorsClearDone(res.deleted));+ // The stats above the table are the dashboard's own numbers, so the whole response is+ // refetched rather than patched here; that also restores page 0 from the new snapshot.+ onCleared();+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setClearing(false);+ }+ };// 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]);@@ -247,28 +319,68 @@ export function ErrorsPanel({</div>)}- {/* Pager: once there is more than one page — and unconditionally while paged away from- the first, so a later page that came back empty or shrank below the page count still- offers the way back instead of stranding the reader on a bare table. Kept outside the- scroll box so it stays reachable without scrolling to the bottom of the rows. */}- {(pageCount > 1 || page > 0) && (- <div className="mt-2 flex items-center justify-end gap-2 text-xs text-gray-500 dark:text-gray-400">- {pageError !== null && <span className="mr-auto text-rose-500">{pageError}</span>}- <span className="tabular-nums">- {S.usage.errorsPageOf(page + 1, pageCount, pagedTotal)}- </span>- <PagerButton- label={S.usage.errorsNewer}- disabled={page === 0 || loading}- onClick={() => setPage((p) => Math.max(0, p - 1))}- />- <PagerButton- label={S.usage.errorsOlder}- disabled={page + 1 >= pageCount || loading}- onClick={() => setPage((p) => p + 1)}- />+ {/* The table's own footer: the clear action on the left, the pager on the right. It is+ rendered whenever there are rows to act on — and unconditionally while paged away+ from the first page, so a later page that came back empty or shrank below the page+ count still offers the way back instead of stranding the reader on a bare table.+ Kept outside the scroll box so it stays reachable without scrolling past the rows.+ The pager itself still appears only once there is more than one page. */}+ {(items.length > 0 || page > 0) && (+ <div className="mt-2 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">+ {/* Offered on what the clear can really take: `clearable` excludes the unattributed+ rows an admin's read includes but no Project-scoped delete removes, so a window+ holding only those shows no button rather than one that deletes nothing. */}+ {canClear && clearable > 0 && clearableFilter(filters) && (+ <button+ type="button"+ disabled={clearing}+ onClick={() => setConfirmingClear(true)}+ className="rounded-md border border-gray-200 px-2 py-0.5 transition-colors duration-150 hover:border-red-200 hover:bg-red-50 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-gray-200 disabled:hover:bg-transparent disabled:hover:text-gray-500 dark:border-gray-800 dark:hover:border-red-900 dark:hover:bg-red-950/50 dark:hover:text-red-400 dark:disabled:hover:border-gray-800 dark:disabled:hover:bg-transparent dark:disabled:hover:text-gray-400"+ >+ {S.usage.errorsClear}+ </button>+ )}+ {pageError !== null && (+ <span className="text-red-600 dark:text-red-400">{pageError}</span>+ )}+ {(pageCount > 1 || page > 0) && (+ <>+ <span className="ml-auto tabular-nums">+ {S.usage.errorsPageOf(page + 1, pageCount, pagedTotal)}+ </span>+ <PagerButton+ label={S.usage.errorsNewer}+ disabled={page === 0 || loading}+ onClick={() => setPage((p) => Math.max(0, p - 1))}+ />+ <PagerButton+ label={S.usage.errorsOlder}+ disabled={page + 1 >= pageCount || loading}+ onClick={() => setPage((p) => p + 1)}+ />+ </>+ )}</div>)}++ {/* The confirm names the filtered set the delete will actually take, and says plainly+ that nothing brings it back — the rows are the only record these errors ever had. */}+ <ConfirmModal+ open={confirmingClear}+ tone="danger"+ title={S.usage.errorsClearTitle}+ confirmLabel={S.usage.errorsClear}+ busy={clearing}+ onClose={() => setConfirmingClear(false)}+ onConfirm={() => void runClear()}+ >+ <div className="space-y-1.5 text-sm text-gray-700 dark:text-gray-300">+ <p className="break-words">{errorsClearScopeText(filters, clearable)}</p>+ <p className="text-xs text-gray-500 dark:text-gray-400">+ {S.usage.errorsClearIrreversible}+ </p>+ </div>+ </ConfirmModal></div>);}diff --git a/packages/web/src/features/usage/usage-page.tsx b/packages/web/src/features/usage/usage-page.tsxindex 876be6d4..fdff3ec6 100644--- a/packages/web/src/features/usage/usage-page.tsx+++ b/packages/web/src/features/usage/usage-page.tsx@@ -34,6 +34,7 @@ import { apiErrorText } from "../../lib/api-error";import { useDocumentTitle } from "../../lib/use-document-title";import { useUpdateBadges } from "../../lib/use-update-badges";import { dismissTodo } from "../../lib/todo-dismissals";+import { refreshProjectTodos } from "../../lib/use-project-todos";import { TodoNotice } from "../../components/ui/todo-notice";import { formatMoney, humanizeTokens } from "../../lib/format";import { catalogEntryFor } from "@prismshadow/penguin-core/model-catalog";@@ -168,6 +169,17 @@ export function UsagePage() {setTo(nextTo);};const [data, setData] = useState<UsageResponse | null>(null);+ /**+ * The date window the dashboard actually READ, which is not always the one the picker holds.+ * A trailing preset computes its window at load time and deliberately leaves `from`/`to` on+ * whatever the last calendar preset put there, so the two diverge the moment "last hour" is+ * chosen. The error panel pages against this window and, for an owner, DELETES against it —+ * so it has to be the window whose rows are on screen, never the stale pair behind them.+ * Kept as two primitives so the memo below holds its identity across a reload that changes+ * nothing (the panel's fetch effect depends on that identity).+ */+ const [loadedFrom, setLoadedFrom] = useState(from);+ const [loadedTo, setLoadedTo] = useState(to);const [error, setError] = useState<string | null>(null);// The legend / control state that lives in the card headers (ChartCard's// extra) while the marks live inside the cards, lifted to this level.@@ -192,6 +204,8 @@ export function UsagePage() {...(modelFilter ? { provider: modelFilter.provider, modelId: modelFilter.modelId } : {}),});setData(res);+ setLoadedFrom(range.from);+ setLoadedTo(range.to);} catch (e) {setError(apiErrorText(e));}@@ -205,10 +219,12 @@ export function UsagePage() {// The error panel pages against this filter and depends on the object's identity, so it is// built once per filter value rather than fresh on every render — a new object each render// would refetch the current page on any unrelated state change (hovering a chart bucket).+ // Built from the window the dashboard read (see loadedFrom/loadedTo), not from the picker's+ // state: the panel's rows, its later pages and its clear all have to name one same set.// The model filter is deliberately absent: it never applied to errors.const errorFilters = useMemo(- () => ({ from, to, ...(agentFilter ? { agentId: agentFilter } : {}) }),- [from, to, agentFilter],+ () => ({ from: loadedFrom, to: loadedTo, ...(agentFilter ? { agentId: agentFilter } : {}) }),+ [loadedFrom, loadedTo, agentFilter],);if (!projectId) return null;@@ -413,7 +429,21 @@ export function UsagePage() {{/* Errors (a single full-width panel: stats + a recent-errors table) */}{data && (<ChartCard title={S.usage.errors}>- <ErrorsPanel errors={data.errors} projectId={projectId} filters={errorFilters} />+ <ErrorsPanel+ errors={data.errors}+ projectId={projectId}+ filters={errorFilters}+ // 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 badge and the notice above are gated on a probe cached per Project for the+ // browser session, not on this response — without the re-probe an emptied table+ // would sit under a dot still pointing at the rows that just went.+ onCleared={() => {+ refreshProjectTodos(projectId);+ void load();+ }}+ /></ChartCard>)}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 784ff525..8b844168 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -2137,6 +2137,16 @@ Scenarios:errorsOlder: "Older",errorsPageOf: (page: number, pages: number, total: number) =>`Page ${page} / ${pages} · ${total} total`,+ /** Clearing the table: the action, and the confirm that must name exactly what goes. */+ errorsClear: "Clear",+ errorsClearTitle: "Clear error records",+ errorsClearScope: (count: number, from: string, to: string): string =>+ `Deletes this Project's ${count} error record${count === 1 ? "" : "s"} between ${from} and ${to}. Records outside that range are kept.`,+ errorsClearScopeAgent: (count: number, from: string, to: string, agentId: string): string =>+ `Deletes this Project's ${count} error record${count === 1 ? "" : "s"} for agent ${agentId} between ${from} and ${to}. Other agents and other dates are kept.`,+ errorsClearIrreversible: "This cannot be undone.",+ errorsClearDone: (count: number): string =>+ `Deleted ${count} error record${count === 1 ? "" : "s"}`,},/** 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.tsindex 9a673f3c..564a85bc 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -2090,6 +2090,15 @@ Benchmark:errorsOlder: "更早",errorsPageOf: (page: number, pages: number, total: number) =>`第 ${page} / ${pages} 页 · 共 ${total} 条`,+ /** Clearing the table: the action, and the confirm that must name exactly what goes. */+ errorsClear: "清空",+ errorsClearTitle: "清空错误记录",+ errorsClearScope: (count: number, from: string, to: string): string =>+ `将删除本 Project 在 ${from} 至 ${to} 区间内的 ${count} 条错误记录,其余时间段的记录保留。`,+ errorsClearScopeAgent: (count: number, from: string, to: string, agentId: string): string =>+ `将删除本 Project 中 Agent「${agentId}」在 ${from} 至 ${to} 区间内的 ${count} 条错误记录,其他 Agent 与其余时间段的记录保留。`,+ errorsClearIrreversible: "此操作不可恢复。",+ errorsClearDone: (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.tsnew file mode 100644index 00000000..41954828--- /dev/null+++ b/packages/web/test/errors-panel.test.ts@@ -0,0 +1,125 @@+/**+ * The cost center's error table and its clear action.+ *+ * Two properties a type checker cannot see. The action is offered only where it can succeed —+ * the route is owner-only, so showing it to a member would be an affordance whose only outcome+ * is a 403 — and only while there are rows to take.+ *+ * 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.+ */+import { afterEach, describe, expect, it } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import type { UsageErrorItem, UsageErrors } from "@prismshadow/penguin-server/api";+import { ErrorsPanel, errorsClearScopeText } from "../src/features/usage/errors-panel";+import type { ErrorsFilters } from "../src/features/usage/errors-panel";+import { S, setActiveStrings, zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";++afterEach(() => setActiveStrings(zh));++const item = (code: string): UsageErrorItem => ({+ ts: "2026-08-27T10:00:00.000Z",+ source: "http",+ code,+ kind: "unexpected",+ message: `${code} went wrong`,+});++function errorsOf(items: UsageErrorItem[], clearable = items.length): UsageErrors {+ return {+ total: items.length,+ clearable,+ unexpected: items.length,+ topCode: null,+ recent: items,+ };+}++const FILTERS: ErrorsFilters = { from: "2026-08-01", to: "2026-08-27" };++function render(+ opts: {+ items?: UsageErrorItem[];+ clearable?: number;+ canClear?: boolean;+ filters?: ErrorsFilters;+ } = {},+): string {+ const items = opts.items ?? [item("internal")];+ return renderToStaticMarkup(+ createElement(ErrorsPanel, {+ errors: errorsOf(items, opts.clearable ?? items.length),+ projectId: "p1",+ filters: opts.filters ?? FILTERS,+ canClear: opts.canClear ?? true,+ onCleared: () => {},+ }),+ );+}++describe("ErrorsPanel clear action", () => {+ it("is offered to the Project owner only", () => {+ expect(render({ canClear: true })).toContain(S.usage.errorsClear);+ // A member reads the panel; the route refuses the delete, so the button is not there to+ // promise otherwise.+ expect(render({ canClear: false })).not.toContain(S.usage.errorsClear);+ });++ it("is absent while the filtered table is empty", () => {+ const empty = render({ items: [] });+ expect(empty).toContain(S.usage.errorsEmpty);+ expect(empty).not.toContain(S.usage.errorsClear);+ });++ it("is absent when every row in range is one no Project-scoped clear can take", () => {+ // An admin's read includes unattributed rows (a login failure, a process crash); the delete+ // never does. A window holding only those has rows on screen and nothing to clear, so the+ // action must not be offered — it could only report "deleted 0".+ expect(render({ items: [item("uncaught_exception")], clearable: 0 })).not.toContain(+ S.usage.errorsClear,+ );+ });++ it("is absent while a date bound is blank: the sentence could not describe that delete", () => {+ // A cleared date input sends no bound, which the route reads as unbounded on that side —+ // wider than anything the confirmation's "records outside that range are kept" can promise.+ expect(render({ filters: { from: "", to: "2026-08-27" } })).not.toContain(S.usage.errorsClear);+ });++ it("keeps the pager independent of it: rows but one page shows the action alone", () => {+ const onePage = render({ items: [item("internal")] });+ expect(onePage).toContain(S.usage.errorsClear);+ expect(onePage).not.toContain(S.usage.errorsOlder);+ });+});++describe("errorsClearScopeText", () => {+ for (const [locale, dict] of Object.entries({ zh, en })) {+ it(`${locale}: names the date range, and the Agent when one is selected`, () => {+ setActiveStrings(dict);+ const ranged = errorsClearScopeText(FILTERS, 12);+ expect(ranged).toContain("2026-08-01");+ expect(ranged).toContain("2026-08-27");+ expect(ranged).toContain("12");+ // No Agent filter: the sentence must not claim one, or it describes a narrower delete+ // than the one about to run.+ expect(ranged).not.toContain("agent-7");++ const perAgent = errorsClearScopeText({ ...FILTERS, agentId: "agent-7" }, 3);+ expect(perAgent).toContain("agent-7");+ expect(perAgent).toContain("2026-08-01");+ expect(perAgent).toContain("3");+ });+ }++ it("an empty agentId is no filter at all (the panel's own spelling of 'all agents')", () => {+ expect(errorsClearScopeText({ ...FILTERS, agentId: "" }, 4)).toBe(+ errorsClearScopeText(FILTERS, 4),+ );+ });+});