From 7d845046e0c6446a11630ab30326c5c7375ff87a Mon Sep 17 00:00:00 2001 From: chengyongru Date: Wed, 9 Sep 2026 11:43:55 +0800 Subject: [PATCH] perf(tui): coalesce and cancel usage refreshes --- tui/src/app.ts | 55 +++++++++++++----- tui/src/protocol.ts | 18 ++++-- tui/src/usage-app.test.ts | 102 ++++++++++++++++++++++++++++++++- tui/src/usage-panel.test.ts | 27 ++++++++- tui/src/usage-panel.ts | 1 + tui/src/usage-protocol.test.ts | 45 +++++++++++++++ 6 files changed, 225 insertions(+), 23 deletions(-) diff --git a/tui/src/app.ts b/tui/src/app.ts index ab9079b06..fa489e634 100644 --- a/tui/src/app.ts +++ b/tui/src/app.ts @@ -492,7 +492,8 @@ export class NanobotTui { private readonly runtimeControls: RuntimeControls private readonly contextPanel: ContextPanel private readonly usagePanel: UsagePanel - private usageRequestId = 0 + private usageRequest: AbortController | null = null + private usageRefreshPending = false private readonly diffViewer: DiffViewer private readonly queuePreview: QueuePreview private readonly recoveryNotice: RecoveryNotice @@ -1091,8 +1092,7 @@ export class NanobotTui { if (event.event === "attached") { const switchedSession = Boolean(this.currentChatId && this.currentChatId !== event.chat_id) this.currentChatId = event.chat_id - this.usagePanel.hide() - this.usageRequestId += 1 + this.closeUsage() if (event.usage) this.lastUsage = event.usage if (event.model_preset !== undefined) { this.applyModelPreset(event.model_preset) @@ -1728,7 +1728,7 @@ export class NanobotTui { } if (this.usagePanel.visible && !key.ctrl && !key.meta) { if (key.name === "escape") { - this.usagePanel.hide() + this.closeUsage() if (this.activeTurn) this.renderActiveStatus() else this.status.content = this.readyStatus() this.updateMeta() @@ -2259,7 +2259,7 @@ export class NanobotTui { if (clearedUnsent) this.unsentSubmit = false this.runtimeControls.hide() if (this.contextPanel.visible && value) this.contextPanel.hide() - if (this.usagePanel.visible && value) this.usagePanel.hide() + if (this.usagePanel.visible && value) this.closeUsage() this.syncComposerPlaceholder() if (this.sessionMenu.visible) this.syncSessionMenu() else if (this.branchMenu.visible) this.syncBranchMenu() @@ -2389,7 +2389,7 @@ export class NanobotTui { this.skillMenu.hide() this.branchMenu.hide() this.contextPanel.hide() - this.usagePanel.hide() + this.closeUsage() this.activeMentionQuery = null this.activeSkillQuery = null } @@ -2446,7 +2446,7 @@ export class NanobotTui { } private async openBranch(): Promise { - this.usagePanel.hide() + this.closeUsage() if (this.activeTurn) { this.status.content = "Wait for the current turn or press Ctrl+C" return @@ -2517,7 +2517,7 @@ export class NanobotTui { } private async openSessions(): Promise { - this.usagePanel.hide() + this.closeUsage() this.commandMenu.hide() this.dismissRuntimeControls() this.mentionMenu.hide() @@ -2602,7 +2602,7 @@ export class NanobotTui { } private startNewChat(): void { - this.usagePanel.hide() + this.closeUsage() if (this.activeTurn) { this.status.content = "Wait for the current turn or press Ctrl+C" return @@ -2780,28 +2780,52 @@ export class NanobotTui { void this.refreshUsage() } + private closeUsage(): void { + this.usagePanel.hide() + this.usageRequest?.abort() + this.usageRequest = null + this.usageRefreshPending = false + } + private async refreshUsage(): Promise { - const requestId = ++this.usageRequestId + if (this.quitting || !this.usagePanel.visible) return + if (this.usageRequest) { + // Events during a fetch need one later snapshot, not parallel thread replays. + this.usageRefreshPending = true + return + } + const request = new AbortController() + this.usageRequest = request const chatId = this.client.activeChatId const current = () => !this.quitting && this.usagePanel.visible - && requestId === this.usageRequestId && chatId === this.client.activeChatId + && request === this.usageRequest && chatId === this.client.activeChatId try { const snapshot = await fetchSessionUsage( this.options.apiUrl, this.options.apiToken, chatId, this.apiReauthenticator, + request.signal, ) - if (!current()) return + if (!current() || this.usageRefreshPending) return this.usagePanel.show(snapshot) } catch { - if (!current()) return + if (!current() || this.usageRefreshPending) return this.usagePanel.showMessage("Usage unavailable · reopen /usage to retry") + } finally { + // A dismissed request must not clear a reopened panel's request or queued refresh. + if (request === this.usageRequest) { + this.usageRequest = null + if (this.usageRefreshPending) { + this.usageRefreshPending = false + void this.refreshUsage() + } + } } } private async openContext(): Promise { - this.usagePanel.hide() + this.closeUsage() this.commandMenu.hide() this.hideSessionMenu() this.mentionMenu.hide() @@ -2875,7 +2899,7 @@ export class NanobotTui { } private openDiff(): void { - this.usagePanel.hide() + this.closeUsage() this.commandMenu.hide() this.hideSessionMenu() this.mentionMenu.hide() @@ -2953,6 +2977,7 @@ export class NanobotTui { private handleDestroy = (): void => { this.quitting = true + this.usageRequest?.abort() this.clipboardPasteGeneration += 1 if (this.shimmerTimer) clearInterval(this.shimmerTimer) this.stopSessionRefresh() diff --git a/tui/src/protocol.ts b/tui/src/protocol.ts index 7d81e8d83..d17ad6064 100644 --- a/tui/src/protocol.ts +++ b/tui/src/protocol.ts @@ -574,11 +574,17 @@ async function fetchApi( apiToken: string, path: string, reauthenticate?: ApiReauthenticator, + signal?: AbortSignal, ): Promise { - const request = (connection: GatewayApiConnection) => fetch(`${connection.apiUrl}${path}`, { - headers: { Authorization: `Bearer ${connection.apiToken}` }, - }) + const request = (connection: GatewayApiConnection) => { + signal?.throwIfAborted() + return fetch(`${connection.apiUrl}${path}`, { + headers: { Authorization: `Bearer ${connection.apiToken}` }, + ...(signal ? { signal } : {}), + }) + } const response = await request({ apiUrl, apiToken }) + signal?.throwIfAborted() if (response.status !== 401 || !reauthenticate) return response return request(await reauthenticate(apiToken)) } @@ -594,6 +600,7 @@ async function fetchThreadPage( chatId: string, beforeCursor?: string | null, reauthenticate?: ApiReauthenticator, + signal?: AbortSignal, ): Promise { if (!apiUrl || !apiToken) return {} const key = encodeURIComponent(`websocket:${chatId}`) @@ -604,6 +611,7 @@ async function fetchThreadPage( apiToken, `/api/sessions/${key}/webui-thread?${params}`, reauthenticate, + signal, ) if (response.status === 404) return {} if (!response.ok) throw new Error(`history request failed: HTTP ${response.status}`) @@ -616,8 +624,10 @@ export async function fetchSessionUsage( apiToken: string, chatId: string, reauthenticate?: ApiReauthenticator, + signal?: AbortSignal, ): Promise { - const payload = await fetchThreadPage(apiUrl, apiToken, chatId, undefined, reauthenticate) + const payload = await fetchThreadPage(apiUrl, apiToken, chatId, undefined, reauthenticate, signal) + signal?.throwIfAborted() const snapshot: SessionUsageSnapshot = { context: null, rounds: [] } const seenTurns = new Set() let contextResolved = false diff --git a/tui/src/usage-app.test.ts b/tui/src/usage-app.test.ts index ce492a13b..5cedb0bf2 100644 --- a/tui/src/usage-app.test.ts +++ b/tui/src/usage-app.test.ts @@ -40,7 +40,7 @@ describe("TUI /usage", () => { globalThis.fetch = originalFetch }) - async function mount(history: () => Promise = async () => Response.json(page())) { + async function mount(history: (init?: RequestInit) => Promise = async () => Response.json(page())) { const sent: string[] = [] const client = { activeChatId: "chat", connect() {}, close() {}, @@ -50,9 +50,9 @@ describe("TUI /usage", () => { setWorkspaceScope() {}, async updateRecovery(): Promise { return { status: "recovered", recovery_id: "r" } }, } - globalThis.fetch = (async (input: string | URL | Request) => { + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { const url = String(input) - if (url.includes("/webui-thread")) return history() + if (url.includes("/webui-thread")) return history(init) return Response.json({ commands: [], sessions: [], skills: [], candidates: [] }) }) as typeof fetch setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen", consoleMode: "disabled" }) @@ -144,6 +144,102 @@ describe("TUI /usage", () => { expect(sent).toEqual([]) }) + test("coalesces a burst into one trailing request without displaying a stale snapshot", async () => { + const pending: Array<(response: Response) => void> = [] + const { app, ui } = await mount(() => new Promise((resolve) => pending.push(resolve))) + await open(ui) + for (let index = 0; index < 10; index++) { + app.accept({ event: "turn_end", chat_id: "chat", turn_id: `turn-${index}` }) + } + app.accept({ event: "context_compaction", chat_id: "chat", compaction_id: "c", phase: "succeeded" }) + expect(pending.length).toBe(1) + pending[0]!(Response.json(page())) + await waitUntil(() => pending.length === 2) + await setup!.flush() + expect(setup!.captureCharFrame()).toContain("Loading usage") + pending[1]!(Response.json(page(12000))) + await setup!.flush() + expect(setup!.captureCharFrame()).toContain("In 12,000") + expect(pending.length).toBe(2) + app.accept({ event: "turn_end", chat_id: "chat", turn_id: "later" }) + expect(pending.length).toBe(3) + pending[2]!(Response.json(page(15000))) + await setup!.flush() + expect(setup!.captureCharFrame()).toContain("In 15,000") + }) + + test("retries a queued refresh after failure and stays idle while hidden or streaming", async () => { + const pending: Array<(response: Response) => void> = [] + const { app, ui } = await mount(() => new Promise((resolve) => pending.push(resolve))) + app.accept({ event: "turn_end", chat_id: "chat", turn_id: "hidden" }) + expect(pending.length).toBe(0) + await open(ui) + for (let index = 0; index < 10; index++) { + app.accept({ event: "delta", chat_id: "chat", turn_id: "active", text: "token " }) + } + app.accept({ event: "context_compaction", chat_id: "chat", compaction_id: "c", phase: "started" }) + expect(pending.length).toBe(1) + app.accept({ event: "turn_end", chat_id: "chat", turn_id: "active" }) + pending[0]!(new Response(null, { status: 503 })) + await waitUntil(() => pending.length === 2) + pending[1]!(Response.json(page(12000))) + await setup!.flush() + expect(setup!.captureCharFrame()).toContain("In 12,000") + await close(ui) + app.accept({ event: "turn_end", chat_id: "chat", turn_id: "hidden-again" }) + app.accept({ event: "context_compaction", chat_id: "chat", compaction_id: "c", phase: "succeeded" }) + expect(pending.length).toBe(2) + }) + + test("aborts dismissed requests and drops queued refreshes without disrupting a reopened panel", async () => { + const pending: Array<{ signal: AbortSignal | null | undefined; finish: (response: Response) => void }> = [] + const { app, ui } = await mount((init) => new Promise((finish) => pending.push({ signal: init?.signal, finish }))) + await open(ui) + expect(pending[0]!.signal?.aborted).toBe(false) + app.accept({ event: "turn_end", chat_id: "chat", turn_id: "queued" }) + await close(ui) + expect(pending[0]!.signal?.aborted).toBe(true) + await open(ui) + expect(pending.length).toBe(2) + pending[0]!.finish(Response.json(page())) + await setup!.flush() + expect(setup!.captureCharFrame()).toContain("Loading usage") + app.accept({ event: "turn_end", chat_id: "chat", turn_id: "queued-new" }) + expect(pending.length).toBe(2) + pending[1]!.finish(Response.json(page(12000))) + await waitUntil(() => pending.length === 3) + pending[2]!.finish(Response.json(page(15000))) + await setup!.flush() + expect(setup!.captureCharFrame()).toContain("In 15,000") + expect(pending.length).toBe(3) + }) + + test.each(["typing", "attach", "destroy"])("aborts usage and queued refreshes on %s", async (action) => { + let signal: AbortSignal | null | undefined + let requests = 0 + const { app, ui, client } = await mount((init) => { + requests++ + // Session hydration is independent of the usage request. + if (requests > 1) return Promise.resolve(Response.json({ messages: [] })) + signal = init?.signal + return new Promise((_resolve, reject) => { + signal?.addEventListener("abort", () => reject(signal!.reason), { once: true }) + }) + }) + await open(ui) + app.accept({ event: "turn_end", chat_id: "chat", turn_id: "queued" }) + if (action === "typing") await setup!.mockInput.typeText("hello") + else if (action === "attach") { + client.attach("other-chat") + app.accept({ event: "attached", chat_id: "other-chat" }) + await waitUntil(() => ui.ready) + } else setup!.renderer.destroy() + await Bun.sleep(20) + expect(signal?.aborted).toBe(true) + expect(requests).toBe(action === "attach" ? 2 : 1) + if (action !== "destroy") expect(ui.usagePanel.visible).toBe(false) + }) + test("ignores an in-flight response after Escape and a newer request supersedes it", async () => { const pending: Array<(response: Response) => void> = [] const { ui } = await mount(() => new Promise((resolve) => pending.push(resolve))) diff --git a/tui/src/usage-panel.test.ts b/tui/src/usage-panel.test.ts index 567bf99c3..15f29ec56 100644 --- a/tui/src/usage-panel.test.ts +++ b/tui/src/usage-panel.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, test } from "bun:test" -import { RGBA } from "@opentui/core" +import { RGBA, type TextRenderable } from "@opentui/core" import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing" import { UsagePanel, type UsagePanelTheme } from "./usage-panel" @@ -178,6 +178,31 @@ describe("UsagePanel", () => { expect(frame).toContain("Cache 100%") }) + test("does not rebuild hidden content and uses the latest dimensions and theme when reopened", async () => { + setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" }) + const panel = new UsagePanel(setup.renderer, theme) + setup.renderer.root.add(panel.root) + const body = panel.root.getChildren()[0] as TextRenderable + const empty = body.content + panel.resize(80, 30) + panel.setTheme(theme) + expect(body.content).toBe(empty) + panel.show(snapshot) + const content = body.content + panel.hide() + setup.resize(56, 18) + panel.resize(56, 18) + panel.setTheme({ ...theme, text: "#18181B", accent: "#B94D0B", cached: "#0F766E" }) + expect(body.content).toBe(content) + panel.show(snapshot) + await setup.renderOnce() + expect(setup.captureCharFrame()).toContain("Context 9k / 262k") + expect(panel.root.height).toBeLessThanOrEqual(6) + const bars = setup.captureSpans().lines.flatMap((line) => line.spans) + .filter((span) => /[▁▂▃▄▅▆▇█]/u.test(span.text)) + expect(bars.some((span) => span.fg.equals(RGBA.fromHex("#0F766E")))).toBe(true) + }) + test("collapses vertically in short terminals and retains data across resize and theme changes", async () => { setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" }) const panel = new UsagePanel(setup.renderer, theme) diff --git a/tui/src/usage-panel.ts b/tui/src/usage-panel.ts index a856a8ff2..e519aec3a 100644 --- a/tui/src/usage-panel.ts +++ b/tui/src/usage-panel.ts @@ -108,6 +108,7 @@ export class UsagePanel { } private render(): void { + if (!this.visible) return const { theme, width } = this const compact = this.height < 20 const tiny = this.height < 14 diff --git a/tui/src/usage-protocol.test.ts b/tui/src/usage-protocol.test.ts index dae8bfae5..b9ef70df0 100644 --- a/tui/src/usage-protocol.test.ts +++ b/tui/src/usage-protocol.test.ts @@ -194,6 +194,51 @@ describe("fetchSessionUsage", () => { ]) }) + test("does not issue a request when already aborted", async () => { + const controller = new AbortController() + controller.abort() + const fetchMock = mockResponses() + const reauthenticate = mock(async () => ({ apiUrl, apiToken: "fresh" })) + await expect(fetchSessionUsage(apiUrl, apiToken, chatId, reauthenticate, controller.signal)) + .rejects.toHaveProperty("name", "AbortError") + expect(fetchMock).not.toHaveBeenCalled() + expect(reauthenticate).not.toHaveBeenCalled() + }) + + test("preserves the abort signal through authenticated retry", async () => { + const controller = new AbortController() + const fetchMock = mockResponses(new Response(null, { status: 401 }), thread([])) + const reauthenticate = mock(async () => ({ apiUrl, apiToken: "fresh" })) + expect(await fetchSessionUsage(apiUrl, apiToken, chatId, reauthenticate, controller.signal)) + .toEqual({ context: null, rounds: [] }) + expect(fetchMock.mock.calls.map(([, init]) => init?.signal)) + .toEqual([controller.signal, controller.signal]) + }) + + test("does not reauthenticate a request cancelled before its 401 arrives", async () => { + const controller = new AbortController() + const fetchMock = mockResponses(new Response(null, { status: 401 })) + const reauthenticate = mock(async () => ({ apiUrl, apiToken: "fresh" })) + const result = fetchSessionUsage(apiUrl, apiToken, chatId, reauthenticate, controller.signal) + controller.abort() + await expect(result).rejects.toHaveProperty("name", "AbortError") + expect(fetchMock).toHaveBeenCalledTimes(1) + expect(reauthenticate).not.toHaveBeenCalled() + }) + + test("does not retry when cancelled during shared reauthentication", async () => { + const controller = new AbortController() + const fetchMock = mockResponses(new Response(null, { status: 401 })) + const reauthenticate = mock(async () => { + controller.abort() + return { apiUrl, apiToken: "fresh" } + }) + await expect(fetchSessionUsage(apiUrl, apiToken, chatId, reauthenticate, controller.signal)) + .rejects.toHaveProperty("name", "AbortError") + expect(fetchMock).toHaveBeenCalledTimes(1) + expect(reauthenticate).toHaveBeenCalledTimes(1) + }) + test("rejects 401 without reauthentication and stops after one rejected refresh", async () => { const fetchMock = mockResponses(...Array.from({ length: 3 }, () => new Response("unauthorized", { status: 401 })))