A local-first multi-agent app development platform, built on PenguinHarness
fix(usage): opening the clear confirmation refreshes the cost center's stats
lmliheng60960406a7e8
diff --git a/changelog/unreleased/2026-10-20-cost-center-refresh.md b/changelog/unreleased/2026-10-20-cost-center-refresh.mdnew file mode 100644index 00000000..87a02cfc--- /dev/null+++ b/changelog/unreleased/2026-10-20-cost-center-refresh.md@@ -0,0 +1,32 @@+# Cost center: opening the clear confirmation refreshes the stats behind it++- **Date:** 2026-10-20+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文版](2026-10-20-cost-center-refresh.zh.md)++The "clear errors" confirmation names, in words, how many records it will delete — a count read+at the moment of the click. But the panel behind it (total / unexpected / expected) still showed+the dashboard's snapshot from page load, and loading the cost center records an error of its own+(a member's shell reads the machine list and gets a 403). So the sentence could say 4 while the+stats right behind it said 2: two numbers on one screen, describing the same action.++Opening the confirmation now re-reads the dashboard, so the panel and the sentence agree.++## Details++- The re-read runs in the background and never delays the dialog: the confirmation always opens+ on the count it just read, even when the second request is slow or fails.+- The number in the sentence — and the `until` boundary — stays the one that click read; a+ snapshot arriving later does not rewrite it.+- A failed re-read leaves the confirmation fully usable and the delete goes through; the next+ successful read catches the stats up.+- Cancelling sends no further request and leaves the caught-up panel in place.+- Side effect worth knowing: the re-read also puts the error table back on its first page (the+ new snapshot invalidates the offsets the reader was paging through).++## Compatibility++- No API, wire-format or dependency change; the page simply issues one more dashboard read.diff --git a/changelog/unreleased/2026-10-20-cost-center-refresh.zh.md b/changelog/unreleased/2026-10-20-cost-center-refresh.zh.mdnew file mode 100644index 00000000..dd7a6af7--- /dev/null+++ b/changelog/unreleased/2026-10-20-cost-center-refresh.zh.md@@ -0,0 +1,27 @@+# 成本中心:打开「清空」确认框时,面板背后的统计跟着刷新++- **Date:** 2026-10-20+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[English](2026-10-20-cost-center-refresh.md)++「清空错误记录」的确认框会把要删的条数写在句子里,而这个数字是点下去那一刻现读的。可它背后的+面板(总数 / 未预期 / 已预期)仍停在页面加载时那份快照上 —— 而加载成本中心本身就会记下一条错误+(成员的界面去读机器列表,端点回 403),所以句子写着 4 条、背后却写着 2 条:同一次操作,屏幕上+两个数字互相矛盾。++现在打开确认框时会顺手把仪表盘重读一次,面板与句子说同一件事。++## 细节++- 重读在后台进行、不阻塞对话:确认框总是先用它刚读到的那份计数打开,网络慢或失败也不会推迟它。+- 句子里的数字仍是那次点击读到的计数(也仍是 `until` 的边界),不会因为随后到达的快照而改写。+- 重读失败时确认框照常可用、照常删除;下一次成功的重读再把面板上的数字补上。+- 取消不会多发请求,面板保持已经追上的数字。+- 顺带的行为:重读会把错误表带回第一页(那边的新快照本来就让旧页码失效)。++## 兼容性++- 没有接口、传输格式或依赖变化;只多了一次页面自己发起的仪表盘读请求。diff --git a/packages/web/e2e/cost-center-refresh.spec.mjs b/packages/web/e2e/cost-center-refresh.spec.mjsnew file mode 100644index 00000000..b5a931e2--- /dev/null+++ b/packages/web/e2e/cost-center-refresh.spec.mjs@@ -0,0 +1,221 @@+/**+ * Regression: opening the clear confirmation also refreshes the dashboard behind it.+ *+ * The cost center's stats ("总数 / 未预期 / 已预期") are the dashboard response's numbers, and+ * that response is taken before the page's own requests are answered — loading the page records+ * one of them (a member's shell asks for the machine list and gets a 403 `admin_required`). So+ * the dialog could name a larger count than the panel right behind it showed: the sentence read+ * "3 records" over a stats row still saying "2". The fix refreshes the dashboard when the+ * confirmation opens, in the background — the dialog still opens on the count it just read.+ *+ * Two properties:+ *+ * 1. **The refresh happens, and it is the only new read.** Opening the confirmation issues one+ * more dashboard GET, whose answer is what the stats then show; cancelling does not issue+ * another, and leaves the caught-up panel in place.+ * 2. **A failed refresh does not disturb the confirmation.** The dialog stays open, keeps its+ * sentence, and the delete still takes exactly that set; the next successful reload catches+ * the panel up.+ *+ * The errors are the app's real ones: the mock rejects the auth prompt with 401 (`unexpected`)+ * and the quota prompt with 403 (also `unexpected`, a fatal turn), both reaching `error_records`+ * through the server's own recorder. Every number asserted comes from a response the page+ * itself received, so a rerun on a data root that is not fresh still holds.+ */+import { test, expect } from "@playwright/test";+import { provisionAndLogin } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;+const P = "password123";++/** The dashboard read the panel's stats come from. */+const isDashboard = (r) => r.url().includes("/usage?") && r.request().method() === "GET";++/** The confirmation's own count read: the first page of the error table, no `kind`. */+const isCountRead = (r) => {+ if (!r.url().includes("/usage/errors?") || r.request().method() !== "GET") return false;+ const u = new URL(r.url());+ return u.searchParams.get("limit") === "1" && !u.searchParams.has("kind");+};++const isDelete = (r) => r.url().includes("/usage/errors") && r.request().method() === "DELETE";++/** The panel's "总数" stat as the reader sees it — "总数 4". */+async function statTotal(page) {+ const stat = page.getByText("总数", { exact: true }).locator("..");+ return (await stat.innerText()).replace(/\s+/g, " ");+}++/** Provision the user, point the Project at the mock (a key the mock rejects), open one Session. */+async function prepare(page, userId) {+ await provisionAndLogin(page.request, userId, P);+ const { projects } = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects[0].projectId;+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel: { provider: "custom", modelId: "claude-4-8" },+ models: [+ {+ provider: "custom",+ modelId: "claude-4-8",+ apiKey: "sk-auth-bad",+ baseUrl: MOCK,+ contextWindow: 200000,+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();+ return { projectId, sessionId: await newSession(page, projectId) };+}++/** One more Session on the same Project (the mock picks its branch off the whole request body). */+async function newSession(page, projectId) {+ const sess = await page.request.post(+ `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,+ { data: { provider: "custom", modelId: "claude-4-8" } },+ );+ expect(sess.ok(), "create session").toBeTruthy();+ return (await sess.json()).session.sessionId;+}++/** One failed turn through the API; resolves once the Trace holds its terminal `request_end`. */+async function failedTurn(page, sessionId, text, code) {+ const res = await page.request.post(`${BASE}/api/sessions/${sessionId}/tasks`, {+ data: { input: [{ type: "text", text }] },+ });+ expect(res.status(), "start task").toBe(202);+ await expect+ .poll(+ async () => {+ const { messages } = await (+ await page.request.get(`${BASE}/api/sessions/${sessionId}/messages`)+ ).json();+ return messages.some(+ (m) => m.payload.type === "request_end" && m.payload.error_code === code,+ );+ },+ { timeout: 30_000 },+ )+ .toBe(true);+}++test("opening the confirmation refreshes the dashboard behind it, and cancelling keeps it", async ({+ page,+}) => {+ test.setTimeout(120_000);+ const { projectId, sessionId } = await prepare(page, "refreshstats");++ // One failed turn on the books before the shell loads; it records two entries (the provider+ // error and the fatal turn), but the test never hard-codes them — every number is read back.+ await failedTurn(page, sessionId, "auth dead test", "auth");++ let dashboards = 0;+ page.on("response", (r) => {+ if (isDashboard(r)) dashboards += 1;+ });+ const loaded = page.waitForResponse(isDashboard);+ await page.goto(`${BASE}/usage`);+ const atLoad = await (await loaded).json();+ await expect(page.locator("tbody tr")).toHaveCount(atLoad.errors.recent.length);+ await expect.poll(async () => statTotal(page)).toBe(`总数 ${atLoad.errors.total}`);++ // Past the recorder's 2 s dedup window, one more surprise while the tab stays open: the panel+ // keeps the load's snapshot, while the API now counts more.+ await page.waitForTimeout(2_500);+ await failedTurn(page, await newSession(page, projectId), "quota fatal test", "rejected");+ expect(dashboards, "nothing reloaded the page between the load and the click").toBe(1);+ await expect.poll(async () => statTotal(page)).toBe(`总数 ${atLoad.errors.total}`);++ // Opening the confirmation reads the count itself, and then refreshes the dashboard so the+ // stats behind the dialog say the same thing. Both responses are awaited from before the click.+ const counted = page.waitForResponse(isCountRead, { timeout: 15_000 });+ const refreshed = page.waitForResponse(isDashboard, { timeout: 15_000 });+ await page.getByRole("button", { name: "清空", exact: true }).click();+ const countedBody = await (await counted).json();+ const refreshedBody = await (await refreshed).json();+ const dialog = page.getByRole("dialog");+ await expect(dialog).toBeVisible();+ expect(dashboards, "opening the dialog issues exactly one more dashboard read").toBe(2);+ expect(+ refreshedBody.errors.total,+ "the refresh sees the records the snapshot missed",+ ).toBeGreaterThan(atLoad.errors.total);+ expect(refreshedBody.errors.total).toBeGreaterThanOrEqual(countedBody.total);+ // The stats behind the dialog catch up to that read; the sentence stays the count the dialog+ // itself read, not the dashboard's later snapshot.+ await expect.poll(async () => statTotal(page)).toBe(`总数 ${refreshedBody.errors.total}`);+ await expect(dialog).toContainText(`近 7 天内的 ${countedBody.total} 条错误记录`);++ // Cancel: nothing is deleted, no third read goes out, and the caught-up panel stays caught up.+ const deletes = [];+ page.on("request", (r) => {+ if (r.url().includes("/usage/errors") && r.method() === "DELETE") deletes.push(r.url());+ });+ await page.getByRole("button", { name: "取消" }).click();+ await expect(dialog).toHaveCount(0);+ expect(deletes).toHaveLength(0);+ expect(dashboards, "cancelling issues no further read").toBe(2);+ expect(await statTotal(page)).toBe(`总数 ${refreshedBody.errors.total}`);+});++test("a dashboard refresh that fails leaves the confirmation intact, and the delete still goes", async ({+ page,+}) => {+ test.setTimeout(120_000);+ const { sessionId } = await prepare(page, "refreshfail");+ await failedTurn(page, sessionId, "auth dead test", "auth");++ // Only the reload issued from the confirmation fails; the initial load must succeed.+ let failDashboard = false;+ await page.route("**/api/projects/*/usage*", async (route) => {+ const url = route.request().url();+ if (!failDashboard || !url.includes("/usage?") || route.request().method() !== "GET") {+ return route.fallback();+ }+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({+ error: { code: "usage_store_closed", message: "usage store is closed" },+ }),+ });+ });++ const loaded = page.waitForResponse(isDashboard);+ await page.goto(`${BASE}/usage`);+ const atLoad = await (await loaded).json();+ await expect(page.locator("tbody tr")).toHaveCount(atLoad.errors.recent.length);++ failDashboard = true;+ const failed = page.waitForResponse((r) => isDashboard(r) && r.status() === 500, {+ timeout: 15_000,+ });+ const counted = page.waitForResponse(isCountRead, { timeout: 15_000 });+ await page.getByRole("button", { name: "清空", exact: true }).click();+ const countedBody = await (await counted).json();+ await failed;+ const dialog = page.getByRole("dialog");+ // The refresh is background work: a refused one costs the reader nothing here. The dialog is+ // open, names the set the count read saw, and the stats behind it keep the last good snapshot.+ await expect(dialog).toBeVisible();+ await expect(dialog).toContainText(`近 7 天内的 ${countedBody.total} 条错误记录`);+ expect(await statTotal(page)).toBe(`总数 ${atLoad.errors.total}`);++ // Recovery, then the write: it carries the boundary the dialog named and closes on success.+ failDashboard = false;+ const reply = page.waitForResponse(isDelete);+ await dialog.getByRole("button", { name: "清空" }).click();+ const deleteResponse = await reply;+ const deleteUrl = new URL(deleteResponse.request().url());+ expect(deleteUrl.searchParams.get("until")).toBe(countedBody.items[0].ts);+ const { deleted } = await deleteResponse.json();+ expect(deleted).toBe(countedBody.total);+ await expect(dialog).toHaveCount(0);+ await expect(page.getByText(`已删除 ${deleted} 条错误记录`)).toBeVisible();+ // The next successful reload catches the panel up: table empty, stats zero, notice gone.+ await expect(page.locator("tbody tr")).toHaveCount(0);+ await expect(page.getByText("暂无异常")).toBeVisible();+ await expect.poll(async () => statTotal(page)).toBe("总数 0");+});diff --git a/packages/web/src/features/usage/errors-panel.tsx b/packages/web/src/features/usage/errors-panel.tsxindex 297d4f8a..27c2a06a 100644--- a/packages/web/src/features/usage/errors-panel.tsx+++ b/packages/web/src/features/usage/errors-panel.tsx@@ -153,7 +153,7 @@ export function ErrorsPanel({filters,preset,canClear,- onCleared,+ onReload,}: {errors: UsageErrors;projectId: string;@@ -170,8 +170,13 @@ export function ErrorsPanel({* from offering an action that can only end in a 403.*/canClear: boolean;- /** Reload the dashboard after a clear — the stats above the table are the caller's data. */- onCleared: () => void;+ /**+ * Reload the dashboard — the stats above the table are the caller's data, not this panel's.+ * Called after a clear, and when the confirmation opens: the sentence names a count read at+ * the click, and the stats behind it would otherwise keep the snapshot from before the page's+ * own requests were answered, disagreeing with the dialog in front of the reader.+ */+ onReload: () => void;}) {const { total, unexpected, topCode, recent, rows } = errors;// Page size is read off the first page rather than duplicating the server's ERROR_RECENT_N:@@ -257,11 +262,17 @@ export function ErrorsPanel({if (res.total === 0 || newest === undefined) {// Emptied between the dashboard's read and this click: nothing to confirm, so the// panel catches up instead of offering a delete of nothing.- onCleared();+ onReload();return;}setConfirmTarget({ total: res.total, until: newest });setConfirmingClear(true);+ // The stats above the table still show the dashboard's snapshot, which is older than this+ // read by exactly the requests that made this dialog necessary (loading the cost center+ // records an expected 403 of its own). Refresh in the background, not awaited: the+ // confirmation must open on the count it just read even if that second request is slow or+ // fails.+ onReload();} catch (e) {toastError(apiErrorText(e));} finally {@@ -281,7 +292,7 @@ export function ErrorsPanel({toastSuccess(S.usage.errorsClearDone(res.deleted));// The stats above the table are the dashboard's own numbers, so the whole response is// refetched rather than patched here; that also restores page 0 from the new snapshot.- onCleared();+ onReload();} catch (e) {toastError(apiErrorText(e));} finally {diff --git a/packages/web/src/features/usage/usage-page.tsx b/packages/web/src/features/usage/usage-page.tsxindex 959c624e..fac37914 100644--- a/packages/web/src/features/usage/usage-page.tsx+++ b/packages/web/src/features/usage/usage-page.tsx@@ -491,8 +491,9 @@ export function UsagePage() {// Clearing the log is a Project-level management operation, gated on the owner// by the route; a member reads the panel without the action.canClear={currentProject?.role === "owner"}- // Reload both the table and its notice after clearing the log.- onCleared={() => {+ // Reload the table, its stats and its notice: after clearing the log, and when+ // the clear confirmation opens (so the panel behind it agrees with its sentence).+ onReload={() => {void load();}}/>diff --git a/packages/web/test/errors-panel.test.ts b/packages/web/test/errors-panel.test.tsindex 8ca585b1..3664714a 100644--- a/packages/web/test/errors-panel.test.ts+++ b/packages/web/test/errors-panel.test.ts@@ -60,7 +60,7 @@ function render(projectId: "p1",filters: opts.filters ?? FILTERS,canClear: opts.canClear ?? true,- onCleared: () => {},+ onReload: () => {},}),);}@@ -124,7 +124,7 @@ describe("ErrorsPanel rows", () => {projectId: "p1",filters: FILTERS,canClear: true,- onCleared: () => {},+ onReload: () => {},}),);expect(html).toContain(S.usage.errorsPageOf(1, 3, 25));