A local-first multi-agent app development platform, built on PenguinHarness
fix(server,web): the error center folds a day's repeats into one counted row, and messaging failures that recover on their own are expected (#908)
Yaowei Zhengb17b7af14496
diff --git a/changelog/unreleased/2026-09-30-error-center-grouping.md b/changelog/unreleased/2026-09-30-error-center-grouping.mdnew file mode 100644index 00000000..30ddce1b--- /dev/null+++ b/changelog/unreleased/2026-09-30-error-center-grouping.md@@ -0,0 +1,20 @@+# The error center folds a day's repeats into one counted row, and messaging failures that recover on their own are expected++- **Date:** 2026-09-30+- **Type:** fix+- **Scope:** `server`, `web`, `docs`+- **PR:** [#908](https://github.com/Prism-Shadow/penguin-harness/pull/908)++[中文版](2026-09-30-error-center-grouping.zh.md)++The cost center's error table folded the records of one day that share a source, code, kind and message into one row that says how many there were, and the messaging connection and send failures that clear on their own were filed as `expected` instead of `unexpected`.++## Details++- **One row per error per day.** `GET /usage` and `GET /usage/errors` took an optional `utcOffsetMinutes`, the reader's offset east of UTC, which the Web App sends from the browser, and the error table folded its records by the reader's calendar day, source, code, kind and message. Each row (`UsageErrorItem`) carried `count`, its latest time `ts` and its first time `firstTs`, newest first. Paging counted rows, and both responses gained `rows`, the row count, while `total`, the unexpected count and the most common code kept counting records. Without an offset the day was the server's own. Clearing still deleted records, and the recorder's short-window dedup and row cap were unchanged.+- **The panel.** A row standing for several records showed a small muted "×N" after its message, its time was the latest one and its tooltip gave the first, and the pager counted rows ("25 rows").+- **A verdict on each connection and send failure.** `MessagingChannelError`, on the connector seam, carried `recovers`, decided where a failure is read. The Telegram, QQ and WeChat transports marked a request that never completed and an HTTP 408, 429 or 5xx as recovering, and WeChat also its `-14` session timeout and any refusal after its credential passed, such as a send's "prepare failed". The QQ gateway added its handshake timeout, heartbeat loss, a reconnect the platform asked for, and the transport closes 1001, 1006 and 1011–1014 to 4009 and 4900–4913. `TelegramApiError`, `QQApiError`, `WeChatApiError` and `MessagingConnectionClosedError` became kinds of it.+- **The classification.** `messagingErrorKind` filed a failure at `messaging_connect_failed` or `messaging_send_failed` as `expected` when its verdict recovers, and as `unexpected` otherwise, untyped failures included. A rejected credential, a missing permission, a Telegram webhook or second poller (409), a chat that blocked the bot and QQ's reply budget stayed `unexpected`. The other capture points kept their rules, and Feishu, whose long connection reports only once its SDK has given up, gained no verdict.+- **One report per outage.** Telegram's and WeChat's poll loops took the QQ gateway's rule: a failure that recovers does not use up the outage's one report, so the first failure after it that does not recover is filed as well.+- **Existing records.** Rows already in the table kept the kind they were filed with.+- **Docs.** The Cost Center and Server API pages described the folded rows, `utcOffsetMinutes` and `rows`, and how connection and send failures are classified.diff --git a/changelog/unreleased/2026-09-30-error-center-grouping.zh.md b/changelog/unreleased/2026-09-30-error-center-grouping.zh.mdnew file mode 100644index 00000000..849d9cdf--- /dev/null+++ b/changelog/unreleased/2026-09-30-error-center-grouping.zh.md@@ -0,0 +1,20 @@+# 异常中心把同一天的重复记录合为一行并计数,能自行恢复的消息渠道失败记为预期内++- **Date:** 2026-09-30+- **Type:** fix+- **Scope:** `server`, `web`, `docs`+- **PR:** [#908](https://github.com/Prism-Shadow/penguin-harness/pull/908)++[English](2026-09-30-error-center-grouping.md)++成本中心的异常表把同一天里来源、错误码、分类和消息都相同的记录合为一行,并标出条数;消息渠道里能自行恢复的连接失败与发送失败改记为 `expected`,不再记为 `unexpected`。++## 细节++- **每天每种异常一行。** `GET /usage` 与 `GET /usage/errors` 新增可选参数 `utcOffsetMinutes`,即读者所在时区相对 UTC 向东的分钟数,Web App 按浏览器的时区传入;异常表按读者的自然日、来源、错误码、分类和消息折叠记录。每一行(`UsageErrorItem`)带上 `count`、最近一次的时间 `ts` 和首次的时间 `firstTs`,按最近一次倒序。分页按行计,两个响应都新增了行数 `rows`,而 `total`、未预期数量和最常见错误码仍按记录计。不传偏移时按服务器自己的日期。清空仍按记录删除,记录器的短窗去重与行数上限不变。+- **面板。** 代表多条记录的行在消息后以小号灰字标出「×N」,时间显示最近一次、悬停给出首次,分页按行计数(「共 25 行」)。+- **每个连接失败与发送失败都带判定。** 连接器接缝上的 `MessagingChannelError` 带有 `recovers`,由读懂这次失败的地方给出。Telegram、QQ 与微信的传输层把请求根本没有完成、HTTP 408、429 或 5xx 判为会恢复;微信另把 `-14` 会话超时和凭据通过之后的任何拒绝(如发送时的「prepare failed」)判为会恢复。QQ 网关在 4009 与 4900–4913 之外,又加上握手超时、心跳失联、平台要求的重连,以及传输层关闭 1001、1006 与 1011–1014。`TelegramApiError`、`QQApiError`、`WeChatApiError` 与 `MessagingConnectionClosedError` 都成为它的子类型。+- **分类。** `messagingErrorKind` 在 `messaging_connect_failed` 与 `messaging_send_failed` 两个捕获点上,判定会恢复的失败记为 `expected`,其余记为 `unexpected`,没有类型的失败也在其中。被拒的凭据、缺少权限、Telegram 的 webhook 或另一个轮询程序(409)、屏蔽了机器人的聊天以及 QQ 的回复额度仍为 `unexpected`。其他捕获点的规则不变;飞书的长连接只在 SDK 放弃重连后才上报,没有加判定。+- **一次故障一条记录。** Telegram 与微信的轮询循环沿用 QQ 网关的规则:会恢复的失败不占住这次故障唯一的记录名额,随后第一个不会恢复的失败同样会记录。+- **既有记录。** 表中已有的行保留写入时的分类。+- **文档。** 「成本中心」与「Server API」两个页面说明了折叠后的行、`utcOffsetMinutes` 与 `rows`,以及连接失败与发送失败如何分类。diff --git a/packages/cli/test/fake-server.ts b/packages/cli/test/fake-server.tsindex 436ff82a..e6be1a63 100644--- a/packages/cli/test/fake-server.ts+++ b/packages/cli/test/fake-server.ts@@ -210,7 +210,7 @@ export class FakeServer {series: [],byAgentSeries: [],byModelSeries: [],- errors: { total: 0, unexpected: 0, topCode: null, recent: [] },+ errors: { total: 0, unexpected: 0, topCode: null, recent: [], rows: 0 },agentIds: [],models: [],};diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 6f0dc127..93f07149 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -637,7 +637,7 @@ The paths below omit the `/api/projects/:projectId` prefix.| --- | --- | --- || GET | `/usage` | Usage statistics || GET | `/usage/model-totals` | Lifetime Token total per model; takes no filters |-| GET | `/usage/errors` | One page of the error detail table, newest first: → `{items, total}` |+| GET | `/usage/errors` | One page of the error detail table, newest first: → `{items, total, rows}` || DELETE | `/usage/errors` | Empties the error table for the current filter: → `{deleted}` (Project owner only) || GET | `/agents/:agentId/traces` | Trace files as a date → Session drill-down || GET | `/agents/:agentId/traces/:sessionId/:index` | Reads Trace events (`offset` / `limit` pagination) |@@ -656,6 +656,7 @@ The paths below omit the `/api/projects/:projectId` prefix.| `agentId`, `provider`, `modelId` | Filters |- `GET /usage/errors` takes `offset`, `limit`, the same `from` / `to` / `fromTs` / `toTs` / `agentId` filter, and an optional `kind` (`unexpected` or `expected`).+- The error table folds the records of one day that share a source, code, kind and message into one row, with its `count`, its latest time `ts` and its first time `firstTs`. `offset`, `limit` and `rows` count those rows; `total` and the dashboard's summary figures count records. `GET /usage` and `GET /usage/errors` take an optional `utcOffsetMinutes`, the reader's offset east of UTC (−840 to 840), which decides the day; without it the day is the server's own.- `DELETE /usage/errors` takes the same filter as the reads, `from` / `to` / `fromTs` / `toTs` / `agentId`, but no `kind`, because the panel offers no such control. `from` and `to` are both required here (400 otherwise), because an open bound would clear the whole history rather than a filtered part. The clear reaches exactly what the caller's reads reach: an admin's clear also removes the unattributed rows that only an admin's read shows, and a member's clear never does.- `GET /agents/:agentId/traces` also accepts `limit` and `offset` for paging, and `category` (which requires `limit`) to list one category of Sessions.- Any member can download a Trace. Import is owner only, like the Agent State snapshot import, and capped at 14MB. The imported file must be valid Trace JSONL whose first record is a `session_meta` with a filename-safe `session_id`. A session id the agent already has is rejected (409 `trace_session_exists`), so an imported file always becomes index 001 of a new Session, stored in the local date directory of its first record's timestamp.@@ -1003,6 +1004,8 @@ Besides its state, a binding's runtime status reports what the live connection hAll three live in the server process and reset on every connect or reconnect, and re-enabling the channel or saving credentials opens a new connection. An absent `lastInboundAt` therefore means "nothing since this connection opened", never "nothing ever". These fields exist because a channel that withholds messages still shows `connected` with no error.+A connection failure is also filed as an error record, `messaging_connect_failed`, once per outage, and a reply that never reached the chat as `messaging_send_failed`. On Telegram, QQ and WeChat both are `expected` when the next attempt clears them by itself: a request that never completed, a timeout, HTTP 408, 429 or 5xx, a QQ gateway that stopped answering heartbeats or asked to reconnect, or WeChat's session timeout. They are `unexpected` when they repeat until someone acts, such as a rejected credential, a missing permission, or a webhook or a second poller on a Telegram bot. When an outage starts with an `expected` failure, the first `unexpected` one after it is filed too.+## TerminalsInteractive shells on the server host. The Web App's terminals use these routes, and so can any client that needs to run a command and read the screen. Each terminal belongs to the user who opened it, and the other routes only find the caller's own terminals.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex ad057767..448268b9 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -637,7 +637,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估| --- | --- | --- || GET | `/usage` | 用量统计 || GET | `/usage/model-totals` | 每个模型的历史累计 Token 总量;不接受任何过滤参数 |-| GET | `/usage/errors` | 错误详情表的一页,按时间倒序:→ `{items, total}` |+| GET | `/usage/errors` | 错误详情表的一页,按时间倒序:→ `{items, total, rows}` || DELETE | `/usage/errors` | 按当前过滤条件清空错误表:→ `{deleted}`(仅限 Project 所有者) || GET | `/agents/:agentId/traces` | Trace 文件,按日期 → Session 逐级下钻 || GET | `/agents/:agentId/traces/:sessionId/:index` | 读取 Trace 事件(`offset` / `limit` 分页) |@@ -656,6 +656,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估| `agentId`、`provider`、`modelId` | 过滤条件 |- `GET /usage/errors` 接受 `offset`、`limit`、同样的 `from` / `to` / `fromTs` / `toTs` / `agentId` 过滤条件,以及可选的 `kind`(`unexpected` 或 `expected`)。+- 错误表把同一天里来源、错误码、分类和消息都相同的记录合为一行,带上次数 `count`、最近一次的时间 `ts` 和首次的时间 `firstTs`。`offset`、`limit` 和 `rows` 按行计;`total` 和仪表盘的汇总数字按记录计。`GET /usage` 与 `GET /usage/errors` 都接受可选的 `utcOffsetMinutes`,即读者所在时区相对 UTC 向东的分钟数(−840 到 840),它决定「同一天」按哪一天算;不传时按服务器自己的日期。- `DELETE /usage/errors` 接受与读取相同的过滤条件(`from` / `to` / `fromTs` / `toTs` / `agentId`),但不接受 `kind`,因为面板上没有这个控件。这里 `from` 和 `to` 都必填(否则返回 400),因为少一个边界,清空的就是整段历史,而不是过滤后的一部分。清空的范围与调用者读取的范围完全一致:管理员清空时,也会删掉只有管理员读取才能看到的未归属行;成员清空时则永远不会。- `GET /agents/:agentId/traces` 还接受 `limit` 和 `offset` 分页,以及 `category`(必须搭配 `limit`),用于只列出某一类别的 Session。- 任何成员都可以下载 Trace。导入只有所有者能做,与 Agent State 快照导入一样,上限 14MB。导入的文件必须是有效的 Trace JSONL,首条记录必须是 `session_meta`,`session_id` 须可安全用作文件名。session id 与 Agent 已有的重复时拒绝导入(409 `trace_session_exists`),所以导入的文件总是成为新 Session 的 index 001,按首条记录的时间戳存入对应的本地日期目录。@@ -1003,6 +1004,8 @@ Telegram 连接时会先清空积压,跳过无连接期间发送的消息。这三个字段都保存在服务器进程中,每次连接或重连都会重置;重新启用渠道或保存凭据都会开启新连接。因此 `lastInboundAt` 缺失意味着「本次连接建立以来没有消息」,绝不是「从来没有过消息」。提供这些字段,是因为一个扣着消息不投递的渠道,照样显示 `connected`,而且没有任何报错。+连接失败还会记一条错误记录 `messaging_connect_failed`,每次故障一条;从未到达聊天的回复记为 `messaging_send_failed`。在 Telegram、QQ 和微信上,下一次尝试就能自行解决的失败属于 `expected`:请求根本没有完成、超时、HTTP 408、429 或 5xx、QQ 网关不再响应心跳或要求重连,以及微信的会话超时。会一直重复、直到有人处理的失败属于 `unexpected`,例如凭据被拒、缺少权限,或者 Telegram 机器人上登记了 webhook、另有程序在轮询同一个机器人。一次故障以 `expected` 的失败开头时,随后第一个 `unexpected` 的失败也会记录。+## 终端服务器主机上的交互式 shell。Web App 的终端使用这些路由,任何需要运行命令并读取屏幕的客户端也可以使用。每个终端属于打开它的用户,其余路由只能找到调用者自己的终端。diff --git a/packages/docs/content/usage.en.md b/packages/docs/content/usage.en.mdindex 518f4ae5..90f3999c 100644--- a/packages/docs/content/usage.en.md+++ b/packages/docs/content/usage.en.md@@ -61,6 +61,7 @@ The **Errors** panel at the bottom of the page shows the errors the server recor- Summary figures: **Total**, **Unexpected**, **Expected** and the **Most common** error code.- A table of errors with their time, **Source · code**, **Type** and **Message**. Click a message to expand its full text. The table shows 10 rows a page and pages with **Newer** and **Older** instead of scrolling.+- The same error recorded more than once on one day shares a row. The time is the latest one, hover it for the first, and ×N after the message counts the records. The summary figures count every record.The model filter does not apply to this panel.diff --git a/packages/docs/content/usage.zh.md b/packages/docs/content/usage.zh.mdindex cbc428a0..df9a5fa8 100644--- a/packages/docs/content/usage.zh.md+++ b/packages/docs/content/usage.zh.md@@ -60,7 +60,8 @@ description: 按 Agent、模型和时间范围查看 Token 用量、成本与服页面底部的**异常**面板展示服务器记录的异常:- 汇总数字:**总数**、**未预期**、**预期内**和**最常见**的错误码。-- 异常明细表:时间、**来源 · 错误码**、**类型**和**消息**。点击消息可展开全文。每页 10 条,用**较新**和**更早**翻页,不滚动。+- 异常明细表:时间、**来源 · 错误码**、**类型**和**消息**。点击消息可展开全文。每页 10 行,用**较新**和**更早**翻页,不滚动。+- 同一天里多次记录的同一个异常合为一行:时间显示最近一次,悬停可看到首次;消息后的 ×N 是记录的条数。汇总数字按每条记录计。模型筛选对这个面板不起作用。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 90cecef1..6afd4b70 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -3257,13 +3257,22 @@ export interface UsageErrorCount {count: number;}-/** A single error summary (one row in the stats center's error panel table). */+/**+ * One row of the stats center's error panel table: the records of one calendar day that share+ * a source, code, kind and message. The day is the viewer's when the request carried+ * `utcOffsetMinutes`, and the server's own otherwise.+ */export interface UsageErrorItem {+ /** The latest of the records this row stands for. */ts: string;source: string;code: string;kind: string;message: string;+ /** How many records this row stands for (the panel's "×N"). */+ count: number;+ /** The earliest of them; equal to `ts` for a single record. */+ firstTs: string;}/**@@ -3275,14 +3284,16 @@ export interface UsageErrorItem {* items.*/export interface UsageErrors {- /** Filtered row count — also what a clear of the same filter takes (see {@link UsageErrorsClearResponse}). */+ /** Filtered record count — also what a clear of the same filter takes (see {@link UsageErrorsClearResponse}). */total: 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). */topCode: UsageErrorCount | null;- /** Most recent N items (reverse chronological) — the first page; older ones come from `GET /usage/errors`. */+ /** Most recent N rows (reverse chronological) — the first page; older ones come from `GET /usage/errors`. */recent: UsageErrorItem[];+ /** How many rows the table has for this filter (records folded per {@link UsageErrorItem}) — what the pager counts. */+ rows: number;}/**@@ -3293,12 +3304,15 @@ export interface UsageErrors {* or neither), so a page never widens what the summary counted, plus an optional `kind`* ({@link UsageErrorKind}) narrowing to one of the two categories — which* is how the cost-center badge asks "are there unexpected errors, and how new is the newest"- * with `limit=1` instead of pulling the whole dashboard aggregate.+ * with `limit=1` instead of pulling the whole dashboard aggregate. `utcOffsetMinutes` (minutes+ * east of UTC, the dashboard takes it too) says whose calendar day a row's records share.*/export interface UsageErrorsPage {items: UsageErrorItem[];- /** Filtered row count, so the caller knows when it has reached the end. */+ /** Filtered record count — the occurrences, which is what the cost-center badge counts. */total: number;+ /** Filtered row count (records folded per {@link UsageErrorItem}), so the caller knows when it has reached the end. */+ rows: number;}/**diff --git a/packages/server/src/db/repos/errors.ts b/packages/server/src/db/repos/errors.tsindex 331fe33a..7460141f 100644--- a/packages/server/src/db/repos/errors.ts+++ b/packages/server/src/db/repos/errors.ts@@ -81,13 +81,38 @@ export interface ErrorCodeCount {count: number;}-/** One error summary row (a row in the error panel's table). */+/**+ * One row of the error panel's table: the records of one calendar day that share a source,+ * code, kind and message (see ErrorsRepo.recent).+ */export interface ErrorItem {+ /** The latest of the records this row stands for. */ts: string;source: string;code: string;kind: string;message: string;+ /** How many records this row stands for. */+ count: number;+ /** The earliest of them (equal to `ts` for a single record). */+ firstTs: string;+}++/**+ * 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.+ * The offset is bound rather than spliced in, as the modifier `date()` takes.+ */+function dayOf(utcOffsetMinutes: number | undefined): {+ sql: string;+ params: Record<string, string>;+} {+ if (utcOffsetMinutes === undefined) return { sql: "date", params: {} };+ const sign = utcOffsetMinutes >= 0 ? "+" : "-";+ return {+ sql: "date(ts, :dayShift)",+ params: { dayShift: `${sign}${Math.abs(utcOffsetMinutes)} minutes` },+ };}@Component()@@ -210,25 +235,61 @@ export class ErrorsRepo implements ErrorLog {};}- /** The most recent `limit` entries (reverse chronological order). */- recent(projectId: string, f: ErrorFilter = {}, limit = 20, offset = 0): ErrorItem[] {+ /**+ * One page of the table, newest first: the records of one calendar day that share a source,+ * code, kind and message fold into a single row, with how many there were and the first and+ * last time among them.+ *+ * A failure that comes back all day — a connection that drops and recovers every few+ * minutes, a send that fails whenever it is asked — reads as one line saying how often,+ * rather than a page of the same line; `summary` and `topCode` still count records, which is+ * what measures how often. The day is `utcOffsetMinutes`'s (see dayOf), so the boundary falls+ * at the viewer's midnight. Rows are ordered by their newest record, and a page is `limit`+ * rows, not records.+ */+ recent(+ projectId: string,+ f: ErrorFilter = {},+ limit = 20,+ offset = 0,+ utcOffsetMinutes?: number,+ ): ErrorItem[] {const { where, params } = this.conds(projectId, f);+ const day = dayOf(utcOffsetMinutes);const rows = this.db.prepare(- `SELECT ts, source, code, kind, message+ `SELECT MAX(ts) AS ts, MIN(ts) AS first_ts, COUNT(*) AS count, source, code, kind, messageFROM error_records WHERE ${where}- ORDER BY id DESC LIMIT :limit OFFSET :offset`,+ GROUP BY ${day.sql}, source, code, kind, message+ ORDER BY MAX(id) DESC LIMIT :limit OFFSET :offset`,)- .all({ ...params, limit, offset });+ .all({ ...params, ...day.params, limit, offset });return rows.map((r) => ({ts: r.ts as string,source: r.source as string,code: r.code as string,kind: r.kind as string,message: r.message as string,+ count: r.count as number,+ firstTs: r.first_ts as string,}));}+ /** How many rows `recent` pages through for the same filter and day — what a pager counts. */+ rowCount(projectId: string, f: ErrorFilter = {}, utcOffsetMinutes?: number): number {+ const { where, params } = this.conds(projectId, f);+ const day = dayOf(utcOffsetMinutes);+ const row = this.db+ .prepare(+ `SELECT COUNT(*) AS n FROM (+ SELECT 1 FROM error_records WHERE ${where}+ GROUP BY ${day.sql}, source, code, kind, message+ )`,+ )+ .get({ ...params, ...day.params })!;+ return row.n as number;+ }+/*** Deletes the rows a matching read would have returned, and answers how many went.*diff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.tsindex 3fd9c8ee..d547f5c0 100644--- a/packages/server/src/http/routes/usage.ts+++ b/packages/server/src/http/routes/usage.ts@@ -7,7 +7,8 @@* together);* GET /api/projects/:p/usage/errors?offset&limit&from&to&fromTs&toTs&agentId&kind — one page* of the error detail table, for paging back past the first page the dashboard already- * returns;+ * 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&agentId — empties that table for* the filter the panel is showing (owner only; `from`/`to` are required, unlike on the reads;* an admin's clear also takes the unattributed rows an admin's read shows);@@ -51,6 +52,26 @@ function optionalTsParam(value: string | undefined, label: string): string | undreturn new Date(ms).toISOString();}+/** The widest offset from UTC a clock actually uses (UTC+14), which bounds `utcOffsetMinutes`. */+const UTC_OFFSET_MAX_MINUTES = 14 * 60;++/**+ * The optional viewer offset east of UTC, in minutes: whose calendar day the error table folds+ * a day's repeats by (see ErrorsRepo.recent). A signed whole number within the offsets clocks+ * use, and nothing else — a typo is a 400 rather than a quietly different day.+ */+function utcOffsetQuery(c: Context<AppEnv>): number | undefined {+ const raw = c.req.query("utcOffsetMinutes");+ if (raw === undefined || raw === "") return undefined;+ const minutes = /^-?\d{1,4}$/.test(raw) ? Number(raw) : Number.NaN;+ if (!(Math.abs(minutes) <= UTC_OFFSET_MAX_MINUTES)) {+ throw badRequest(+ `utcOffsetMinutes must be a whole number of minutes between -${UTC_OFFSET_MAX_MINUTES} and ${UTC_OFFSET_MAX_MINUTES}.`,+ );+ }+ return minutes;+}+/*** The optional trailing-window pair, normalized: both or neither, and in order. One parser* for the dashboard and the two error routes, so a window means the same thing to all three.@@ -86,6 +107,7 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {const from = optionalDateParam(c.req.query("from"), "from");const to = optionalDateParam(c.req.query("to"), "to");const window = tsWindowQuery(c);+ const utcOffsetMinutes = utcOffsetQuery(c);const agentId = c.req.query("agentId");const provider = c.req.query("provider");const modelId = c.req.query("modelId");@@ -94,6 +116,7 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {groupBy: groupByRaw as UsageGroupBy,granularity,...window,+ ...(utcOffsetMinutes !== undefined ? { utcOffsetMinutes } : {}),// Unattributed errors (login failures, process crashes, etc. with no Project// context) are visible only to admins: requireProjectAccess only guarantees// "is a member of this Project" — a regular member seeing another tenant's errors@@ -130,6 +153,7 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {const from = optionalDateParam(c.req.query("from"), "from");const to = optionalDateParam(c.req.query("to"), "to");const window = tsWindowQuery(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@@ -152,6 +176,7 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {...(from !== undefined ? { from } : {}),...(to !== undefined ? { to } : {}),...window,+ ...(utcOffsetMinutes !== undefined ? { utcOffsetMinutes } : {}),...(agentId !== undefined && agentId !== "" ? { agentId } : {}),...(kindRaw !== undefined && kindRaw !== "" ? { kind: kindRaw } : {}),}),diff --git a/packages/server/src/mechanisms/observability.ts b/packages/server/src/mechanisms/observability.tsindex fca4fbc7..f31d13fc 100644--- a/packages/server/src/mechanisms/observability.ts+++ b/packages/server/src/mechanisms/observability.ts@@ -66,7 +66,14 @@ export abstract class ErrorLog extends Interface<{insert(r: ErrorRecordInsert): void;summary(projectId: string, f?: ErrorFilter): ErrorSummary;topCode(projectId: string, f?: ErrorFilter): ErrorCodeCount | null;- recent(projectId: string, f?: ErrorFilter, limit?: number, offset?: number): ErrorItem[];+ recent(+ projectId: string,+ f?: ErrorFilter,+ limit?: number,+ offset?: number,+ utcOffsetMinutes?: number,+ ): ErrorItem[];+ rowCount(projectId: string, f?: ErrorFilter, utcOffsetMinutes?: number): number;deleteFiltered(projectId: string, f?: Omit<ErrorFilter, "includeGlobal">): number;deleteByAgent(projectId: string, agentId: string): void;deleteByProject(projectId: string): void;diff --git a/packages/server/src/runtime/messaging/connector.ts b/packages/server/src/runtime/messaging/connector.tsindex 33aaade0..ab3255f2 100644--- a/packages/server/src/runtime/messaging/connector.ts+++ b/packages/server/src/runtime/messaging/connector.ts@@ -133,7 +133,10 @@ export interface MessagingConnectorHandlers {onMessage(msg: MessagingInboundMessage): void | Promise<void>;/** The connection completed a handshake (may fire again after an automatic reconnect). */onReady?(): void;- /** The connection failed and the channel gave up (or the initial connect failed). */+ /**+ * The connection failed and the channel gave up (or the initial connect failed). A+ * {@link MessagingChannelError} says whether the outage clears without anyone acting.+ */onError?(err: unknown): void;}@@ -142,6 +145,41 @@ export interface MessagingConnection {close(): void;}+/**+ * A channel failure that carries its connector's verdict on whether anybody has to act.+ *+ * `recovers` answers one question: made again with nothing changed, does the same attempt go+ * through? A connection the connector's own retry brings back — a network drop, a reset TLS+ * handshake, a deadline, a platform restarting — does, and so does a send the next message+ * gets past (a 5xx, a rate limit). A credential the platform refused, a permission never+ * granted or a console setting in the way does not, however eagerly the connector retries.+ *+ * The verdict is decided where the failure is understood — the transport that read the+ * platform's status and its own code, or the connection loop that knows why it gave up on a+ * socket — and error-kind.ts reads the boolean and nothing else: a wording match would tie+ * the dashboard's "needs a human" count to how a platform phrases itself.+ */+export class MessagingChannelError extends Error {+ constructor(+ message: string,+ /** Whether the same attempt, made again with nothing changed, goes through. */+ readonly recovers: boolean,+ ) {+ super(message);+ this.name = "MessagingChannelError";+ }+}++/**+ * Whether a request the platform answered with this HTTP status may go through unchanged next+ * time: 408 and 429 say "not now" and a 5xx is the platform's own fault, while any other 4xx is+ * a refusal that repeats until someone changes something — the line core draws for an LLM+ * provider's status.+ */+export function httpStatusRecovers(status: number | undefined): boolean {+ return status === 408 || status === 429 || (status !== undefined && status >= 500);+}+/*** A successful credential check's optional payload: whatever the probe learned that the test* endpoint's feedback can act on. Every member is independently optional — a channel reportsdiff --git a/packages/server/src/runtime/messaging/error-kind.ts b/packages/server/src/runtime/messaging/error-kind.tsindex 758f2d8d..0185726c 100644--- a/packages/server/src/runtime/messaging/error-kind.ts+++ b/packages/server/src/runtime/messaging/error-kind.ts@@ -26,13 +26,14 @@* it surfaces.** The rule is deliberately a small allowlist of TYPED failures at NAMED capture points rather- * 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.+ * than a message match, plus failures that arrive carrying their own verdict — a connection+ * the connector retries, and a text send — 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.*/import type { ErrorKind } from "../error-recorder.js";+import { MessagingChannelError } from "./connector.js";import {MessagingMediaTooLargeError,MessagingOutboundCapError,@@ -63,6 +64,29 @@ const CODES_EXPLAINED_IN_CHAT = new Set(["messaging_file_fetch_failed",]);+/**+ * The capture points where the connector's own verdict decides (see MessagingChannelError):+ * a connection its retry loop reported, and a text send.+ *+ * Nobody in the chat is told about either — a connection that will not come up has no chat to+ * speak in, and the message that would carry the explanation is the message that did not go+ * out — so the question is only whether anybody has to act. A connection the connector's+ * backoff brings back on its own, and a send the next message gets past, leave nobody anything+ * to do; the platform refusing the credential, a permission or a setting leaves the binding+ * broken until someone does. The transports read that off the status and the platform's code+ * where they meet the failure, so it arrives typed; a failure that arrives untyped stays+ * `unexpected`.+ *+ * The file capture points are not here even though the same transports throw there: a reply's+ * file that did not go out is said in its error record and nowhere else, and whether that+ * record is routine is answered by type and code below, not by whether the upload might work+ * next time.+ */+const CODES_JUDGED_BY_THE_CONNECTOR = new Set([+ "messaging_connect_failed",+ "messaging_send_failed",+]);+/** A typed refusal's class, as `instanceof` takes it. */type RefusalType = new (message: string) => Error;@@ -114,24 +138,29 @@ const ROUTINE_OUTBOUND_FILE_REFUSALS: ReadonlyMap<string, RefusalType> = new Map* ROUTINE_OUTBOUND_FILE_REFUSALS gives: the structural refusal and the bridge's own caps, and* never a missing permission.*- * 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 understood type caught anywhere not named- * above: a refusal nobody was told about, and that somebody could still fix, is a refusal- * somebody has to notice.- *- * {@link MessagingConnectionClosedError} is classified wherever it is caught, and answers the- * criterion from its own verdict rather than a capture point: 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.+ * Everything else at those capture points — a network failure, a 5xx from the platform, a bug+ * here — is `unexpected` and keeps its place on the dashboard, and so is any understood type+ * caught anywhere not named above: a refusal nobody was told about, and that somebody could+ * still fix, is a refusal somebody has to notice.+ *+ * A connection failure and a text send answer the criterion from their own verdict instead+ * (see CODES_JUDGED_BY_THE_CONNECTOR): nobody needs telling, because nothing stayed broken. A+ * dropped socket, a reset TLS handshake, a deadline, a 5xx or a rate limit is answered by the+ * connector's next attempt within the backoff, or by the next message, and the only trace is a+ * record nobody can act on. It is `expected` only when the connector says the failure is one of+ * those, and a failure that leaves the binding down until a credential or a console setting+ * changes reports `recovers: false` and stays a defect.+ *+ * {@link MessagingConnectionClosedError} is classified by that verdict wherever it is caught:+ * the gateway is the only place that raises it, and it raises it about the connection.*/export function messagingErrorKind(err: unknown, code: string): ErrorKind {if (err instanceof MessagingConnectionClosedError) {return err.recovers ? "expected" : "unexpected";}+ if (CODES_JUDGED_BY_THE_CONNECTOR.has(code)) {+ return err instanceof MessagingChannelError && err.recovers ? "expected" : "unexpected";+ }if (CODES_EXPLAINED_IN_CHAT.has(code)) {return err instanceof MessagingPermissionError ||err instanceof MessagingMediaTooLargeError ||diff --git a/packages/server/src/runtime/messaging/qq-api.ts b/packages/server/src/runtime/messaging/qq-api.tsindex ccd14b95..1fb702e7 100644--- a/packages/server/src/runtime/messaging/qq-api.ts+++ b/packages/server/src/runtime/messaging/qq-api.ts@@ -32,6 +32,7 @@* that is a budget — see qq-connector.ts, which owns the accounting.*/import { WebSocket } from "undici";+import { MessagingChannelError, httpStatusRecovers } from "./connector.js";/*** QQ bot OpenAPI host — both the token endpoint and the resource endpoints. Deliberately@@ -222,7 +223,9 @@ function closeCodeIsFatal(code: number): boolean {* 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.+ * up. The transport's own closes join them: 1006 is the socket dropping with no close frame at+ * all — the network, not the platform — and 1001 and 1011-1014 are a server or a proxy going+ * away, failing, restarting or losing its upstream. None of those ask anything of anyone.** 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@@ -233,16 +236,22 @@ function closeCodeIsFatal(code: number): boolean {* repeating, points at this client's own sequence bookkeeping.*/function closeCodeIsRoutine(code: number): boolean {- return code === 4009 || (code >= 4900 && code <= 4913);+ return (+ code === 4009 ||+ (code >= 4900 && code <= 4913) ||+ code === 1001 ||+ code === 1006 ||+ (code >= 1011 && code <= 1014)+ );}/*** 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.+ * The gateway's own kind of MessagingChannelError, 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@@ -255,15 +264,15 @@ function closeCodeIsRoutine(code: number): boolean {* 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 {+export class MessagingConnectionClosedError extends MessagingChannelError {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,+ recovers: boolean,) {- super(message);+ super(message, recovers);this.name = "MessagingConnectionClosedError";}}@@ -363,15 +372,19 @@ export function qqSendErrorText(errCode: number | undefined, message: string): s* request that never completed are the same outcome and opposite facts. The platform* answered, so nothing was delivered and the same message may safely be sent again in* another form — which is what the markdown-to-text fallback does. A timeout or a reset- * carries no code, stays a plain Error, and must never be retried: it may already have been+ * carries no code, stays out of this class, and must never be retried: it may already have been* delivered, and on this channel a retry also spends another slot of a four-reply budget.+ *+ * `recovers` is read off the HTTP status the refusal came with (see httpStatusRecovers): the+ * platform's own codes name rules and budgets, not whether the next send meets the same no.*/-export class QQApiError extends Error {+export class QQApiError extends MessagingChannelError {constructor(message: string,readonly code: number | undefined,+ recovers = false,) {- super(message);+ super(message, recovers);this.name = "QQApiError";}}@@ -406,14 +419,16 @@ function tokenCacheOf(creds: QQCredentials): TokenCache {signal: AbortSignal.timeout(CALL_TIMEOUT_MS),});} catch (err) {- throw new Error(`Token exchange failed: ${fetchErrorText(err)}`);+ // The exchange never completed, so nothing was refused: the next one may well go through.+ throw new MessagingChannelError(`Token exchange failed: ${fetchErrorText(err)}`, true);}const body = (await res.json().catch(() => null)) as (QQAppAccessToken & QQErrorBody) | null;if (body === null || typeof body.access_token !== "string" || body.access_token === "") {const detail = body?.message ?? `HTTP ${res.status}`;const code = body?.code ?? body?.err_code;- throw new Error(+ throw new MessagingChannelError(`Token exchange failed: ${detail}${code !== undefined ? ` (code ${code})` : ""}`,+ httpStatusRecovers(res.status),);}const ttl = Number(body.expires_in);@@ -460,7 +475,7 @@ function createProductionClient(creds: QQCredentials): ProductionClient {signal: AbortSignal.timeout(CALL_TIMEOUT_MS),});} catch (err) {- throw new Error(`Message send failed: ${fetchErrorText(err)}`);+ throw new MessagingChannelError(`Message send failed: ${fetchErrorText(err)}`, true);}if (res.status >= 200 && res.status < 300) return;const body = (await res.json().catch(() => null)) as QQErrorBody | null;@@ -478,6 +493,7 @@ function createProductionClient(creds: QQCredentials): ProductionClient {throw new QQApiError(`Message send failed: ${detail}${errCode !== undefined ? ` (code ${errCode})` : ""}`,errCode,+ httpStatusRecovers(res.status),);};@@ -579,11 +595,12 @@ class GatewaySession {* 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.+ * failure — one whose MessagingChannelError says it recovers — is 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";@@ -637,11 +654,14 @@ class GatewaySession {signal: AbortSignal.timeout(CALL_TIMEOUT_MS),});} catch (err) {- throw new Error(`Gateway lookup failed: ${fetchErrorText(err)}`);+ throw new MessagingChannelError(`Gateway lookup failed: ${fetchErrorText(err)}`, true);}const body = (await res.json().catch(() => null)) as (QQGatewayInfo & QQErrorBody) | null;if (body === null || typeof body.url !== "string" || body.url === "") {- throw new Error(`Gateway lookup failed: ${body?.message ?? `HTTP ${res.status}`}`);+ throw new MessagingChannelError(+ `Gateway lookup failed: ${body?.message ?? `HTTP ${res.status}`}`,+ httpStatusRecovers(res.status),+ );}return body.url;}@@ -653,7 +673,7 @@ class GatewaySession {// it to prove it, and it covers both silences: no HELLO, and an IDENTIFY nobody answers.this.handshakeTimer = setTimeout(() => {this.handshakeTimer = null;- this.dropSocket(ws, new Error("gateway handshake did not complete"));+ this.dropSocket(ws, new MessagingChannelError("gateway handshake did not complete", true));}, this.opts.handshakeMs);this.handshakeTimer.unref?.();ws.addEventListener("message", (evt) => {@@ -736,10 +756,16 @@ class GatewaySession {this.seq = null;this.ws?.close();return;- case OP.RECONNECT:- // Politely asked to reconnect; the session stays resumable.- this.ws?.close();+ case OP.RECONNECT: {+ // Politely asked to reconnect; the session stays resumable. The drop is driven from+ // here, with its reason, because the `close` the request leads to carries no code+ // that says it was asked for — the refused resume above closes the same way.+ const ws = this.ws;+ if (ws !== null) {+ this.dropSocket(ws, new MessagingChannelError("gateway asked to reconnect", true));+ }return;+ }case OP.HEARTBEAT_ACK:// The one frame that proves the socket is still a round trip rather than a write// into a dead pipe. startHeartbeat measures its silence.@@ -785,7 +811,8 @@ class GatewaySession {* The `close` handler is not enough on its own here: the failure both watchdogs cover is* a socket that never fires `close`, and asking a half-open one to close is a request the* far end may never answer. Detaching first makes the `close` that may eventually arrive- * a no-op (every listener is gated on `this.ws === ws`).+ * a no-op (every listener is gated on `this.ws === ws`). A RECONNECT takes the same path,+ * so the failure it reports is the reason it was asked for rather than a bare close code.*/private dropSocket(ws: QQSocket, err: Error): void {if (this.ws !== ws) return;@@ -813,7 +840,10 @@ class GatewaySession {// still writable but no longer answering is a dead pipe rather than a slow one. One// interval would be a lost ack; two is an outage.if (Date.now() - this.lastAckAt > intervalMs * 2) {- this.dropSocket(ws, new Error("gateway stopped acknowledging heartbeats"));+ this.dropSocket(+ ws,+ new MessagingChannelError("gateway stopped acknowledging heartbeats", true),+ );return;}this.send({ op: OP.HEARTBEAT, d: this.seq });@@ -838,13 +868,13 @@ class GatewaySession {/*** 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.+ * the one exception `reported` documents: a routine failure 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;- const routine = err instanceof MessagingConnectionClosedError && err.recovers;+ const routine = err instanceof MessagingChannelError && err.recovers;if (this.reported === "none" || (this.reported === "routine" && !routine)) {this.reported = routine ? "routine" : "defect";this.handlers.onError?.(err);diff --git a/packages/server/src/runtime/messaging/telegram-api.ts b/packages/server/src/runtime/messaging/telegram-api.tsindex 5d487b95..b0e1121b 100644--- a/packages/server/src/runtime/messaging/telegram-api.ts+++ b/packages/server/src/runtime/messaging/telegram-api.ts@@ -11,6 +11,7 @@* reshape payloads, so a test fake constructs exactly what the real API returns.*/import { FormData, fetch as undiciFetch } from "undici";+import { MessagingChannelError, httpStatusRecovers } from "./connector.js";import { MessagingMediaTooLargeError, collectUnderCap } from "./media.js";/** Telegram Bot API host. Deliberately not configurable: bindings carry only the token. */@@ -302,17 +303,23 @@ interface TelegramEnvelope<T> {** The code is the only part of the envelope a caller may branch on: `description` is prose* Telegram rewords without notice, so a retry keyed on its wording breaks silently. A- * transport failure — a timeout, a reset, an unparseable body — has no code and stays a- * plain Error, which keeps "the request never completed" distinguishable from "Telegram- * refused it"; nothing may retry the former, because the message may well have been- * delivered.+ * transport failure — a timeout, a reset — has no code and stays out of this class (a+ * MessagingChannelError that recovers), which keeps "the request never completed"+ * distinguishable from "Telegram refused it"; nothing may retry the former, because the+ * message may well have been delivered.+ *+ * `recovers` follows the code, which is Telegram's copy of the HTTP status (see+ * httpStatusRecovers): a 429 flood wait or a 5xx clears by itself, while a revoked token+ * (401), a conflicting poller (409) or a chat that blocked the bot (403) repeats until someone+ * acts. A body with no code at all is judged by the status it arrived with.*/-export class TelegramApiError extends Error {+export class TelegramApiError extends MessagingChannelError {constructor(message: string,readonly errorCode: number | undefined,+ recovers = httpStatusRecovers(errorCode),) {- super(message);+ super(message, recovers);this.name = "TelegramApiError";}}@@ -392,7 +399,7 @@ export function createTelegramTransport(opts: TelegramTransportOpts = {}): Telegsignal,});} catch (err) {- throw new Error(`${method} failed: ${fetchErrorText(err)}`);+ throw new MessagingChannelError(`${method} failed: ${fetchErrorText(err)}`, true);}const parsed = (await res.json().catch(() => null)) as TelegramEnvelope<T> | null;if (parsed === null || parsed.ok !== true) {@@ -402,7 +409,11 @@ export function createTelegramTransport(opts: TelegramTransportOpts = {}): Telegdescribed ??`HTTP ${res.status}`;const code = parsed?.error_code !== undefined ? ` (code ${parsed.error_code})` : "";- throw new TelegramApiError(`${method} failed: ${detail}${code}`, parsed?.error_code);+ throw new TelegramApiError(+ `${method} failed: ${detail}${code}`,+ parsed?.error_code,+ httpStatusRecovers(parsed?.error_code ?? res.status),+ );}return parsed.result as T;};diff --git a/packages/server/src/runtime/messaging/telegram-connector.ts b/packages/server/src/runtime/messaging/telegram-connector.tsindex a9fcfc31..6bf0cc6a 100644--- a/packages/server/src/runtime/messaging/telegram-connector.ts+++ b/packages/server/src/runtime/messaging/telegram-connector.ts@@ -46,6 +46,7 @@ import type {MessagingInboundMessage,MessagingSendNote,} from "./connector.js";+import { MessagingChannelError } from "./connector.js";import { imageMimeOfName } from "./media.js";import { telegramHtmlOf } from "./telegram-html.js";import type {@@ -525,6 +526,8 @@ export class TelegramConnector implements MessagingChannelConnector {/** This bot's own account, from the `getMe` the loop already makes; only its own mention needs it. */let me: TelegramBotUser | null = null;let failures = 0;+ /** What this outage has already reported (see qq-api's GatewaySession.reported). */+ let reported: "none" | "routine" | "defect" = "none";let offset: number | undefined;while (!isClosed()) {try {@@ -562,6 +565,7 @@ export class TelegramConnector implements MessagingChannelConnector {});if (isClosed()) return;failures = 0;+ reported = "none";if (!ready) {ready = true;handlers.onReady?.();@@ -578,8 +582,14 @@ export class TelegramConnector implements MessagingChannelConnector {// one error record; the retries stay quiet until recovery re-fires onReady. The// counter survives the recovery attempt above precisely so a failure that only// ever hits `getUpdates` — a 409 conflict — still walks the backoff up to its- // ceiling instead of re-polling every second forever.- if (failures === 1) handlers.onError?.(err);+ // ceiling instead of re-polling every second forever. A failure that recovers on+ // its own is filed `expected`, so it does not get to be the whole story: the first+ // one after it that does not recover is reported too.+ const routine = err instanceof MessagingChannelError && err.recovers;+ if (reported === "none" || (reported === "routine" && !routine)) {+ reported = routine ? "routine" : "defect";+ handlers.onError?.(err);+ }ready = false;await sleep(this.retryDelayMs(failures), signal);}diff --git a/packages/server/src/runtime/messaging/wechat-api.ts b/packages/server/src/runtime/messaging/wechat-api.tsindex 582869ec..ce099589 100644--- a/packages/server/src/runtime/messaging/wechat-api.ts+++ b/packages/server/src/runtime/messaging/wechat-api.ts@@ -42,6 +42,7 @@* from traffic, and traffic is what re-derives it.*/import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";+import { MessagingChannelError, httpStatusRecovers } from "./connector.js";import { MessagingMediaTooLargeError, collectUnderCap } from "./media.js";/** The platform's fixed entry host: the QR calls, and the default API base before a scan names one. */@@ -271,14 +272,27 @@ export interface WeChatTransport {* The code the platform answers with when the bot token is stale or revoked. It arrives with* an HTTP 200 and a non-zero envelope, so it is the one business-level code that has to be* read as an authentication failure rather than as one of the call behind it.+ *+ * What it asks of a client is to wait, though: its errmsg is "session timeout", and Tencent's+ * own plugin (see the module doc) answers it by pausing the account for an hour and then+ * resuming, never by asking for a new scan. So it fails the credential probe while it lasts,+ * and still counts as a failure that recovers (see WeChatApiError).*/export const WECHAT_STALE_TOKEN_CODE = -14;/*** A call the platform answered with a failure of its own, as opposed to one that never* arrived. `ret` is the protocol's numeric code where it returned one.+ *+ * `recovers` is set where the failure is read (see `post` and checkEnvelope). A request that+ * never completed, an HTTP 408/429/5xx, and every refusal the envelope carries — the session+ * pause of WECHAT_STALE_TOKEN_CODE, and whatever the platform declines behind a credential it+ * accepted, such as a send's "prepare failed" — go through on a later attempt with nothing+ * changed: this channel has no permission and no console setting a person could fix them+ * with. An HTTP refusal of the credential (401/403), a wrong host (404) and a body this client+ * cannot read do not.*/-export class WeChatApiError extends Error {+export class WeChatApiError extends MessagingChannelError {/*** The request was ACCEPTED — it authenticated, and the failure came from the call behind* the credential rather than from the credential.@@ -299,9 +313,9 @@ export class WeChatApiError extends Error {constructor(readonly ret: number | undefined,message: string,- flags: { authenticated?: boolean; timedOut?: boolean } = {},+ flags: { authenticated?: boolean; timedOut?: boolean; recovers?: boolean } = {},) {- super(message);+ super(message, flags.recovers ?? false);this.name = "WeChatApiError";this.authenticated = flags.authenticated ?? false;this.timedOut = flags.timedOut ?? false;@@ -382,6 +396,7 @@ function checkEnvelope(label: string, status: number, raw: string): Record<strin// being the one code that says otherwise.throw new WeChatApiError(code, `${label} failed: ${env.errmsg ?? `code ${code}`}`, {authenticated: code !== WECHAT_STALE_TOKEN_CODE,+ recovers: true,});}return body;@@ -568,6 +583,7 @@ export function createWeChatTransport(): WeChatTransport {`${opts.label} failed: ${wechatFetchErrorText(err)}`,{timedOut: isAbortLike(err),+ recovers: true,},);}@@ -580,6 +596,7 @@ export function createWeChatTransport(): WeChatTransport {throw new WeChatApiError(undefined,`${opts.label} failed: HTTP ${res.status}${raw === "" ? "" : ` ${raw.slice(0, 300)}`}`,+ { recovers: httpStatusRecovers(res.status) },);}return checkEnvelope(opts.label, res.status, raw);diff --git a/packages/server/src/runtime/messaging/wechat-connector.ts b/packages/server/src/runtime/messaging/wechat-connector.tsindex a8785f83..99d47271 100644--- a/packages/server/src/runtime/messaging/wechat-connector.ts+++ b/packages/server/src/runtime/messaging/wechat-connector.ts@@ -88,6 +88,7 @@ import type {MessagingOutboundFile,MessagingSendOptions,} from "./connector.js";+import { MessagingChannelError } from "./connector.js";import { wechatMarkdownOf } from "./wechat-markdown.js";import type {WeChatBotClient,@@ -323,6 +324,8 @@ export class WeChatConnector implements MessagingChannelConnector {/** Drains that closed on their deadline without the platform answering. */let drainAttempts = 0;let failures = 0;+ /** What this outage has already reported (see qq-api's GatewaySession.reported). */+ let reported: "none" | "routine" | "defect" = "none";let cursor = "";while (!isClosed()) {try {@@ -376,6 +379,7 @@ export class WeChatConnector implements MessagingChannelConnector {// endpoints, so a failure that only ever hits the poll would otherwise be zeroed by// every recovery, never walk the backoff up, and write one error record per attempt.failures = 0;+ reported = "none";for (const evt of messages) {if (isClosed()) return;// The token is learned BEFORE the bridge is told, so the reply to this very@@ -390,8 +394,14 @@ export class WeChatConnector implements MessagingChannelConnector {ready = false;failures += 1;// Reported once per outage, not once per attempt: a token revoked overnight would- // otherwise write one error record per retry until somebody looked.- if (failures === 1) handlers.onError?.(err);+ // otherwise write one error record per retry until somebody looked. A failure that+ // recovers on its own is filed `expected`, so it does not get to be the whole story:+ // the first one after it that does not recover is reported too.+ const routine = err instanceof MessagingChannelError && err.recovers;+ if (reported === "none" || (reported === "routine" && !routine)) {+ reported = routine ? "routine" : "defect";+ handlers.onError?.(err);+ }await this.sleep(this.retryDelayMs(failures), signal);}}diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.tsindex 6933f55f..35be800f 100644--- a/packages/server/src/services/usage-service.ts+++ b/packages/server/src/services/usage-service.ts@@ -56,7 +56,7 @@ import type { ErrorLog, UsageQueries, UsageStore } from "../mechanisms/observabiimport type { ProjectConfigStore } from "../mechanisms/projects.js";/**- * Number of most-recent entries kept in the error detail table. Also the page size the whole+ * Number of most-recent rows kept in the error detail table. Also the page size the whole* feature runs on, but nothing needs to hard-code it: `errors.recent` is exactly this many rows* whenever a second page exists, so the client derives its page size from the response instead* of holding a constant that could drift out of step with this one.@@ -110,6 +110,12 @@ export interface UsageQuery {*/fromTs?: string;toTs?: string;+ /**+ * The viewer's offset east of UTC, in minutes: the calendar day the error table folds a+ * day's repeats by (see ErrorsRepo.recent). Nothing else in the response reads it; absent,+ * the day is the server's own.+ */+ utcOffsetMinutes?: number;}/** One page of the error detail table (see {@link UsageService.queryErrors}). */@@ -126,6 +132,8 @@ export interface UsageErrorsQuery {kind?: string;/** 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}). */+ utcOffsetMinutes?: number;}/**@@ -409,7 +417,7 @@ export class UsageService implements UsageQueries {series: this.foldSeries(bucketKeys, seriesRows, rates),byAgentSeries: foldAgentSeries(bucketKeys, agentBucketRows),byModelSeries: foldModelSeries(bucketKeys, modelBucketRows),- errors: this.foldErrors(projectId, errorFilter),+ errors: this.foldErrors(projectId, errorFilter, q.utcOffsetMinutes),agentIds: this.usage.distinctAgentIds(projectId),models: this.usage.distinctModels(projectId),};@@ -418,8 +426,9 @@ export class UsageService implements UsageQueries {/*** One page of the error detail table, newest first. The dashboard's own response already* carries the first page (`errors.recent`); this serves the "show me earlier ones" paging,- * where refetching the whole aggregate to move one page would be wasteful. `total` is the- * filtered row count, so the caller knows when it has reached the end.+ * where refetching the whole aggregate to move one page would be wasteful. `rows` is the+ * filtered row count, so the caller knows when it has reached the end; `total` counts the+ * records behind those rows, the occurrences the badge reports.** Takes the same filter the dashboard applies — date + agent, and admin-only visibility of* unattributed errors — so a page never widens what the summary above it counted.@@ -441,8 +450,9 @@ export class UsageService implements UsageQueries {...(q.includeGlobalErrors === true ? { includeGlobal: true } : {}),};return {- items: this.errors.recent(projectId, f, q.limit, q.offset),+ items: this.errors.recent(projectId, f, q.limit, q.offset, q.utcOffsetMinutes),total: this.errors.summary(projectId, f).total,+ rows: this.errors.rowCount(projectId, f, q.utcOffsetMinutes),};}@@ -467,14 +477,15 @@ export class UsageService implements UsageQueries {});}- /** 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 {+ /** 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,topCode: this.errors.topCode(projectId, f),- recent: this.errors.recent(projectId, f, ERROR_RECENT_N),+ 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.tsindex de468d5b..22a7559a 100644--- a/packages/server/test/errors.test.ts+++ b/packages/server/test/errors.test.ts@@ -92,10 +92,10 @@ describe("errors-repo", () => {const admin = { includeGlobal: true };expect(repo.summary("p1", admin)).toEqual({ total: 3, unexpected: 2 });expect(repo.topCode("p1", admin)).toMatchObject({ code: "uncaught_exception", count: 2 });- expect(repo.recent("p1", admin).map((r) => r.code)).toEqual([- "not_found",- "uncaught_exception",- "uncaught_exception",+ // The two unattributed records are the same error on the same day, so they share a row.+ expect(repo.recent("p1", admin).map((r) => [r.code, r.count])).toEqual([+ ["not_found", 1],+ ["uncaught_exception", 2],]);// A member of another Project likewise only sees their own row: unattributed errors never land in any regular member's view.@@ -157,6 +157,91 @@ describe("errors-repo", () => {expect(repo.recent("p1").map((r) => r.message)).toEqual(["just after", "just before"]);});+ it("recent folds a day's repeats into one row, with how many and the first and last time", () => {+ // A connection that drops and recovers all afternoon files the same record again and again;+ // the table reads it as one line saying how often. Anything that differs keeps its own row:+ // another message, another day, another kind (a record filed before a reclassification).+ const heartbeat = {+ source: "messaging",+ code: "messaging_connect_failed",+ kind: "expected",+ message: "gateway stopped acknowledging heartbeats",+ };+ const at = (ts: string, o: Partial<ErrorRecordInsert> = {}) =>+ repo.insert(row(ts.slice(0, 10), { ...heartbeat, ts, ...o }));+ at("2026-07-06T09:00:00.000Z");+ at("2026-07-06T12:30:00.000Z");+ at("2026-07-06T13:00:00.000Z", { message: "gateway connection closed (code 4009)" });+ at("2026-07-06T17:45:00.000Z");+ at("2026-07-06T18:00:00.000Z", { kind: "unexpected" });+ at("2026-07-07T08:00:00.000Z");++ const rows = repo+ .recent("p1")+ .map(({ ts, firstTs, count, kind, message }) => ({ ts, firstTs, count, kind, message }));+ expect(rows).toEqual([+ {+ ts: "2026-07-07T08:00:00.000Z",+ firstTs: "2026-07-07T08:00:00.000Z",+ count: 1,+ kind: "expected",+ message: heartbeat.message,+ },+ {+ ts: "2026-07-06T18:00:00.000Z",+ firstTs: "2026-07-06T18:00:00.000Z",+ count: 1,+ kind: "unexpected",+ message: heartbeat.message,+ },+ // Newest first by the row's latest record, so the fold sits where its last one happened.+ {+ ts: "2026-07-06T17:45:00.000Z",+ firstTs: "2026-07-06T09:00:00.000Z",+ count: 3,+ kind: "expected",+ message: heartbeat.message,+ },+ {+ ts: "2026-07-06T13:00:00.000Z",+ firstTs: "2026-07-06T13:00:00.000Z",+ count: 1,+ kind: "expected",+ message: "gateway connection closed (code 4009)",+ },+ ]);+ // A page is rows, and the pager counts rows; the summary still counts the records.+ expect(repo.recent("p1", {}, 2, 2).map((r) => r.ts)).toEqual([+ "2026-07-06T17:45:00.000Z",+ "2026-07-06T13:00:00.000Z",+ ]);+ expect(repo.rowCount("p1")).toBe(4);+ expect(repo.summary("p1")).toEqual({ total: 6, unexpected: 1 });+ expect(repo.topCode("p1")).toMatchObject({ code: "messaging_connect_failed", count: 5 });+ // Filters narrow the records before they fold.+ expect(repo.rowCount("p1", { kind: "unexpected" })).toBe(1);+ expect(repo.recent("p1", { from: "2026-07-06", to: "2026-07-06" })).toHaveLength(3);+ });++ it("the day a row folds by is the viewer's, from the offset the read carries", () => {+ // Two records an hour apart, either side of UTC midnight. The `date` column is the server's+ // day, which is what a read without an offset folds by.+ const late = { ts: "2026-07-06T23:30:00.000Z", message: "socket hang up" };+ const early = { ts: "2026-07-07T00:30:00.000Z", message: "socket hang up" };+ repo.insert(row("2026-07-06", late));+ repo.insert(row("2026-07-07", early));++ expect(repo.recent("p1").map((r) => r.count)).toEqual([1, 1]);+ expect(repo.rowCount("p1")).toBe(2);+ // UTC+8 and UTC-5: both land on one local day, so one row says twice.+ for (const offset of [480, -300]) {+ expect(repo.recent("p1", {}, 20, 0, offset).map((r) => r.count)).toEqual([2]);+ expect(repo.rowCount("p1", {}, offset)).toBe(1);+ }+ // UTC itself splits them again.+ expect(repo.rowCount("p1", {}, 0)).toBe(2);+ });+it("recent errors: newest first, top limit rows", () => {repo.insert(row("2026-07-05", { message: "old" }));repo.insert(row("2026-07-06", { message: "new" }));@@ -1271,6 +1356,69 @@ describe("HTTP onError persistence (integration)", () => {expect(all.total).toBe(4);});+ it("the paged error route and the dashboard fold a day's repeats by the viewer's day", async () => {+ // Three of the same send failure: two on the evening of the 27th in UTC and one just after+ // UTC midnight — the same evening for a reader five hours behind.+ const repo = wire(ErrorsRepo, { db: t.deps.db });+ for (const ts of [+ "2026-07-27T20:00:00.000Z",+ "2026-07-27T22:00:00.000Z",+ "2026-07-28T01:00:00.000Z",+ ]) {+ repo.insert({+ ts,+ date: ts.slice(0, 10),+ projectId,+ agentId: "a1",+ sessionId: "s1",+ source: "messaging",+ kind: "expected",+ code: "messaging_send_failed",+ status: null,+ message: "wechat send failed: prepare failed",+ });+ }+ const pageFor = async (query: string) =>+ (await (+ await api.get(`/api/projects/${projectId}/usage/errors?offset=0&limit=20${query}`)+ ).json()) as UsageErrorsPage;++ const eastern = await pageFor("&utcOffsetMinutes=-300");+ expect(eastern.items).toHaveLength(1);+ expect(eastern.items[0]).toMatchObject({+ count: 3,+ ts: "2026-07-28T01:00:00.000Z",+ firstTs: "2026-07-27T20:00:00.000Z",+ });+ // Rows are what a pager pages through; the records behind them are still the total.+ expect(eastern.rows).toBe(1);+ expect(eastern.total).toBe(3);++ // Without an offset the day is the server's, the `date` column: two days, two rows.+ const server = await pageFor("");+ expect(server.items.map((e) => e.count)).toEqual([1, 2]);+ expect(server.rows).toBe(2);++ // The dashboard's first page folds the same way, and its summary keeps counting records.+ const dashboard = (await (+ await api.get(`/api/projects/${projectId}/usage?utcOffsetMinutes=-300`)+ ).json()) as UsageResponse;+ expect(dashboard.errors.recent.map((e) => e.count)).toEqual([3]);+ expect(dashboard.errors.rows).toBe(1);+ expect(dashboard.errors.total).toBe(3);++ // An offset no clock uses, or one that is not a whole number, is a 400 rather than a+ // quietly different day.+ for (const bad of ["900", "-841", "1.5", "east", "+60"]) {+ expect(+ (await api.get(`/api/projects/${projectId}/usage/errors?utcOffsetMinutes=${bad}`)).status,+ ).toBe(400);+ }+ expect((await api.get(`/api/projects/${projectId}/usage?utcOffsetMinutes=900`)).status).toBe(+ 400,+ );+ });+/** 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 }) =>wire(ErrorsRepo, { db: t.deps.db }).insert({diff --git a/packages/server/test/messaging-error-kind.test.ts b/packages/server/test/messaging-error-kind.test.tsindex 1f67fb8b..02b95a67 100644--- a/packages/server/test/messaging-error-kind.test.ts+++ b/packages/server/test/messaging-error-kind.test.ts@@ -8,9 +8,12 @@* at nothing, or hides the one failure worth an alert.** Only the two halves live here; that the classification reaches `error_records` this way is- * proved end to end in messaging.test.ts and messaging-qq.test.ts.+ * proved end to end in messaging.test.ts and messaging-qq.test.ts, and the verdicts a failure+ * carries are asserted where the transports decide them (messaging-wire.test.ts and the qq and+ * wechat transport suites).*/import { describe, expect, it } from "vitest";+import { MessagingChannelError } from "../src/runtime/messaging/connector.js";import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";import {MessagingMediaTooLargeError,@@ -19,6 +22,7 @@ import {MessagingUnsupportedError,} from "../src/runtime/messaging/media.js";import { MessagingConnectionClosedError } from "../src/runtime/messaging/qq-api.js";+import { TelegramApiError } from "../src/runtime/messaging/telegram-api.js";/** Feishu's 99991672, which every one of its calls throws alike — the point of the code half. */const scopeDenial = (): MessagingPermissionError =>@@ -158,4 +162,55 @@ describe("messagingErrorKind", () => {),).toBe("unexpected");});++ it("a connection failure or a text send is read from the connector's own verdict", () => {+ // The two capture points where the chat hears nothing and the only question is whether+ // anybody has to act. A failure the next attempt gets past is routine there…+ const blip = new MessagingChannelError("getUpdates failed: socket hang up", true);+ expect(messagingErrorKind(blip, "messaging_connect_failed")).toBe("expected");+ expect(messagingErrorKind(blip, "messaging_send_failed")).toBe("expected");+ expect(+ messagingErrorKind(+ new TelegramApiError(+ "sendMessage failed: Too Many Requests: retry after 5 (code 429)",+ 429,+ ),+ "messaging_send_failed",+ ),+ ).toBe("expected");+ // …and one that meets the same refusal every time stays a defect, whichever channel's+ // type carries the verdict.+ expect(+ messagingErrorKind(+ new MessagingChannelError("Token exchange failed: appid invalid (code 100007)", false),+ "messaging_connect_failed",+ ),+ ).toBe("unexpected");+ expect(+ messagingErrorKind(+ new TelegramApiError(+ "sendMessage failed: Forbidden: bot was blocked by the user (code 403)",+ 403,+ ),+ "messaging_send_failed",+ ),+ ).toBe("unexpected");+ // A plain Error carries no verdict, whatever its words say: unclassified stays loud.+ expect(+ messagingErrorKind(+ new Error("getUpdates failed: socket hang up"),+ "messaging_connect_failed",+ ),+ ).toBe("unexpected");+ });++ it("reads that verdict at those two capture points and nowhere else", () => {+ // The same transports throw at the file and download capture points, which answer the+ // question by type and code: a reply's file that did not go out is said nowhere but its+ // record, and whether the upload would work next time does not change that.+ const blip = new MessagingChannelError("sendPhoto failed: socket hang up", true);+ expect(messagingErrorKind(blip, "messaging_file_send_failed")).toBe("unexpected");+ expect(messagingErrorKind(blip, "messaging_image_fetch_failed")).toBe("unexpected");+ expect(messagingErrorKind(blip, "messaging_inbound_failed")).toBe("unexpected");+ });});diff --git a/packages/server/test/messaging-qq-transport.test.ts b/packages/server/test/messaging-qq-transport.test.tsindex 1725e7e4..baf8064c 100644--- a/packages/server/test/messaging-qq-transport.test.ts+++ b/packages/server/test/messaging-qq-transport.test.ts@@ -27,6 +27,7 @@ import {QQApiError,createQQTransport,} from "../src/runtime/messaging/qq-api.js";+import { MessagingChannelError } from "../src/runtime/messaging/connector.js";import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";import { waitFor } from "./helpers.js";@@ -349,7 +350,7 @@ describe("the QQ OpenAPI send", () => {});});- it("types a refusal as QQApiError and a transfer failure as a plain Error", async () => {+ it("types a refusal as QQApiError and a transfer failure as one that recovers", async () => {// The distinction the markdown-to-text fallback turns on: the platform answered and// delivered nothing, so another form of the same message is safe to send — where a// request that never completed may already have been delivered.@@ -360,6 +361,19 @@ describe("the QQ OpenAPI send", () => {const err = await bot.sendMessage(args).catch((e: unknown) => e);expect(err).toBeInstanceOf(QQApiError);expect((err as QQApiError).code).toBe(40054001);+ // A 4xx refusal meets the same no next time: the error table keeps it a defect.+ expect((err as QQApiError).recovers).toBe(false);+ expect(messagingErrorKind(err, "messaging_send_failed")).toBe("unexpected");+ },+ );+ await withFetch(+ (call) => (call.url.includes("/v2/") ? jsonResponse({ err_code: 22009 }, 503) : null),+ async () => {+ const bot = createQQTransport().createClient(CREDS);+ const err = await bot.sendMessage(args).catch((e: unknown) => e);+ // The platform's own fault, whatever its code says: the next send goes through.+ expect(err).toBeInstanceOf(QQApiError);+ expect(messagingErrorKind(err, "messaging_send_failed")).toBe("expected");},);await withFetch(@@ -370,8 +384,10 @@ describe("the QQ OpenAPI send", () => {async () => {const bot = createQQTransport().createClient(CREDS);const err = await bot.sendMessage(args).catch((e: unknown) => e);- expect(err).toBeInstanceOf(Error);+ expect(err).toBeInstanceOf(MessagingChannelError);expect(err).not.toBeInstanceOf(QQApiError);+ expect((err as MessagingChannelError).recovers).toBe(true);+ expect(messagingErrorKind(err, "messaging_send_failed")).toBe("expected");},);});@@ -502,6 +518,15 @@ describe("the QQ gateway session", () => {await waitFor(() => h.sockets.length === 3);h.sockets[2]!.deliver({ op: OP_HELLO, d: { heartbeat_interval: 45_000 } });expect(h.sockets[2]!.frames(OP_IDENTIFY)).toHaveLength(1);++ // The two closes look alike on the wire, so their verdicts come from the session: the+ // reconnect the platform asked for is routine, and the refused resume — which loses+ // whatever arrived in the gap — is not, and is reported although the same outage has+ // already reported the routine one.+ expect(h.errors.map((err) => messagingErrorKind(err, "messaging_connect_failed"))).toEqual([+ "expected",+ "unexpected",+ ]);} finally {conn.close();}@@ -555,6 +580,15 @@ describe("the QQ gateway session", () => {expect((await verdictOf(4009)).recovers).toBe(true);expect((await verdictOf(4900)).recovers).toBe(true);expect((await verdictOf(4913)).recovers).toBe(true);+ // The transport's own closes: a socket that dropped with no close frame at all, and a server+ // or proxy going away, failing or restarting. The next handshake is the whole of the fix.+ expect((await verdictOf(1006)).recovers).toBe(true);+ expect((await verdictOf(1001)).recovers).toBe(true);+ expect((await verdictOf(1011)).recovers).toBe(true);+ expect((await verdictOf(1014)).recovers).toBe(true);+ // A close nobody explained is not presumed routine.+ expect((await verdictOf(1000)).recovers).toBe(false);+ expect((await verdictOf(1005)).recovers).toBe(false);// 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);@@ -634,6 +668,9 @@ describe("the QQ gateway session", () => {expect(socket.closes).toBe(1);expect(h.errors).toHaveLength(1);expect(String(h.errors[0])).toContain("heartbeat");+ // A dead pipe the next socket replaces: routine, whatever the retries meet next.+ expect(h.errors[0]).toBeInstanceOf(MessagingChannelError);+ expect(messagingErrorKind(h.errors[0], "messaging_connect_failed")).toBe("expected");} finally {conn.close();}@@ -652,12 +689,69 @@ describe("the QQ gateway session", () => {expect(h.sockets[0]!.closes).toBe(1);expect(h.errors).toHaveLength(1);expect(String(h.errors[0])).toContain("handshake");+ expect(messagingErrorKind(h.errors[0], "messaging_connect_failed")).toBe("expected");} finally {conn.close();}});});+ it("judges the two calls in front of the socket the way it judges a send", async () => {+ // The token exchange and the gateway lookup are plain HTTPS: a request that never arrived+ // may go through next time, and a refusal is judged by its status.+ const firstError = (answer: (call: Call) => Response | null): Promise<unknown> =>+ withFetch(answer, async () => {+ const errors: unknown[] = [];+ const conn = await createQQTransport({ gatewayRetryMs: () => 5 }).openGateway(CREDS, {+ onMessage: () => {},+ onError: (err) => {+ errors.push(err);+ },+ });+ try {+ await waitFor(() => errors.length > 0);+ return errors[0];+ } finally {+ conn.close();+ }+ });+ const kindOf = (err: unknown) => messagingErrorKind(err, "messaging_connect_failed");++ expect(+ kindOf(+ await firstError((call) => {+ if (call.url.endsWith("/gateway")) throw new TypeError("fetch failed");+ return null;+ }),+ ),+ ).toBe("expected");+ expect(+ kindOf(+ await firstError((call) => {+ if (call.url.endsWith("/app/getAppAccessToken")) throw new TypeError("fetch failed");+ return null;+ }),+ ),+ ).toBe("expected");+ expect(+ kindOf(+ await firstError((call) =>+ call.url.endsWith("/gateway") ? jsonResponse({ message: "busy" }, 502) : null,+ ),+ ),+ ).toBe("expected");+ // A secret the platform refuses stays refused however often it is exchanged.+ expect(+ kindOf(+ await firstError((call) =>+ call.url.endsWith("/app/getAppAccessToken")+ ? jsonResponse({ code: 100007, message: "appid invalid" }, 400)+ : null,+ ),+ ),+ ).toBe("unexpected");+ });+it("stops opening sockets once the connection is closed", async () => {await withFetch(defaults, async () => {const h = harnessOf({ handshakeTimeoutMs: 20 });diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.tsindex 62a3d045..5f7b38d5 100644--- a/packages/server/test/messaging-telegram.test.ts+++ b/packages/server/test/messaging-telegram.test.ts@@ -45,6 +45,8 @@ import {messagingImageFailedNotice,messagingInboundFileTooLargeNotice,} from "../src/runtime/messaging/bridge.js";+import { MessagingChannelError } from "../src/runtime/messaging/connector.js";+import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";import { MessagingMediaTooLargeError, collectUnderCap } from "../src/runtime/messaging/media.js";import type {TelegramBotClient,@@ -1929,6 +1931,8 @@ class ConflictBotClient implements TelegramBotClient {pollCalls = 0;/** getUpdates rejects with the 409 while this is true. */conflict = false;+ /** Failures the next polls reject with, one each and in order, ahead of the conflict. */+ readonly failWith: Error[] = [];/** Rejects the parked long poll (what Telegram does to the loser of the conflict). */private parkedReject: ((err: Error) => void) | null = null;@@ -1957,6 +1961,8 @@ class ConflictBotClient implements TelegramBotClient {signal: AbortSignal;}): Promise<TelegramUpdate[]> {this.pollCalls++;+ const failure = this.failWith.shift();+ if (failure !== undefined) return Promise.reject(failure);if (this.conflict)return Promise.reject(new Error(`getUpdates failed: ${CONFLICT_DESCRIPTION}`));if (args.timeoutSec === 0) return Promise.resolve([]);@@ -1970,6 +1976,10 @@ class ConflictBotClient implements TelegramBotClient {this.conflict = true;this.parkedReject?.(new Error(`getUpdates failed: ${CONFLICT_DESCRIPTION}`));}+ /** Ends the parked long poll with this failure, as a dropped connection does. */+ failParked(err: Error): void {+ this.parkedReject?.(err);+ }}class ConflictTransport implements TelegramTransport {@@ -2070,6 +2080,40 @@ describe("telegram poll loop under a persistent 409", () => {expect(inbound).toEqual([]);});+ it("a failure that recovers on its own does not silence the refusal behind it", async () => {+ // A dropped poll is filed as routine, so if it kept the outage's one report, a token+ // revoked while the connection was down would never be filed: the binding stays down and+ // the dashboard reads zero defects. The adapter's verdicts are asserted where they are made+ // (messaging-wire.test.ts); these stand in for them.+ const { connector, transport } = conflictConnector();+ const errors: unknown[] = [];+ let readies = 0;+ const conn = await connector.connect(+ { botToken: TOKEN },+ {+ onMessage: async () => {},+ onReady: () => {+ readies++;+ },+ onError: (err) => {+ errors.push(err);+ },+ },+ );+ const bot = transport.clients[0]!;+ await waitFor(() => readies === 1);+ const revoked = () => new TelegramApiError("getUpdates failed: Unauthorized (code 401)", 401);+ bot.failWith.push(revoked(), revoked());+ bot.failParked(new MessagingChannelError("getUpdates failed: socket hang up", true));+ await waitFor(() => bot.failWith.length === 0 && readies === 2);+ conn.close();+ // The blip, then the refusal behind it — and nothing more: the repeat stays quiet.+ expect(errors.map((err) => messagingErrorKind(err, "messaging_connect_failed"))).toEqual([+ "expected",+ "unexpected",+ ]);+ });+it("probes for a webhook once per connection, before the first poll", async () => {const { connector, transport } = conflictConnector();let readies = 0;diff --git a/packages/server/test/messaging-wechat-transport.test.ts b/packages/server/test/messaging-wechat-transport.test.tsindex 5794bfec..6fdd4f5d 100644--- a/packages/server/test/messaging-wechat-transport.test.ts+++ b/packages/server/test/messaging-wechat-transport.test.ts@@ -14,6 +14,7 @@*/import { describe, expect, it } from "vitest";import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";+import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";import { MessagingMediaTooLargeError } from "../src/runtime/messaging/media.js";import type { WeChatCredentials } from "../src/runtime/messaging/wechat-api.js";import {@@ -602,6 +603,75 @@ describe("outbound sends", () => {});});+describe("the verdict a failure carries", () => {+ // What the error table files a connection failure or a send by: error-kind.ts reads+ // `recovers` at those two capture points and nothing else. Asserted where the adapter decides+ // it rather than on a hand-built error, which would only prove the classifier reads a boolean.+ const failureOf = async (+ answer: (call: Call) => Response | null,+ run: () => Promise<unknown>,+ ): Promise<WeChatApiError> => {+ let caught: unknown;+ await withFetch(answer, async () => {+ caught = await run().then(+ () => null,+ (e: unknown) => e,+ );+ });+ expect(caught).toBeInstanceOf(WeChatApiError);+ return caught as WeChatApiError;+ };+ const send = () => client().sendText({ userId: USER, text: "hi" });+ const probe = () => client().checkCredentials();++ it("recovers from a refusal the platform makes behind an accepted credential", async () => {+ // The reported row: the platform declined a send it had authenticated. Nothing on this+ // channel — no permission, no console setting — is anyone's to change, and the next send+ // goes through.+ const err = await failureOf(() => jsonResponse({ ret: -2, errmsg: "prepare failed" }), send);+ expect(err.message).toBe("wechat send failed: prepare failed");+ expect(err.authenticated).toBe(true);+ expect(err.recovers).toBe(true);+ expect(messagingErrorKind(err, "messaging_send_failed")).toBe("expected");+ });++ it("recovers from the session timeout, though the credential probe still fails on it", async () => {+ // The other reported row. The platform pauses the session; its own client waits and+ // resumes, never asking for a new scan — so the probe fails while it lasts, and the+ // outage it opens is routine.+ const err = await failureOf(+ () => jsonResponse({ ret: WECHAT_STALE_TOKEN_CODE, errmsg: "session timeout" }),+ probe,+ );+ expect(err.message).toBe("wechat credential check failed: session timeout");+ expect(err.authenticated).toBe(false);+ expect(err.recovers).toBe(true);+ expect(messagingErrorKind(err, "messaging_connect_failed")).toBe("expected");+ });++ it("recovers from a request that never arrived, and from a 408, a 429 or a 5xx", async () => {+ const unreachable = await failureOf(() => {+ throw new TypeError("fetch failed");+ }, send);+ expect(unreachable.recovers).toBe(true);+ for (const status of [408, 429, 500, 502, 503]) {+ const err = await failureOf(() => new Response("busy", { status }), send);+ expect(err.recovers).toBe(true);+ }+ });++ it("does not recover from a refused credential, a wrong host or an unreadable answer", async () => {+ for (const status of [401, 403, 404]) {+ const err = await failureOf(() => new Response("invalid bot token", { status }), probe);+ expect(err.recovers).toBe(false);+ expect(messagingErrorKind(err, "messaging_connect_failed")).toBe("unexpected");+ }+ const garbled = await failureOf(() => new Response("<html>proxy</html>"), send);+ expect(garbled.recovers).toBe(false);+ expect(messagingErrorKind(garbled, "messaging_send_failed")).toBe("unexpected");+ });+});+describe("inbound media transfers", () => {const KEY = randomBytes(16);const PLAIN = Buffer.from("a picture's worth of bytes, padded on the way out");diff --git a/packages/server/test/messaging-wechat.test.ts b/packages/server/test/messaging-wechat.test.tsindex cf27b04a..4f2ee927 100644--- a/packages/server/test/messaging-wechat.test.ts+++ b/packages/server/test/messaging-wechat.test.ts@@ -30,6 +30,7 @@ import {MESSAGING_TEST_MESSAGE,MESSAGING_UNSUPPORTED_NOTICE,} from "../src/runtime/messaging/bridge.js";+import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";import { MessagingMediaTooLargeError } from "../src/runtime/messaging/media.js";import type {WeChatBotClient,@@ -41,7 +42,7 @@ import type {WeChatTransport,WeChatUpdates,} from "../src/runtime/messaging/wechat-api.js";-import { WECHAT_API_BASE } from "../src/runtime/messaging/wechat-api.js";+import { WECHAT_API_BASE, WeChatApiError } from "../src/runtime/messaging/wechat-api.js";import {WeChatConnector,chatOfWeChatReplyRef,@@ -119,6 +120,8 @@ class FakeWeChatClient implements WeChatBotClient {this.polls += 1;this.cursors.push(cursor);this.drains.push(drain);+ const failure = this.t.failPollWith.shift();+ if (failure !== undefined) throw failure;if (this.t.failPoll !== null) throw new Error(this.t.failPoll);const queued = this.queue.shift();if (queued !== undefined) {@@ -174,6 +177,8 @@ class FakeWeChatTransport implements WeChatTransport {failAuth: string | null = null;failSend: string | null = null;failPoll: string | null = null;+ /** Failures the next polls throw, one each and in order, ahead of `failPoll`. */+ readonly failPollWith: Error[] = [];/** Every poll parks, the drain included — an idle bot, which is the readiness case. */stallPolls = false;oversizedMedia = false;@@ -715,6 +720,35 @@ describe("wechat binding routes and the long poll", () => {}});+ it("a failure that recovers on its own does not silence the refusal behind it", async () => {+ // A dropped request is filed as routine, so if it kept the outage's one report, a token+ // refused on every retry after it would never be filed at all: the binding stays down and+ // the dashboard reads zero defects. The transport's verdicts are asserted where they are+ // made (messaging-wechat-transport.test.ts); these stand in for them.+ const errors: unknown[] = [];+ fake.failPollWith.push(+ new WeChatApiError(undefined, "wechat getUpdates failed: fetch failed", { recovers: true }),+ new WeChatApiError(undefined, "wechat getUpdates failed: HTTP 401 invalid bot token"),+ new WeChatApiError(undefined, "wechat getUpdates failed: HTTP 401 invalid bot token"),+ );+ const connector = new WeChatConnector(fake, { retryDelayMs: () => 1 });+ const conn = await connector.connect(SCANNED_CONFIG, {+ onMessage: async () => {},+ onError: (err) => errors.push(err),+ });+ try {+ await waitFor(() => fake.failPollWith.length === 0 && errors.length === 2);+ await new Promise((resolve) => setTimeout(resolve, 20));+ // The blip, then the refusal behind it — and nothing more: the repeat stays quiet.+ expect(errors.map((err) => messagingErrorKind(err, "messaging_connect_failed"))).toEqual([+ "expected",+ "unexpected",+ ]);+ } finally {+ conn.close();+ }+ });+it("sends a picture as a picture and any other file as an attachment", async () => {// The capability QQ has to refuse outright: outbound media, both kinds, no public URL.const connector = new WeChatConnector(fake, { retryDelayMs: () => 0 });diff --git a/packages/server/test/messaging-wire.test.ts b/packages/server/test/messaging-wire.test.tsindex 5cb98d7a..8c402b5d 100644--- a/packages/server/test/messaging-wire.test.ts+++ b/packages/server/test/messaging-wire.test.ts@@ -33,7 +33,11 @@ import type { Dispatcher } from "undici";import { afterEach, describe, expect, it } from "vitest";import { FeishuApiError, createLarkSdk } from "../src/runtime/messaging/feishu-sdk.js";import { feishuCardOf } from "../src/runtime/messaging/feishu-card.js";-import { createTelegramTransport } from "../src/runtime/messaging/telegram-api.js";+import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";+import {+ TelegramApiError,+ createTelegramTransport,+} from "../src/runtime/messaging/telegram-api.js";import type {TelegramTransport,TelegramTransportOpts,@@ -641,6 +645,64 @@ describe("telegram adapter against the fetch boundary", () => {expect(photoBody).toContain(PHOTO.toString("latin1"));});+ it("gives a failure the verdict the error table files it by", async () => {+ // error-kind.ts reads `recovers` at the connection and at a text send, and this adapter is+ // where it is decided: off Telegram's own code, its copy of the HTTP status, or off the+ // status itself when a proxy answered instead of Telegram.+ const refusal = (code: number, description: string): Response =>+ new Response(JSON.stringify({ ok: false, error_code: code, description }), {+ status: code,+ headers: { "content-type": "application/json" },+ });+ const sendFailure = (answer: (url: string) => Response): Promise<unknown> =>+ stubFetch(answer)+ .transport.createClient({ botToken: TOKEN })+ .sendMessage({ chatId: "1", text: "hi" })+ .then(+ () => null,+ (e: unknown) => e,+ );+ const sendKind = async (answer: (url: string) => Response) =>+ messagingErrorKind(await sendFailure(answer), "messaging_send_failed");+ const tlsReset = (): Response => {+ throw Object.assign(new TypeError("fetch failed"), {+ cause: new Error(+ "Client network socket disconnected before secure TLS connection was established",+ ),+ });+ };++ // The reported row: a poll that never completed is no refusal of Telegram's, and the+ // loop's next poll is the whole of the fix.+ const poll = await stubFetch(tlsReset)+ .transport.createClient({ botToken: TOKEN })+ .getUpdates({ timeoutSec: 0, signal: new AbortController().signal })+ .then(+ () => null,+ (e: unknown) => e,+ );+ expect(poll).not.toBeInstanceOf(TelegramApiError);+ expect(String((poll as Error).message)).toBe(+ "getUpdates failed: Client network socket disconnected before secure TLS connection was established",+ );+ expect(messagingErrorKind(poll, "messaging_connect_failed")).toBe("expected");+ // A send that never completed, a flood wait and Telegram's own outage clear by themselves,+ // and so does a proxy's error page, which carries no code but a status.+ expect(await sendKind(tlsReset)).toBe("expected");+ expect(await sendKind(() => refusal(429, "Too Many Requests: retry after 5"))).toBe("expected");+ expect(await sendKind(() => refusal(502, "Bad Gateway"))).toBe("expected");+ expect(+ await sendKind(() => new Response("<html>gateway timeout</html>", { status: 504 })),+ ).toBe("expected");+ // A revoked token, a chat that blocked the bot and a chat that is gone meet the same no on+ // every later send.+ expect(await sendKind(() => refusal(401, "Unauthorized"))).toBe("unexpected");+ expect(await sendKind(() => refusal(403, "Forbidden: bot was blocked by the user"))).toBe(+ "unexpected",+ );+ expect(await sendKind(() => refusal(400, "Bad Request: chat not found"))).toBe("unexpected");+ });+it("surfaces a Bot API refusal of an upload with its description", async () => {const stub = stubFetch(() =>diff --git a/packages/server/test/usage.test.ts b/packages/server/test/usage.test.tsindex f0b1ea5e..b068d886 100644--- a/packages/server/test/usage.test.ts+++ b/packages/server/test/usage.test.ts@@ -744,6 +744,8 @@ describe("usage-service.queryErrors (error table paging)", () => {it("pages newest-first and reports the filtered total, so the caller knows where the end is", () => {const first = service.queryErrors("p1", { offset: 0, limit: 20 });expect(first.total).toBe(25);+ // Every record here is a different error, so each is its own row.+ expect(first.rows).toBe(25);expect(first.items).toHaveLength(20);expect(first.items[0]!.code).toBe("code_24"); // newestconst second = service.queryErrors("p1", { offset: 20, limit: 20 });@@ -762,6 +764,30 @@ describe("usage-service.queryErrors (error table paging)", () => {const page = service.queryErrors("p1", { offset: 100, limit: 20 });expect(page.items).toEqual([]);expect(page.total).toBe(25);+ expect(page.rows).toBe(25);+ });++ it("pages through rows, not records, once a day's repeats fold", () => {+ // Ten more of one error on the same day: one more row, ten more records.+ for (let i = 0; i < 10; i += 1) {+ errors.insert({+ ts: `2026-07-27T01:00:${String(i).padStart(2, "0")}.000Z`,+ date: "2026-07-27",+ projectId: "p1",+ agentId: "a1",+ sessionId: "s1",+ source: "messaging",+ kind: "expected",+ code: "messaging_connect_failed",+ status: null,+ message: "gateway stopped acknowledging heartbeats",+ });+ }+ const first = service.queryErrors("p1", { offset: 0, limit: 20 });+ expect(first.total).toBe(35);+ expect(first.rows).toBe(26);+ expect(first.items[0]).toMatchObject({ code: "messaging_connect_failed", count: 10 });+ expect(service.queryErrors("p1", { offset: 20, limit: 20 }).items).toHaveLength(6);});it("filters before it offsets, so a later page never slides onto rows the summary excluded", () => {diff --git a/packages/ui-gallery/src/app/mock/fixtures.ts b/packages/ui-gallery/src/app/mock/fixtures.tsindex 8a8b2596..f3f544f5 100644--- a/packages/ui-gallery/src/app/mock/fixtures.ts+++ b/packages/ui-gallery/src/app/mock/fixtures.ts@@ -1323,6 +1323,8 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {const usageErrors: UsageErrorItem[] = [{ts: iso(ago(0, 95)),+ firstTs: iso(ago(0, 180)),+ count: 4,source: "llm",code: "rate_limited",kind: "expected",@@ -1330,6 +1332,8 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {},{ts: iso(ago(2, 40)),+ firstTs: iso(ago(2, 40)),+ count: 1,source: "http",code: "file_too_large",kind: "expected",@@ -1337,6 +1341,8 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {},{ts: iso(ago(5, 12)),+ firstTs: iso(ago(5, 12)),+ count: 1,source: "runtime",code: "internal",kind: "unexpected",diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex dda44ee8..857ebc66 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -1203,7 +1203,11 @@ routerconst items = store.f.usageErrors.filter((e) => !kind || e.kind === kind);const offset = Number(query.get("offset")) || 0;const limit = Number(query.get("limit")) || items.length;- return { items: items.slice(offset, offset + limit), total: items.length };+ return {+ items: items.slice(offset, offset + limit),+ total: items.reduce((n, e) => n + e.count, 0),+ rows: items.length,+ };}).delete("/api/projects/:projectId/usage/errors", ({ store }): UsageErrorsClearResponse => {const deleted = store.f.usageErrors.length;@@ -1333,7 +1337,8 @@ routerbyAgentSeries: [...perAgent.values()],byModelSeries: [...perModel.values()],errors: {- total: store.f.usageErrors.length,+ total: store.f.usageErrors.reduce((n, e) => n + e.count, 0),+ rows: store.f.usageErrors.length,unexpected,topCode: store.f.usageErrors[0]? {diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 8e73ecbf..fb566462 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -1142,6 +1142,12 @@ export const importAgentTrace = (projectId: string, agentId: string, body: Trace// Usage statistics ----------------------------------------------------------------------+/**+ * The browser's own offset east of UTC, in minutes. The error table folds a day's repeats into+ * one row, and the day it folds by is the reader's rather than the server's.+ */+const viewerUtcOffsetMinutes = (): string => String(-new Date().getTimezoneOffset());+/*** One page of the cost center's error table (newest first). The dashboard response already* carries the first page; this is for paging back to earlier ones without refetching the@@ -1173,6 +1179,7 @@ export const getUsageErrors = (toTs: params.toTs,agentId: params.agentId,kind: params.kind,+ utcOffsetMinutes: viewerUtcOffsetMinutes(),},});@@ -1236,6 +1243,7 @@ export const getUsage = (agentId: params.agentId,provider: params.provider,modelId: params.modelId,+ utcOffsetMinutes: viewerUtcOffsetMinutes(),},});diff --git a/packages/web/src/features/usage/errors-panel.tsx b/packages/web/src/features/usage/errors-panel.tsxindex 360bc4b9..e7e5ce75 100644--- a/packages/web/src/features/usage/errors-panel.tsx+++ b/packages/web/src/features/usage/errors-panel.tsx@@ -5,6 +5,10 @@* message). What an error needs to answer is "what exactly went wrong" — a* detail table is more direct than a chart here: the count alone in the stats already covers the summary.*+ * The server folds a day's repeats of one error into one row: the stats count records, the+ * table and its pager count rows, and a row standing for several records says how many after+ * its message.+ ** Color semantics are consistent site-wide: unexpected (500s / runtime* exceptions) is a prominent rose; expected (HttpError, business 4xx) recedes into gray.* The outer frame is provided by the caller's ChartCard (full width, below the four business charts).@@ -127,7 +131,7 @@ function Th({ children, className = "" }: { children: React.ReactNode; className/*** Error panel: stats + a recent-errors table (the server already takes the top N, newest first).- * The message column shows **one line per error by default** (kept compact — an error storm can+ * The message column shows **one line per row by default** (kept compact — an error storm can* fill the table); clicking a message expands it in place to the full text (wrapping, newlines* preserved — the upstream detail after the code, e.g. a provider's 402 body, is what matters),* and clicking again collapses it. The full text is also in the hover title. Cells align to the@@ -137,9 +141,9 @@ function Th({ children, className = "" }: { children: React.ReactNode; className* 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.+ * Clearing deletes the records the current filter selects — the set the reader is looking at,+ * not the Project's whole history — and the confirmation says which set that is and how many+ * records it holds, because a deleted error record has no other copy anywhere.*/export function ErrorsPanel({errors,@@ -167,7 +171,7 @@ export function ErrorsPanel({/** 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, unexpected, 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.)@@ -177,10 +181,10 @@ export function ErrorsPanel({const [page, setPage] = useState(0);const [items, setItems] = useState<UsageErrorItem[]>(recent);// The row count the pager counts pages against: seeded from the dashboard snapshot, then- // replaced by each page's own total. The snapshot goes stale (rows evicted by the row cap, an+ // replaced by each page's own count. The snapshot goes stale (rows evicted by the row cap, an// Agent deleted between load and click), and pinning to it computes a page count that can- // strand the caller on a page the data no longer has.- const [pagedTotal, setPagedTotal] = useState(total);+ // strand the caller on a page the data no longer has. Rows, not records: a page holds rows.+ const [pagedRows, setPagedRows] = useState(rows);const [pageError, setPageError] = useState<string | null>(null);const [loading, setLoading] = useState(false);// A new dashboard response invalidates the offsets being paged through, so paging goes back to@@ -197,7 +201,7 @@ export function ErrorsPanel({// changing a filter.if (page === 0) {setItems(recent);- setPagedTotal(total);+ setPagedRows(rows);setPageError(null);return;}@@ -209,7 +213,7 @@ export function ErrorsPanel({.then((res) => {if (cancelled) return;setItems(res.items);- setPagedTotal(res.total);+ setPagedRows(res.rows);}).catch((e: unknown) => {// Keep the rows already on screen rather than blanking the table under an error.@@ -221,9 +225,9 @@ export function ErrorsPanel({return () => {cancelled = true;};- }, [page, pageSize, projectId, filters, recent, total]);+ }, [page, pageSize, projectId, filters, recent, rows]);- const pageCount = Math.max(1, Math.ceil(pagedTotal / pageSize));+ const pageCount = Math.max(1, Math.ceil(pagedRows / pageSize));const [confirmingClear, setConfirmingClear] = useState(false);const [clearing, setClearing] = useState(false);@@ -304,7 +308,13 @@ export function ErrorsPanel({key={`${e.ts}-${i}`}className="border-t border-gray-100 dark:border-gray-800/60">- <td className="py-1.5 pr-2 align-top font-mono tabular-nums text-gray-400">+ {/* The latest of the row's records; the first is in the tooltip. */}+ <td+ className="py-1.5 pr-2 align-top font-mono tabular-nums text-gray-400"+ data-tooltip={+ e.count > 1 ? S.usage.errorsFirstAt(formatDateTime(e.firstTs)) : undefined+ }+ >{formatDateTime(e.ts)}</td><td className="py-1.5 pr-2 align-top font-mono text-gray-500 dark:text-gray-400">@@ -316,17 +326,29 @@ export function ErrorsPanel({</Badge></td><td className="py-1.5 align-top text-gray-500 dark:text-gray-400">- {/* One line by default; click to expand to the full message (wrapping), click again to collapse. */}+ {/* One line by default; click to expand to the full message (wrapping), click+ again to collapse. How many of the day's records the row stands for+ follows as a muted count, outside the truncated text so a long message+ cannot push it out of sight. */}<buttontype="button"data-tooltip={e.message}data-tooltip-content="text"onClick={() => toggle(i)}- className={`block w-full cursor-pointer text-left transition-colors hover:text-gray-700 dark:hover:text-gray-300 ${- expanded.has(i) ? "whitespace-pre-wrap break-words" : "truncate"- }`}+ className="flex w-full min-w-0 cursor-pointer items-baseline gap-1.5 text-left transition-colors hover:text-gray-700 dark:hover:text-gray-300">- {e.message}+ <span+ className={`min-w-0 ${+ expanded.has(i) ? "whitespace-pre-wrap break-words" : "truncate"+ }`}+ >+ {e.message}+ </span>+ {e.count > 1 && (+ <span className="shrink-0 tabular-nums text-gray-400 dark:text-gray-500">+ ×{e.count}+ </span>+ )}</button></td></tr>@@ -369,7 +391,7 @@ export function ErrorsPanel({onChange={setPage}previousLabel={S.usage.errorsNewer}nextLabel={S.usage.errorsOlder}- readout={S.usage.errorsPageOf(page + 1, pageCount, pagedTotal)}+ readout={S.usage.errorsPageOf(page + 1, pageCount, pagedRows)}disabled={loading}/>)}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex e0ea94a4..0db60722 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -3533,11 +3533,13 @@ Scenarios:errorsColKind: "Type",errorsColMessage: "Message",errorsEmpty: "No errors",- /** Detail-table pager: newer/older step back through pages of the same filtered set. */+ /** Time cell tooltip on a row that folds several of a day's records: when the first one was. */+ errorsFirstAt: (time: string): string => `First at ${time}`,+ /** Detail-table pager: newer/older step back through pages of the same filtered set; it counts rows, not records. */errorsNewer: "Newer",errorsOlder: "Older",- errorsPageOf: (page: number, pages: number, total: number) =>- `Page ${page} / ${pages} · ${total} total`,+ errorsPageOf: (page: number, pages: number, rows: number) =>+ `Page ${page} / ${pages} · ${rows} row${rows === 1 ? "" : "s"}`,/** Clearing the table: the action, and the confirm that must name exactly what goes. */errorsClear: "Clear",errorsClearTitle: "Clear error records",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 4b0a18b0..9929d606 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -3566,11 +3566,13 @@ Benchmark:errorsColKind: "类型",errorsColMessage: "消息",errorsEmpty: "暂无异常",- /** Detail-table pager: newer/older step back through pages of the same filtered set. */+ /** Time cell tooltip on a row that folds several of a day's records: when the first one was. */+ errorsFirstAt: (time: string): string => `首次出现于 ${time}`,+ /** Detail-table pager: newer/older step back through pages of the same filtered set; it counts rows, not records. */errorsNewer: "较新",errorsOlder: "更早",- errorsPageOf: (page: number, pages: number, total: number) =>- `第 ${page} / ${pages} 页 · 共 ${total} 条`,+ errorsPageOf: (page: number, pages: number, rows: number) =>+ `第 ${page} / ${pages} 页 · 共 ${rows} 行`,/** Clearing the table: the action, and the confirm that must name exactly what goes. */errorsClear: "清空",errorsClearTitle: "清空错误记录",diff --git a/packages/web/test/errors-panel.test.ts b/packages/web/test/errors-panel.test.tsindex f1b32d64..2c1fee11 100644--- a/packages/web/test/errors-panel.test.ts+++ b/packages/web/test/errors-panel.test.ts@@ -17,6 +17,7 @@ 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 { formatDateTime } from "../src/lib/format";import { S, setActiveStrings, zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";@@ -28,14 +29,18 @@ const item = (code: string): UsageErrorItem => ({code,kind: "unexpected",message: `${code} went wrong`,+ count: 1,+ firstTs: "2026-08-27T10:00:00.000Z",});function errorsOf(items: UsageErrorItem[]): UsageErrors {+ const total = items.reduce((sum, e) => sum + e.count, 0);return {- total: items.length,- unexpected: items.length,+ total,+ unexpected: total,topCode: null,recent: items,+ rows: items.length,};}@@ -87,6 +92,46 @@ describe("ErrorsPanel clear action", () => {});});+describe("ErrorsPanel rows", () => {+ it("a row standing for several records says how many after its message, and when the first was", () => {+ const folded: UsageErrorItem = {+ ...item("messaging_connect_failed"),+ message: "gateway stopped acknowledging heartbeats",+ count: 3,+ firstTs: "2026-08-27T06:00:00.000Z",+ };+ const html = render({ items: [folded] });+ expect(html).toContain("×3");+ expect(html).toContain(+ `data-tooltip="${S.usage.errorsFirstAt(formatDateTime(folded.firstTs))}"`,+ );+ // The time shown is the latest one.+ expect(html).toContain(formatDateTime(folded.ts));+ });++ it("a single record says nothing more than it did", () => {+ const html = render({ items: [item("internal")] });+ expect(html).not.toContain("×1");+ expect(html).not.toContain(S.usage.errorsFirstAt(formatDateTime(item("internal").ts)));+ });++ it("pages by rows, while the stats above count records", () => {+ // Ten rows on this page out of 25, standing for 40 records.+ 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 },+ projectId: "p1",+ filters: FILTERS,+ canClear: true,+ onCleared: () => {},+ }),+ );+ expect(html).toContain(S.usage.errorsPageOf(1, 3, 25));+ expect(html).toContain(">40<");+ });+});+describe("errorsClearScopeText", () => {for (const [locale, dict] of Object.entries({ zh, en })) {it(`${locale}: a custom range is named by its dates, and the Agent when one is selected`, () => {diff --git a/packages/web/test/todo-badges.test.ts b/packages/web/test/todo-badges.test.tsindex adaa6930..0f9a4148 100644--- a/packages/web/test/todo-badges.test.ts+++ b/packages/web/test/todo-badges.test.ts@@ -29,12 +29,15 @@ function agent(function errorPage(total: number, ...timestamps: string[]): UsageErrorsPage {return {total,+ rows: timestamps.length,items: timestamps.map((ts) => ({ts,source: "runtime",code: "boom",kind: "unexpected",message: "boom",+ count: 1,+ firstTs: ts,})),};}