Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(tui): add /usage context and token charts
chengyongrub7fc4146e023
diff --git a/tui/README.md b/tui/README.mdindex 22c8516b7..2e1c2c4d9 100644--- a/tui/README.md+++ b/tui/README.md@@ -74,6 +74,19 @@ summary, replayable raw suffix, and an estimated token count. It deliberately doprivate reasoning and does not pretend to be the complete model prompt; workspace instructions,memory, and skills are assembled separately by the Python runtime.+`/usage` shows the latest measured context occupancy and up to eight recent logical model+rounds from the latest history page, matching the WebUI usage chart. Bar heights represent input+tokens; orange indicates uncached input, teal indicates cached input, and gray means cache usage+is unknown. Use `Left`/`Right` to inspect a round's input, output, cache hit rate, generation time,+and estimated-usage indicator; `Esc` closes the panel. Details collapse in short terminals.+The panel refreshes when a turn ends while open. Missing usage is not treated as zero, and a+successful compaction hides the old context meter until a later request reports context usage.+Bar heights and cache boundaries are rounded independently to eighths of a character row;+positive input always occupies at least one eighth. Mixed full cells use both foreground and+background colors. If a partial top cell contains empty space and both token categories, it+keeps its height and uses the larger category's color because a terminal cell has only two colors.+Use the numeric details for exact token counts; the chart remains a grid approximation.+`/diff` opens the latest turn's file changes in a full-screen unified diff. Use `Left`/`Right`to switch edits, `PageUp`/`PageDown` or `Home`/`End` to navigate, and `Esc` to return to chat.The gateway remains the source of the patch; the TUI never rereads workspace files to rebuild it.diff --git a/tui/src/app.ts b/tui/src/app.tsindex 9c4c965f8..ab9079b06 100644--- a/tui/src/app.ts+++ b/tui/src/app.ts@@ -27,6 +27,7 @@ import {fetchGatewayConnection,fetchMentionCandidates,fetchSessionContext,+ fetchSessionUsage,fetchSessions,fetchSlashCommands,type ApiReauthenticator,@@ -56,6 +57,7 @@ import {} from "./command-menu"import { SessionMenu, sessionLabel } from "./session-menu"import { ContextPanel, formatTokenCount, type ContextPanelTheme } from "./context-panel"+import { UsagePanel, type UsagePanelTheme } from "./usage-panel"import {DiffViewer,latestTurnFileEdits,@@ -214,6 +216,12 @@ const LOCAL_COMMANDS: TuiCommand[] = [description: "Explain what this session contributes to the next prompt",action: "context",},+ {+ command: "/usage",+ title: "Token usage",+ description: "Show context occupancy and recent model-call input tokens",+ action: "usage",+ },{command: "/diff",title: "Last turn diff",@@ -311,6 +319,10 @@ function contextPanelTheme(palette: Palette): ContextPanelTheme {}}+function usagePanelTheme(palette: Palette): UsagePanelTheme {+ return { ...palette, cached: palette.cool }+}+function diffViewerTheme(palette: Palette, backgroundKnown: boolean): DiffViewerTheme {const light = palette === LIGHTreturn {@@ -479,6 +491,8 @@ export class NanobotTui {private readonly branchMenu: BranchMenuprivate readonly runtimeControls: RuntimeControlsprivate readonly contextPanel: ContextPanel+ private readonly usagePanel: UsagePanel+ private usageRequestId = 0private readonly diffViewer: DiffViewerprivate readonly queuePreview: QueuePreviewprivate readonly recoveryNotice: RecoveryNotice@@ -603,6 +617,7 @@ export class NanobotTui {this.skillMenu = new SkillMenu(renderer, commandMenuTheme(this.palette))this.branchMenu = new BranchMenu(renderer, commandMenuTheme(this.palette))this.contextPanel = new ContextPanel(renderer, contextPanelTheme(this.palette))+ this.usagePanel = new UsagePanel(renderer, usagePanelTheme(this.palette))this.diffViewer = new DiffViewer(renderer,diffViewerTheme(this.palette, this.backgroundKnown),@@ -828,6 +843,7 @@ export class NanobotTui {this.shell.add(this.skillMenu.root)this.shell.add(this.branchMenu.root)this.shell.add(this.contextPanel.root)+ this.shell.add(this.usagePanel.root)this.shell.add(this.runtimeControls.menuRoot)this.shell.add(this.title)this.shell.add(this.queuePreview.root)@@ -984,6 +1000,7 @@ export class NanobotTui {if (command?.source === "tui") {if (command.command.action === "sessions") void this.openSessions()else if (command.command.action === "context") void this.openContext()+ else if (command.command.action === "usage") this.openUsage()else if (command.command.action === "diff") this.openDiff()else if (command.command.action === "branch") void this.openBranch()else if (command.command.action === "detach") this.quit(true)@@ -1074,6 +1091,8 @@ 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 += 1if (event.usage) this.lastUsage = event.usageif (event.model_preset !== undefined) {this.applyModelPreset(event.model_preset)@@ -1116,6 +1135,7 @@ export class NanobotTui {switch (event.event) {case "context_compaction":this.transcript.compaction({ id: event.compaction_id, phase: event.phase })+ if (event.phase === "succeeded" && this.usagePanel.visible) void this.refreshUsage()returncase "message_accepted":this.reconcileTurnOwnership(event)@@ -1244,6 +1264,7 @@ export class NanobotTui {: ""this.status.content = this.readyStatus()if (this.contextTokens !== null) void this.refreshContextEstimate(event.chat_id)+ if (this.usagePanel.visible) void this.refreshUsage()this.sendNextFollowUp()returncase "goal_status":@@ -1636,6 +1657,10 @@ export class NanobotTui {this.status.content = "Images cannot be queued · press Enter to send now"return}+ if (this.commandMenu.resolve(visibleContent)?.source === "tui") {+ this.status.content = "Local commands cannot be queued · press Enter to run"+ return+ }const content = this.draft.expand(visibleContent).trim()if (!content) returnthis.promptQueue.enqueue({@@ -1701,6 +1726,21 @@ export class NanobotTui {key.preventDefault()return}+ if (this.usagePanel.visible && !key.ctrl && !key.meta) {+ if (key.name === "escape") {+ this.usagePanel.hide()+ if (this.activeTurn) this.renderActiveStatus()+ else this.status.content = this.readyStatus()+ this.updateMeta()+ key.preventDefault()+ return+ }+ if (key.name === "left" || key.name === "right") {+ this.usagePanel.move(key.name === "left" ? -1 : 1)+ key.preventDefault()+ return+ }+ }if (this.contextPanel.visible && key.name === "escape") {this.contextPanel.hide()this.status.content = this.readyStatus()@@ -1969,6 +2009,7 @@ export class NanobotTui {this.branchMenu.setTheme(commandMenuTheme(this.palette))this.runtimeControls.setTheme(runtimeControlsTheme(this.palette))this.contextPanel.setTheme(contextPanelTheme(this.palette))+ this.usagePanel.setTheme(usagePanelTheme(this.palette))this.diffViewer.setTheme(diffViewerTheme(this.palette, this.backgroundKnown))this.queuePreview.setTheme(queuePreviewTheme(this.palette))this.recoveryNotice.setTheme(recoveryNoticeTheme(this.palette))@@ -1990,6 +2031,7 @@ export class NanobotTui {this.resizeComposer()this.syncComposerPlaceholder()this.contextPanel.resize(this.renderer.height)+ this.usagePanel.resize(this.renderer.width, this.renderer.height)this.diffViewer.resize(this.renderer.width)this.title.visible = this.renderer.height >= 14this.runtimeControls.resize(this.renderer.width)@@ -2001,6 +2043,7 @@ export class NanobotTui {const mode: FooterMode = this.runtimeControls.visible ? "runtime": this.mentionMenu.visible ? "mention": this.skillMenu.visible ? "skill"+ : this.usagePanel.visible ? "usage": this.activeTurn ? "active": this.branchMenu.visible ? "branch": this.commandMenu.visible ? "command"@@ -2216,6 +2259,7 @@ export class NanobotTui {if (clearedUnsent) this.unsentSubmit = falsethis.runtimeControls.hide()if (this.contextPanel.visible && value) this.contextPanel.hide()+ if (this.usagePanel.visible && value) this.usagePanel.hide()this.syncComposerPlaceholder()if (this.sessionMenu.visible) this.syncSessionMenu()else if (this.branchMenu.visible) this.syncBranchMenu()@@ -2345,6 +2389,7 @@ export class NanobotTui {this.skillMenu.hide()this.branchMenu.hide()this.contextPanel.hide()+ this.usagePanel.hide()this.activeMentionQuery = nullthis.activeSkillQuery = null}@@ -2401,6 +2446,7 @@ export class NanobotTui {}private async openBranch(): Promise<void> {+ this.usagePanel.hide()if (this.activeTurn) {this.status.content = "Wait for the current turn or press Ctrl+C"return@@ -2471,6 +2517,7 @@ export class NanobotTui {}private async openSessions(): Promise<void> {+ this.usagePanel.hide()this.commandMenu.hide()this.dismissRuntimeControls()this.mentionMenu.hide()@@ -2555,6 +2602,7 @@ export class NanobotTui {}private startNewChat(): void {+ this.usagePanel.hide()if (this.activeTurn) {this.status.content = "Wait for the current turn or press Ctrl+C"return@@ -2724,7 +2772,36 @@ export class NanobotTui {}}+ private openUsage(): void {+ this.closeTransientMenus()+ this.clearComposer()+ this.usagePanel.showMessage("Loading usage…")+ this.updateMeta()+ void this.refreshUsage()+ }++ private async refreshUsage(): Promise<void> {+ const requestId = ++this.usageRequestId+ const chatId = this.client.activeChatId+ const current = () => !this.quitting && this.usagePanel.visible+ && requestId === this.usageRequestId && chatId === this.client.activeChatId+ try {+ const snapshot = await fetchSessionUsage(+ this.options.apiUrl,+ this.options.apiToken,+ chatId,+ this.apiReauthenticator,+ )+ if (!current()) return+ this.usagePanel.show(snapshot)+ } catch {+ if (!current()) return+ this.usagePanel.showMessage("Usage unavailable · reopen /usage to retry")+ }+ }+private async openContext(): Promise<void> {+ this.usagePanel.hide()this.commandMenu.hide()this.hideSessionMenu()this.mentionMenu.hide()@@ -2798,6 +2875,7 @@ export class NanobotTui {}private openDiff(): void {+ this.usagePanel.hide()this.commandMenu.hide()this.hideSessionMenu()this.mentionMenu.hide()diff --git a/tui/src/command-menu.ts b/tui/src/command-menu.tsindex 31e403318..58cdb2cb4 100644--- a/tui/src/command-menu.ts+++ b/tui/src/command-menu.ts@@ -9,6 +9,7 @@ type TuiCommandAction =| "sessions"| "new-chat"| "context"+ | "usage"| "diff"| "branch"| "detach"diff --git a/tui/src/footer-hints.ts b/tui/src/footer-hints.tsindex 67baf706b..8bac3ab6a 100644--- a/tui/src/footer-hints.ts+++ b/tui/src/footer-hints.ts@@ -22,6 +22,7 @@ export type FooterMode =| "command"| "session"| "context"+ | "usage"| "history"| "ready"@@ -87,6 +88,7 @@ function hintsFor(if (mode === "session") return width >= 64? [hint("type", "filter"), hint("↑↓", "choose"), hint("enter", "open"), hint("esc", "close")]: [hint("enter", "open"), hint("esc", "close")]+ if (mode === "usage") return [hint("←→", "round"), hint("esc", "close")]if (mode === "context") return [hint("esc", "close"), hint("pgup/pgdn", "scroll")]if (mode === "history") return width >= 72? [hint("ctrl+end", "latest"), hint("pgup/pgdn", "scroll")]diff --git a/tui/src/protocol.ts b/tui/src/protocol.tsindex 40771f8b2..7d81e8d83 100644--- a/tui/src/protocol.ts+++ b/tui/src/protocol.ts@@ -263,6 +263,11 @@ export interface TokenUsage {timed_requests?: number}+export interface SessionUsageSnapshot {+ context: { tokens: number; windowTokens?: number } | null+ rounds: TokenUsage[]+}+export interface SessionContextSnapshot {totalMessages: numberarchivedMessages: number@@ -578,16 +583,19 @@ async function fetchApi(return request(await reauthenticate(apiToken))}-export async function fetchHistory(+interface ThreadPage {+ messages?: Array<Record<string, unknown>>+ page?: { has_more_before?: boolean; before_cursor?: string; user_message_offset?: number }+}++async function fetchThreadPage(apiUrl: string,apiToken: string,chatId: string,beforeCursor?: string | null,reauthenticate?: ApiReauthenticator,-): Promise<HistorySnapshot> {- if (!apiUrl || !apiToken) {- return { messages: [], hasMoreBefore: false, beforeCursor: null, userMessageOffset: 0 }- }+): Promise<ThreadPage> {+ if (!apiUrl || !apiToken) return {}const key = encodeURIComponent(`websocket:${chatId}`)const params = new URLSearchParams({ limit: "120", direction: "latest" })if (beforeCursor) params.set("before", beforeCursor)@@ -597,14 +605,61 @@ export async function fetchHistory(`/api/sessions/${key}/webui-thread?${params}`,reauthenticate,)- if (response.status === 404) {- return { messages: [], hasMoreBefore: false, beforeCursor: null, userMessageOffset: 0 }- }+ if (response.status === 404) return {}if (!response.ok) throw new Error(`history request failed: HTTP ${response.status}`)- const payload = (await response.json()) as {- messages?: Array<Record<string, unknown>>- page?: { has_more_before?: boolean; before_cursor?: string; user_message_offset?: number }+ return await response.json() as ThreadPage+}++/** Same recent model-call samples and context boundary as the WebUI usage popover. */+export async function fetchSessionUsage(+ apiUrl: string,+ apiToken: string,+ chatId: string,+ reauthenticate?: ApiReauthenticator,+): Promise<SessionUsageSnapshot> {+ const payload = await fetchThreadPage(apiUrl, apiToken, chatId, undefined, reauthenticate)+ const snapshot: SessionUsageSnapshot = { context: null, rounds: [] }+ const seenTurns = new Set<unknown>()+ let contextResolved = false+ for (const message of [...(payload.messages ?? [])].reverse()) {+ if (message.kind === "compaction" && isRecord(message.compaction)+ && message.compaction.phase === "succeeded") contextResolved = true+ if (message.role !== "assistant" || message.kind === "trace" || message.isStreaming) continue+ const usage = isTokenUsage(message.usage) ? message.usage : null+ if (!contextResolved && typeof usage?.context_tokens === "number"+ && Number.isFinite(usage.context_tokens) && usage.context_tokens >= 0) {+ const window = message.contextWindowTokens+ snapshot.context = {+ tokens: usage.context_tokens,+ ...(typeof window === "number" && Number.isFinite(window) && window > 0+ ? { windowTokens: window } : {}),+ }+ contextResolved = true+ }+ const turnKey = message.turnId || message.id || message+ if (seenTurns.has(turnKey)) continue+ seenTurns.add(turnKey)+ const rounds = Array.isArray(message.roundUsages) ? message.roundUsages : []+ for (const round of [...rounds].reverse()) {+ if (snapshot.rounds.length >= 8) break+ if (isTokenUsage(round) && typeof round.prompt_tokens === "number"+ && Number.isFinite(round.prompt_tokens) && round.prompt_tokens > 0) {+ snapshot.rounds.push(round)+ }+ }}+ snapshot.rounds.reverse()+ return snapshot+}++export async function fetchHistory(+ apiUrl: string,+ apiToken: string,+ chatId: string,+ beforeCursor?: string | null,+ reauthenticate?: ApiReauthenticator,+): Promise<HistorySnapshot> {+ const payload = await fetchThreadPage(apiUrl, apiToken, chatId, beforeCursor, reauthenticate)let userIndex = typeof payload.page?.user_message_offset === "number"? Math.max(0, payload.page.user_message_offset): 0diff --git a/tui/src/usage-app.test.ts b/tui/src/usage-app.test.tsnew file mode 100644index 000000000..ce492a13b--- /dev/null+++ b/tui/src/usage-app.test.ts@@ -0,0 +1,199 @@+import { afterEach, describe, expect, test } from "bun:test"+import { type TextareaRenderable } from "@opentui/core"+import { MockTreeSitterClient, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"++import { NanobotTui } from "./app"+import type { UsagePanel } from "./usage-panel"+import type { RecoveryState } from "./protocol"++const originalFetch = globalThis.fetch+const page = (input = 9000) => ({+ messages: [{+ id: "reply", turnId: "turn", role: "assistant", content: "Saved reply",+ usage: { prompt_tokens: 15000, context_tokens: 9000 }, contextWindowTokens: 262144,+ roundUsages: [+ { prompt_tokens: 3000, completion_tokens: 100, cached_tokens: 0 },+ { prompt_tokens: input, completion_tokens: 200, cached_tokens: 6000 },+ ],+ }],+})++async function waitUntil(predicate: () => boolean): Promise<void> {+ const deadline = Date.now() + 2000+ while (!predicate() && Date.now() < deadline) await Bun.sleep(5)+ expect(predicate()).toBe(true)+}++// The mounted app owns these retained renderables; assertions exercise keyboard input and frames.+interface MountedUI {+ composer: TextareaRenderable+ usagePanel: UsagePanel+ commandMenu: { visible: boolean }+ ready: boolean+}++describe("TUI /usage", () => {+ let setup: TestRendererSetup | undefined+ afterEach(() => {+ if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()+ setup = undefined+ globalThis.fetch = originalFetch+ })++ async function mount(history: () => Promise<Response> = async () => Response.json(page())) {+ const sent: string[] = []+ const client = {+ activeChatId: "chat", connect() {}, close() {},+ send(content: string) { sent.push(content); return "turn" },+ attach(chatId: string) { this.activeChatId = chatId },+ newChat() { this.activeChatId = "new-chat" },+ setWorkspaceScope() {},+ async updateRecovery(): Promise<RecoveryState> { return { status: "recovered", recovery_id: "r" } },+ }+ globalThis.fetch = (async (input: string | URL | Request) => {+ const url = String(input)+ if (url.includes("/webui-thread")) return history()+ return Response.json({ commands: [], sessions: [], skills: [], candidates: [] })+ }) as typeof fetch+ setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen", consoleMode: "disabled" })+ const app = NanobotTui.mount(setup.renderer, {+ wsUrl: "ws://localhost.invalid/ws", apiUrl: "http://nanobot.test", apiToken: "test-token",+ model: "test/model", modelPreset: "default", workspace: "/test", version: "test",+ access: "workspace access", theme: "dark",+ }, client, new MockTreeSitterClient({ autoResolveTimeout: 0 }))+ app.accept({ event: "attached", chat_id: "chat" })+ const ui = app as unknown as MountedUI+ await waitUntil(() => ui.ready)+ return { app, ui, sent, client }+ }++ async function close(ui: MountedUI) {+ setup!.mockInput.pressEscape()+ await waitUntil(() => !ui.usagePanel.visible)+ }++ async function open(ui: MountedUI) {+ ui.composer.setText("/usage")+ setup!.mockInput.pressEnter()+ await waitUntil(() => ui.usagePanel.visible)+ await setup!.flush()+ }++ test("completes and opens locally, navigates rounds, resizes, and returns to the composer", async () => {+ const { ui, sent } = await mount()+ await setup!.mockInput.typeText("/us")+ setup!.mockInput.pressTab()+ expect(ui.composer.plainText).toBe("/usage")+ setup!.mockInput.pressEnter()+ await waitUntil(() => ui.usagePanel.visible)+ await setup!.flush()+ let frame = setup!.captureCharFrame()+ expect(frame).toContain("Context 9k / 262k")+ expect(frame).toContain("Round 2/2 · In 9,000 · Out 200")+ expect(frame).toContain("←→ round")+ expect(sent).toEqual([])+ setup!.mockInput.pressArrow("left")+ await setup!.renderOnce()+ expect(setup!.captureCharFrame()).toContain("Round 1/2 · In 3,000 · Out 100")+ expect(setup!.captureCharFrame()).toContain("Cache 0%")+ for (const [width, height] of [[56, 18], [40, 10], [80, 30]] as const) {+ setup!.resize(width, height)+ await setup!.renderOnce()+ frame = setup!.captureCharFrame()+ expect(frame).toContain("Context 9k / 262k")+ expect(frame).toContain("Ask nanobot anything")+ }+ await close(ui)+ await setup!.renderOnce()+ expect(ui.usagePanel.visible).toBe(false)+ await setup!.mockInput.typeText("next prompt")+ expect(ui.composer.plainText).toBe("next prompt")+ expect(sent).toEqual([])+ })++ test("does not queue a local usage command after dismissing completion during a turn", async () => {+ const { app, ui, sent } = await mount()+ app.accept({ event: "message_accepted", chat_id: "chat", turn_id: "active", starts_turn: true })+ await setup!.mockInput.typeText("/usage")+ setup!.mockInput.pressEscape()+ await waitUntil(() => !ui.commandMenu.visible)+ setup!.mockInput.pressTab()+ expect(ui.composer.plainText).toBe("/usage")+ expect(ui.usagePanel.visible).toBe(false)+ app.accept({ event: "turn_end", chat_id: "chat", turn_id: "active" })+ expect(sent).toEqual([])+ setup!.mockInput.pressEnter()+ await waitUntil(() => ui.usagePanel.visible)+ await setup!.flush()+ expect(setup!.captureCharFrame()).toContain("Context 9k / 262k")+ expect(sent).toEqual([])+ })++ test("refreshes on turn completion without adding duplicate rounds", async () => {+ let input = 9000+ let requests = 0+ const { app, ui, sent } = await mount(async () => { requests++; return Response.json(page(input)) })+ await open(ui)+ input = 12000+ app.accept({ event: "turn_end", chat_id: "chat", turn_id: "turn" })+ await waitUntil(() => requests === 2)+ await setup!.flush()+ const frame = setup!.captureCharFrame()+ expect(frame).toContain("Round 2/2 · In 12,000 · Out 200")+ expect(frame).not.toContain("Round 4/4")+ expect(sent).toEqual([])+ })++ 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)))+ await open(ui)+ expect(setup!.captureCharFrame()).toContain("Loading usage")+ await close(ui)+ await open(ui)+ pending[1]!(Response.json(page(12000)))+ await setup!.flush()+ pending[0]!(Response.json(page(9000)))+ await setup!.flush()+ expect(setup!.captureCharFrame()).toContain("In 12,000")+ await close(ui)+ expect(ui.usagePanel.visible).toBe(false)+ })++ test("does not resurrect the previous session's panel after attach", async () => {+ let finish: ((response: Response) => void) | undefined+ let requests = 0+ const { app, ui, client } = await mount(() => {+ requests+++ if (requests === 1) return new Promise((resolve) => { finish = resolve })+ return Promise.resolve(Response.json({ messages: [] }))+ })+ await open(ui)+ client.attach("other-chat")+ app.accept({ event: "attached", chat_id: "other-chat" })+ finish!(Response.json(page()))+ await setup!.flush()+ expect(ui.usagePanel.visible).toBe(false)+ expect(setup!.captureCharFrame()).not.toContain("Context 9k")+ await open(ui)+ expect(setup!.captureCharFrame()).toContain("No model-call usage available yet")+ })++ test("keeps empty sessions and failed requests usable without sending the command", async () => {+ let fail = false+ const { ui, sent } = await mount(async () => {+ if (fail) throw new Error("offline")+ return new Response(null, { status: 404 })+ })+ await open(ui)+ expect(setup!.captureCharFrame()).toContain("No model-call usage available yet")+ await close(ui)+ fail = true+ await open(ui)+ expect(setup!.captureCharFrame()).toContain("Usage unavailable · reopen /usage to retry")+ await setup!.mockInput.typeText("hello")+ expect(ui.usagePanel.visible).toBe(false)+ expect(ui.composer.plainText).toBe("hello")+ expect(sent).toEqual([])+ })+})diff --git a/tui/src/usage-panel.test.ts b/tui/src/usage-panel.test.tsnew file mode 100644index 000000000..567bf99c3--- /dev/null+++ b/tui/src/usage-panel.test.ts@@ -0,0 +1,203 @@+import { afterEach, describe, expect, test } from "bun:test"+import { RGBA } from "@opentui/core"+import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"++import { UsagePanel, type UsagePanelTheme } from "./usage-panel"+import type { SessionUsageSnapshot } from "./protocol"++const theme: UsagePanelTheme = {+ text: "#ECEDEE", muted: "#A1A1AA", border: "#3F3F46", accent: "#EF8E30",+ cached: "#1795A2", warning: "#F5C451", error: "#F87171",+}+const snapshot: SessionUsageSnapshot = {+ context: { tokens: 9_000, windowTokens: 262_144 },+ rounds: [+ { prompt_tokens: 3_000, completion_tokens: 200 },+ { prompt_tokens: 6_000, completion_tokens: 400, cached_tokens: 0 },+ { prompt_tokens: 9_000, completion_tokens: 800, cached_tokens: 6_000, generation_ms: 1500, estimated_tokens: 20 },+ ],+}++describe("UsagePanel", () => {+ let setup: TestRendererSetup | undefined+ afterEach(() => {+ if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()+ setup = undefined+ })++ test("renders context occupancy and selects logical-round details without inventing cache data", async () => {+ setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })+ const panel = new UsagePanel(setup.renderer, theme)+ setup.renderer.root.add(panel.root)+ panel.resize(80, 30)+ panel.show(snapshot)+ await setup.renderOnce()+ const frame = setup.captureCharFrame()+ expect(frame).toContain("Context 9k / 262k")+ expect(frame).toContain("3%")+ expect(frame).toContain("Input tokens · max 9k")+ expect(frame).toContain("Round 3/3 · In 9,000 · Out 800")+ expect(frame).toContain("Cache 67% · 1.5s · includes estimated usage")+ expect(frame).toContain("Uncached")+ expect(frame).toContain("Unknown cache")+ expect(frame).toContain("███")+ const rows = frame.split("\n")+ const detailsIndex = rows.findIndex((row) => row.includes("Round 3/3"))+ expect(rows[detailsIndex - 1]).toContain("███")+ panel.move(-1)+ await setup.renderOnce()+ expect(setup.captureCharFrame()).toContain("Cache 0%")+ panel.move(-1)+ panel.move(-1)+ await setup.renderOnce()+ expect(setup.captureCharFrame()).toContain("Round 1/3 · In 3,000 · Out 200")+ expect(setup.captureCharFrame()).toContain("Cache ?")+ })++ test("splits cached foreground and uncached background at eighth-row precision without color bleed", async () => {+ setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })+ const panel = new UsagePanel(setup.renderer, theme)+ setup.renderer.root.add(panel.root)+ panel.show({ context: null, rounds: [{ prompt_tokens: 1000, cached_tokens: 800 }] })+ const barSpans = () => setup!.captureSpans().lines.flatMap((line) =>+ line.spans.filter((span) => /[▁▂▃▄▅▆▇█]/u.test(span.text)))++ for (const palette of [theme, { ...theme, accent: "#B94D0B", cached: "#0F766E" }]) {+ panel.setTheme(palette)+ for (const [height, glyphs] of [[30, ["███", "▆▆▆", "███", "███", "███", "███"]], [18, ["▆▆▆"]]] as const) {+ setup.resize(80, height)+ panel.resize(80, height)+ await setup.renderOnce()+ const bars = barSpans()+ expect(bars.map((span) => span.text.trim())).toEqual([...glyphs])+ const cachedColor = RGBA.fromHex(palette.cached)+ const uncachedColor = RGBA.fromHex(palette.accent)+ const split = bars.find((span) => span.text.includes("▆"))!+ expect(split.fg.equals(cachedColor)).toBe(true)+ expect(split.bg.equals(uncachedColor)).toBe(true)+ // Every solid cell below the split is cached; the cell above is uncached.+ expect(bars.filter((span) => span.fg.equals(cachedColor)).length).toBe(height === 30 ? 5 : 1)+ expect(setup.captureSpans().lines.flatMap((line) => line.spans)+ .filter((span) => span.bg.equals(uncachedColor)).map((span) => span.text)).toEqual(["▆▆▆"])+ }+ }+ })++ test("quantizes the cache boundary from raw tokens rather than the rounded total height", async () => {+ setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })+ const panel = new UsagePanel(setup.renderer, theme)+ setup.renderer.root.add(panel.root)+ panel.resize(80, 30)+ panel.show({ context: null, rounds: [+ { prompt_tokens: 480 },+ { prompt_tokens: 254, cached_tokens: 215 },+ ] })+ await setup.renderOnce()+ const bars = setup.captureSpans().lines.flatMap((line) =>+ line.spans.filter((span) => /[▁▂▃▄▅▆▇█]/u.test(span.text)))+ const cached = bars.filter((span) => span.fg.equals(RGBA.fromHex(theme.cached)))+ // Total: round(25.4) = 25 eighths; cache: round(21.5) = 22, not round(25 * 215/254) = 21.+ expect(cached.map((span) => span.text.trim())).toEqual(["▆▆▆", "███", "███"])+ expect(bars.some((span) => span.text.includes("▁") && span.fg.equals(RGBA.fromHex(theme.accent)))).toBe(true)+ })++ test("preserves a partial top's empty space when cached and uncached input share it", async () => {+ setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })+ const panel = new UsagePanel(setup.renderer, theme)+ setup.renderer.root.add(panel.root)+ panel.resize(80, 30)+ for (const [input, cachedTokens, glyph, color] of [+ [300, 240, "▆", theme.cached], [300, 180, "▆", theme.accent],+ [100, 80, "▅", theme.cached], [1, 0, "▁", theme.accent],+ ] as const) {+ panel.show({ context: null, rounds: [+ { prompt_tokens: 1000 }, { prompt_tokens: input, cached_tokens: cachedTokens },+ ] })+ await setup.renderOnce()+ const spans = setup.captureSpans().lines.flatMap((line) => line.spans)+ const top = spans.find((span) => span.text.includes(glyph))!+ expect(top.text.trim()).toBe(glyph.repeat(3))+ expect(top.fg.equals(RGBA.fromHex(color))).toBe(true)+ expect(top.bg.equals(RGBA.fromHex(theme.accent))).toBe(false)+ expect(top.bg.equals(RGBA.fromHex(theme.cached))).toBe(false)+ expect(setup.captureCharFrame()).toContain(`Cache ${Math.round(cachedTokens / input * 100)}%`)+ }+ })++ test("keeps unknown, zero, and fully cached bars unblended", async () => {+ setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })+ const panel = new UsagePanel(setup.renderer, theme)+ setup.renderer.root.add(panel.root)+ panel.resize(80, 30)+ for (const [cachedTokens, color] of [[undefined, theme.muted], [0, theme.accent], [1000, theme.cached], [2000, theme.cached]] as const) {+ panel.show({ context: null, rounds: [{ prompt_tokens: 1000, cached_tokens: cachedTokens }] })+ await setup.renderOnce()+ const bars = setup.captureSpans().lines.flatMap((line) =>+ line.spans.filter((span) => span.text.includes("█")))+ expect(bars.length).toBe(6)+ for (const bar of bars) {+ expect(bar.text.trim()).toBe("███")+ expect(bar.fg.equals(RGBA.fromHex(color))).toBe(true)+ expect(bar.bg.equals(RGBA.fromHex(theme.accent))).toBe(false)+ expect(bar.bg.equals(RGBA.fromHex(theme.cached))).toBe(false)+ }+ }+ })++ test("keeps zero context distinct from unknown capacity and missing usage", async () => {+ setup = await createTestRenderer({ width: 80, height: 26, screenMode: "alternate-screen" })+ const panel = new UsagePanel(setup.renderer, theme)+ setup.renderer.root.add(panel.root)+ panel.show({ context: { tokens: 0, windowTokens: 1000 }, rounds: [] })+ await setup.renderOnce()+ expect(setup.captureCharFrame()).toContain("Context 0 / 1k")+ expect(setup.captureCharFrame()).toContain("0%")+ panel.show({ context: { tokens: 9000 }, rounds: [] })+ await setup.renderOnce()+ expect(setup.captureCharFrame()).toContain("Context 9k / ?")+ expect(setup.captureCharFrame()).not.toContain("0%")+ panel.show({ context: null, rounds: [] })+ await setup.renderOnce()+ expect(setup.captureCharFrame()).toContain("Context unavailable")+ expect(setup.captureCharFrame()).toContain("No model-call usage available yet")+ })++ test("clamps context and cached portions without losing the actual input count", async () => {+ setup = await createTestRenderer({ width: 80, height: 26, screenMode: "alternate-screen" })+ const panel = new UsagePanel(setup.renderer, theme)+ setup.renderer.root.add(panel.root)+ panel.show({+ context: { tokens: 2000, windowTokens: 1000 },+ rounds: [{ prompt_tokens: 2000, cached_tokens: 3000 }],+ })+ await setup.renderOnce()+ const frame = setup.captureCharFrame()+ expect(frame).toContain("Context 2k / 1k")+ expect(frame).toContain("100%")+ expect(frame).toContain("In 2,000 · Out ?")+ expect(frame).toContain("Cache 100%")+ })++ 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)+ setup.renderer.root.add(panel.root)+ panel.show(snapshot)+ for (const [width, height, maxPanelHeight] of [[80, 30, 17], [56, 18, 6], [40, 10, 4]] as const) {+ setup.resize(width, height)+ panel.resize(width, height)+ await setup.renderOnce()+ expect(panel.root.height).toBeLessThanOrEqual(maxPanelHeight)+ expect(setup.captureCharFrame()).toContain("Context 9k / 262k")+ expect(setup.captureCharFrame()).toContain("3%")+ }+ setup.resize(80, 30)+ panel.resize(80, 30)+ panel.setTheme({ ...theme, text: "#18181B", border: "#D4D4D8" })+ await setup.renderOnce()+ expect(setup.captureCharFrame()).toContain("Round 3/3 · In 9,000 · Out 800")+ panel.hide()+ await setup.renderOnce()+ expect(setup.captureCharFrame()).not.toContain("Context")+ })+})diff --git a/tui/src/usage-panel.ts b/tui/src/usage-panel.tsnew file mode 100644index 000000000..a856a8ff2--- /dev/null+++ b/tui/src/usage-panel.ts@@ -0,0 +1,211 @@+import {+ BoxRenderable,+ RGBA,+ StyledText,+ TextAttributes,+ TextRenderable,+ type CliRenderer,+ type TextChunk,+} from "@opentui/core"++import { formatTokenCount } from "./context-panel"+import type { SessionUsageSnapshot } from "./protocol"++export interface UsagePanelTheme {+ text: string+ muted: string+ border: string+ accent: string+ cached: string+ warning: string+ error: string+}++function known(value: number | undefined): value is number {+ return typeof value === "number" && Number.isFinite(value) && value >= 0+}++function chunk(text: string, color: string, bold = false): TextChunk {+ return {+ __isChunk: true,+ text,+ fg: RGBA.fromHex(color),+ attributes: bold ? TextAttributes.BOLD : 0,+ }+}++/** A bounded, read-only view of persisted model-call usage. */+export class UsagePanel {+ readonly root: BoxRenderable+ private readonly body: TextRenderable+ private snapshot: SessionUsageSnapshot = { context: null, rounds: [] }+ private selected = 0+ private message = ""+ private width = 68+ private height = 24++ constructor(renderer: CliRenderer, private theme: UsagePanelTheme) {+ this.root = new BoxRenderable(renderer, {+ id: "nanobot-tui-usage-panel",+ width: "100%",+ maxWidth: 72,+ flexShrink: 0,+ flexDirection: "column",+ border: true,+ borderStyle: "rounded",+ borderColor: theme.border,+ paddingLeft: 1,+ paddingRight: 1,+ visible: false,+ })+ this.body = new TextRenderable(renderer, {+ id: "nanobot-tui-usage-body",+ width: "100%",+ content: "",+ wrapMode: "none",+ })+ this.root.add(this.body)+ }++ get visible(): boolean {+ return this.root.visible+ }++ showMessage(message: string): void {+ this.message = message+ this.root.visible = true+ this.render()+ }++ show(snapshot: SessionUsageSnapshot): void {+ this.snapshot = snapshot+ this.selected = Math.max(0, snapshot.rounds.length - 1)+ this.message = ""+ this.root.visible = true+ this.render()+ }++ hide(): void {+ this.root.visible = false+ }++ move(direction: -1 | 1): void {+ this.selected = Math.max(0, Math.min(this.snapshot.rounds.length - 1, this.selected + direction))+ this.render()+ }++ resize(terminalWidth: number, terminalHeight: number): void {+ // The shell has one column of padding on each side; the panel adds four.+ this.width = Math.max(1, Math.min(72, terminalWidth - 2) - 4)+ this.height = terminalHeight+ this.render()+ }++ setTheme(theme: UsagePanelTheme): void {+ this.theme = theme+ this.root.borderColor = theme.border+ this.render()+ }++ private render(): void {+ const { theme, width } = this+ const compact = this.height < 20+ const tiny = this.height < 14+ const chunks: TextChunk[] = []+ const line = (text: string, color = theme.text, bold = false) => {+ chunks.push(chunk(`${text}\n`, color, bold))+ }+ const heading = (left: string, right: string) => {+ line(`${left}${" ".repeat(Math.max(1, width - left.length - right.length))}${right}`)+ }+ if (this.message) {+ line("Usage", theme.accent, true)+ line(this.message, theme.muted)+ } else {+ const context = this.snapshot.context+ if (context && known(context.tokens)) {+ const window = context.windowTokens+ const percent = known(window) && window > 0+ ? Math.min(100, Math.round(context.tokens / window * 100)) : null+ heading(+ `Context ${formatTokenCount(context.tokens)} / ${known(window) && window > 0 ? formatTokenCount(window) : "?"}`,+ percent === null ? "" : `${percent}%`,+ )+ if (percent !== null && !compact) {+ const filled = Math.round(percent / 100 * width)+ const color = percent >= 90 ? theme.error : percent >= 75 ? theme.warning : theme.muted+ chunks.push(chunk("━".repeat(filled), color), chunk(`${"─".repeat(width - filled)}\n`, theme.border))+ }+ } else {+ line("Context unavailable", theme.muted)+ }+ const rounds = this.snapshot.rounds+ if (!rounds.length) {+ line("No model-call usage available yet", theme.muted)+ } else {+ if (!compact) line("")+ const inputs = rounds.map((round) => round.prompt_tokens ?? 0)+ const max = Math.max(1, ...inputs)+ if (!tiny) heading(width < 48 ? "Rounds" : "Recent rounds", `Input tokens · max ${formatTokenCount(max)}`)+ const chartHeight = Math.max(1, Math.min(6, this.height - 18))+ const slot = Math.max(1, Math.floor(width / rounds.length))+ const barWidth = Math.min(3, Math.max(1, slot - 1))+ const blocks = " ▁▂▃▄▅▆▇█"+ const bars = rounds.map((round, index) => {+ const input = inputs[index] ?? 0+ const units = Math.max(1, Math.round(input / max * chartHeight * 8))+ // Quantize both boundaries from token counts, not the rounded bar height.+ const cachedUnits = known(round.cached_tokens)+ ? Math.min(units, Math.round(Math.min(input, round.cached_tokens) / max * chartHeight * 8))+ : null+ return { units, cachedUnits }+ })+ for (let row = chartHeight - 1; row >= 0; row -= 1) {+ bars.forEach(({ units, cachedUnits }) => {+ const fill = Math.max(0, Math.min(8, units - row * 8))+ const cachedFill = cachedUnits === null ? null+ : Math.max(0, Math.min(fill, cachedUnits - row * 8))+ if (fill === 8 && cachedFill !== null && cachedFill > 0 && cachedFill < 8) {+ const cell = chunk((blocks[cachedFill] ?? " ").repeat(barWidth), theme.cached)+ cell.bg = RGBA.fromHex(theme.accent)+ chunks.push(cell)+ } else {+ // A partial top can contain three regions, but a cell has only two+ // colors. Preserve the empty space and use the larger filled segment.+ const color = cachedFill === null ? theme.muted+ : cachedFill > 0 && cachedFill * 2 >= fill ? theme.cached : theme.accent+ chunks.push(chunk((blocks[fill] ?? " ").repeat(barWidth), color))+ }+ chunks.push(chunk(" ".repeat(slot - barWidth), theme.muted))+ })+ line("")+ }+ const round = rounds[this.selected]+ if (round && !tiny) {+ const input = round.prompt_tokens ?? 0+ const count = (value: number | undefined) => known(value) ? value.toLocaleString("en-US") : "?"+ line(`${width < 48 ? "" : "Round "}${this.selected + 1}/${rounds.length} · In ${count(input)} · Out ${count(round.completion_tokens)}`)+ const cache = known(round.cached_tokens)+ ? `${Math.round(Math.min(input, round.cached_tokens) / input * 100)}%` : "?"+ const time = known(round.generation_ms) ? ` · ${(round.generation_ms / 1000).toFixed(1)}s` : ""+ if (!compact) {+ const estimated = known(round.estimated_tokens) && round.estimated_tokens > 0+ line(`Cache ${cache}${time}${estimated && width >= 48 ? " · includes estimated usage" : ""}`, theme.muted)+ if (estimated && width < 48) line("Includes estimated usage", theme.muted)+ }+ }+ if (!compact) {+ chunks.push(+ chunk("■ ", theme.accent), chunk("Uncached ", theme.muted),+ chunk("■ ", theme.cached), chunk("Cached ", theme.muted),+ chunk(width < 48 ? "■ Unknown\n" : "■ Unknown cache\n", theme.muted),+ )+ }+ }+ }+ // Keep the final newline from reserving an empty row in the retained layout.+ const last = chunks.at(-1)+ if (last) last.text = last.text.replace(/\n$/u, "")+ this.body.content = new StyledText(chunks)+ }+}diff --git a/tui/src/usage-protocol.test.ts b/tui/src/usage-protocol.test.tsnew file mode 100644index 000000000..dae8bfae5--- /dev/null+++ b/tui/src/usage-protocol.test.ts@@ -0,0 +1,209 @@+import { afterEach, describe, expect, mock, test } from "bun:test"++import { fetchSessionUsage } from "./protocol"++const apiUrl = "http://nanobot.test"+const apiToken = "usage-token"+const chatId = "usage/chat"+const threadPath = "/api/sessions/websocket%3Ausage%2Fchat/webui-thread?limit=120&direction=latest"+const originalFetch = globalThis.fetch++afterEach(() => { globalThis.fetch = originalFetch })++function mockResponses(...responses: Response[]) {+ const fetchMock = mock(async (_input: string | URL | Request, _init?: RequestInit) => {+ const response = responses.shift()+ if (!response) throw new Error("unexpected fetch")+ return response+ })+ globalThis.fetch = Object.assign(fetchMock, { preconnect: originalFetch.preconnect })+ return fetchMock+}++function thread(messages: Array<Record<string, unknown>>) {+ return Response.json({ messages })+}++function assistant(turnId: string, fields: Record<string, unknown>) {+ return { role: "assistant", content: "answer", turnId, ...fields }+}++describe("fetchSessionUsage", () => {+ test("returns the latest eight logical rounds chronologically across deduplicated turns", async () => {+ const rounds = Array.from({ length: 11 }, (_, index) => ({+ prompt_tokens: (index + 1) * 100,+ completion_tokens: index + 1,+ }))+ const fetchMock = mockResponses(thread([+ assistant("first", { id: "first-a", roundUsages: rounds.slice(0, 4) }),+ assistant("first", { id: "first-b", roundUsages: rounds.slice(0, 4) }),+ assistant("second", { id: "second-a", roundUsages: rounds.slice(4, 8) }),+ assistant("second", { id: "second-b", roundUsages: rounds.slice(4, 8) }),+ assistant("third", { roundUsages: rounds.slice(8) }),+ ]))++ expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({+ context: null,+ rounds: rounds.slice(-8),+ })+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(fetchMock.mock.calls[0]?.[0]).toBe(`${apiUrl}${threadPath}`)+ expect(new Headers(fetchMock.mock.calls[0]?.[1]?.headers).get("Authorization"))+ .toBe(`Bearer ${apiToken}`)+ })++ test("never substitutes aggregate prompt usage for missing or invalid round samples", async () => {+ mockResponses(thread([+ assistant("aggregate-only", { usage: { prompt_tokens: 90_000, total_tokens: 91_000 } }),+ assistant("invalid-rounds", {+ usage: { prompt_tokens: 80_000, context_tokens: 12 },+ contextWindowTokens: 1_000,+ roundUsages: [null, {}, { completion_tokens: 2 }, { prompt_tokens: 0 },+ { prompt_tokens: -1 }, { prompt_tokens: "500" }],+ }),+ ]))++ expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({+ context: { tokens: 12, windowTokens: 1_000 },+ rounds: [],+ })+ })++ test("takes context and capacity from the latest message with context usage, not its neighbors", async () => {+ const round = { prompt_tokens: 70, context_tokens: 999 }+ mockResponses(thread([+ assistant("old", { usage: { context_tokens: 100 }, contextWindowTokens: 1_000 }),+ assistant("context", {+ usage: { prompt_tokens: 50_000, context_tokens: 250 },+ contextWindowTokens: 4_000,+ }),+ assistant("newer", {+ usage: { prompt_tokens: 90_000, total_tokens: 91_000 },+ contextWindowTokens: 100_000,+ roundUsages: [round],+ }),+ ]))++ expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({+ context: { tokens: 250, windowTokens: 4_000 },+ rounds: [round],+ })+ })++ test("keeps usage-only and empty assistants while ignoring streaming, trace and non-assistant rows", async () => {+ const rounds = [{ prompt_tokens: 80 }, { prompt_tokens: 160, cached_tokens: 40 }]+ const noise = { usage: { context_tokens: 999 }, roundUsages: [{ prompt_tokens: 999 }] }+ mockResponses(thread([+ assistant("usage-only", { content: undefined, usage: { context_tokens: 80 }, roundUsages: [rounds[0]] }),+ assistant("empty", {+ content: "", usage: { context_tokens: 160 }, contextWindowTokens: 2_000,+ roundUsages: [rounds[1]],+ }),+ assistant("empty", { isStreaming: true, ...noise }),+ assistant("empty", { kind: "trace", ...noise }),+ { role: "tool", kind: "trace", ...noise },+ { role: "user", content: "question", ...noise },+ ]))++ expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({+ context: { tokens: 160, windowTokens: 2_000 },+ rounds,+ })+ })++ test("successful compaction clears context but not bars, and later completed usage restores it", async () => {+ const oldRound = { prompt_tokens: 800 }+ const newRound = { prompt_tokens: 120 }+ const old = assistant("old", {+ usage: { context_tokens: 800 }, contextWindowTokens: 1_000, roundUsages: [oldRound],+ })+ const compaction = (phase: string) => ({+ role: "activity", kind: "compaction", compaction: { id: "compact-1", phase },+ })+ mockResponses(+ thread([old, compaction("started")]),+ thread([old, compaction("failed")]),+ thread([old, compaction("succeeded")]),+ thread([old, compaction("succeeded"), assistant("new", {+ usage: { context_tokens: 120 }, contextWindowTokens: 2_000, roundUsages: [newRound],+ })]),+ )++ for (const _phase of ["started", "failed"]) {+ expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({+ context: { tokens: 800, windowTokens: 1_000 }, rounds: [oldRound],+ })+ }+ expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({+ context: null, rounds: [oldRound],+ })+ expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({+ context: { tokens: 120, windowTokens: 2_000 }, rounds: [oldRound, newRound],+ })+ })++ test("keeps zero context and missing versus zero cache without borrowing an invalid or missing capacity", async () => {+ const rounds = [+ { prompt_tokens: 40 },+ { prompt_tokens: 80, cached_tokens: 0, cache_write_tokens: 0 },+ ]+ for (const capacity of [undefined, 0, -1, "64000", null]) {+ mockResponses(thread([+ assistant("old", { usage: { context_tokens: 88 }, contextWindowTokens: 64_000 }),+ assistant("latest", {+ usage: { context_tokens: 0 }, contextWindowTokens: capacity, roundUsages: rounds,+ }),+ ]))++ expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({+ context: { tokens: 0 }, rounds,+ })+ }+ })++ test("returns an empty snapshot on 404 or missing credentials without reauthentication", async () => {+ const fetchMock = mockResponses(new Response("missing", { status: 404 }))+ const reauthenticate = mock(async () => ({ apiUrl, apiToken: "fresh" }))+ const empty = { context: null, rounds: [] }++ expect(await fetchSessionUsage(apiUrl, apiToken, chatId, reauthenticate)).toStrictEqual(empty)+ expect(await fetchSessionUsage("", apiToken, chatId, reauthenticate)).toStrictEqual(empty)+ expect(await fetchSessionUsage(apiUrl, "", chatId, reauthenticate)).toStrictEqual(empty)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(reauthenticate).not.toHaveBeenCalled()+ })++ test("retries 401 once with the refreshed endpoint and token, retaining the thread request", async () => {+ const fresh = { apiUrl: "http://refreshed.test", apiToken: "fresh-token" }+ const fetchMock = mockResponses(+ new Response("expired", { status: 401 }),+ thread([assistant("fresh", { usage: { context_tokens: 42 } })]),+ )+ const reauthenticate = mock(async (_rejectedToken: string) => fresh)++ expect(await fetchSessionUsage(apiUrl, apiToken, chatId, reauthenticate)).toStrictEqual({+ context: { tokens: 42 }, rounds: [],+ })+ expect(reauthenticate).toHaveBeenCalledTimes(1)+ expect(reauthenticate).toHaveBeenCalledWith(apiToken)+ expect(fetchMock.mock.calls.map(([url, init]) => ({+ url: String(url), authorization: new Headers(init?.headers).get("Authorization"),+ }))).toEqual([+ { url: `${apiUrl}${threadPath}`, authorization: `Bearer ${apiToken}` },+ { url: `${fresh.apiUrl}${threadPath}`, authorization: `Bearer ${fresh.apiToken}` },+ ])+ })++ test("rejects 401 without reauthentication and stops after one rejected refresh", async () => {+ const fetchMock = mockResponses(...Array.from({ length: 3 }, () =>+ new Response("unauthorized", { status: 401 })))+ const reauthenticate = mock(async () => ({ apiUrl, apiToken: "still-rejected" }))++ await expect(fetchSessionUsage(apiUrl, apiToken, chatId)).rejects.toThrow("HTTP 401")+ await expect(fetchSessionUsage(apiUrl, apiToken, chatId, reauthenticate))+ .rejects.toThrow("HTTP 401")+ expect(fetchMock).toHaveBeenCalledTimes(3)+ expect(reauthenticate).toHaveBeenCalledTimes(1)+ expect(reauthenticate).toHaveBeenCalledWith(apiToken)+ })+})