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
fix(tui): show context window usage in footer (#5679)
chengyongru5eb9039f0e58
diff --git a/tui/src/app.test.ts b/tui/src/app.test.tsindex d730daebf..b642500b4 100644--- a/tui/src/app.test.ts+++ b/tui/src/app.test.ts@@ -2310,7 +2310,7 @@ describe("NanobotTui layout", () => {expect(assistantMarker?.renderable.fg.toInts().slice(0, 3)).toEqual([161, 161, 170])})- test("uses the idle footer for model telemetry instead of permanent shortcuts", async () => {+ test("shows context usage in the idle footer", async () => {setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })const app = mount(setup)app.accept({ event: "attached", chat_id: "chat" })@@ -2319,13 +2319,7 @@ describe("NanobotTui layout", () => {chat_id: "chat",latency_ms: 1700,usage: {- prompt_tokens: 1200,- completion_tokens: 80,- cached_tokens: 900,- generation_ms: 1600,- measured_completion_tokens: 80,- ttft_ms: 240,- timed_requests: 1,+ context_tokens: 14_700,},context_window_tokens: 128_000,})@@ -2333,18 +2327,7 @@ describe("NanobotTui layout", () => {const footer = setup.captureCharFrame().split("\n").find((line) => line.includes("Ready · 1.7s")) || ""expect(footer).toContain("Ready · 1.7s")- expect(footer).toContain("50 tok/s")- expect(footer).toContain("1.2K in (75% cached) · 80 out")- expect(footer).not.toContain("TTFT")- expect(footer).not.toContain("enter send")-- app.accept({ event: "reasoning_delta", chat_id: "chat", text: "hidden" })- await Bun.sleep(130)- await setup.renderOnce()- const activeFooter = setup.captureCharFrame().split("\n").find((line) => line.includes("Thinking")) || ""- expect(activeFooter).not.toContain("ctrl+c stop")- expect(activeFooter).not.toContain("enter steer")- app.accept({ event: "turn_end", chat_id: "chat" })+ expect(footer).toContain("11% context")})test("keeps an explicit theme stable when the terminal reports another mode", async () => {diff --git a/tui/src/app.ts b/tui/src/app.tsindex bb7fc2c5f..318059ab0 100644--- a/tui/src/app.ts+++ b/tui/src/app.ts@@ -1914,8 +1914,8 @@ export class NanobotTui {: "ready"if (mode === "ready") {this.meta.content = footerTelemetry(- this.lastUsage,- this.renderer.width,+ this.lastUsage?.context_tokens ?? null,+ this.contextWindowTokens,footerHintTheme(this.palette),)returndiff --git a/tui/src/footer-hints.test.ts b/tui/src/footer-hints.test.tsindex 6338e71a0..033f7a704 100644--- a/tui/src/footer-hints.test.ts+++ b/tui/src/footer-hints.test.ts@@ -29,44 +29,28 @@ describe("footerHints", () => {expect(active.chunks).toHaveLength(0)})- test("groups the cache ratio with input telemetry", () => {- const result = footerTelemetry({- prompt_tokens: 1200,- completion_tokens: 80,- cached_tokens: 900,- generation_ms: 1600,- measured_completion_tokens: 80,- ttft_ms: 500,- timed_requests: 2,- }, 120, theme)+ test("shows the measured request's context-window percentage", () => {+ const result = footerTelemetry(14_700, 128_000, theme)expect(result.chunks.map(({ text }) => text).join(""))- .toBe("50 tok/s · 1.2K in (75% cached) · 80 out")+ .toBe("11% context")expect(result.chunks[0]?.fg?.toInts().slice(0, 3)).toEqual([239, 142, 48])})- test("uses familiar compact units for large token counts", () => {- const result = footerTelemetry({- prompt_tokens: 4_500_000,- completion_tokens: 19_000,- cached_tokens: 3_600_000,- generation_ms: 135_714,- measured_completion_tokens: 19_000,- }, 120, theme)+ test("clamps usage above the configured window", () => {+ const result = footerTelemetry(220_000, 200_000, theme)expect(result.chunks.map(({ text }) => text).join(""))- .toBe("140 tok/s · 4.5M in (80% cached) · 19K out")+ .toBe("100% context")})- test("degrades telemetry instead of guessing missing provider metrics", () => {- const compact = footerTelemetry({- prompt_tokens: 1000,- completion_tokens: 20,- cached_tokens: 0,- }, 60, theme)- const unsupported = footerTelemetry({ prompt_tokens: 1000, completion_tokens: 20 }, 60, theme)+ test("does not guess without measured context or a valid window", () => {+ const missingContext = footerTelemetry(null, 128_000, theme)+ const missingWindow = footerTelemetry(1000, null, theme)+ const invalidWindow = footerTelemetry(1000, 0, theme)- expect(compact.chunks.map(({ text }) => text).join("")).toBe("0% cached")- expect(unsupported.chunks).toHaveLength(0)+ expect(missingContext.chunks).toHaveLength(0)+ expect(missingWindow.chunks).toHaveLength(0)+ expect(invalidWindow.chunks).toHaveLength(0)})})diff --git a/tui/src/footer-hints.ts b/tui/src/footer-hints.tsindex e73aad1c3..67baf706b 100644--- a/tui/src/footer-hints.ts+++ b/tui/src/footer-hints.ts@@ -1,7 +1,5 @@import { RGBA, StyledText, TextAttributes, type TextChunk } from "@opentui/core"-import type { TokenUsage } from "./protocol"-export interface FooterHint {key: stringlabel: string@@ -37,66 +35,24 @@ export function contextualFooterHints(return footerHints(hintsFor(mode, width), theme)}-/** Last-turn model telemetry. Passive chrome reports the system, not its manual. */+/** Latest measured request's context-window occupancy. */export function footerTelemetry(- usage: TokenUsage | null,- width: number,+ contextTokens: number | null,+ contextWindowTokens: number | null,theme: FooterHintTheme,): StyledText {- if (!usage) return new StyledText([])- const parts: string[] = []- const duration = usage.generation_ms- const measured = usage.measured_completion_tokens- if (typeof duration === "number" && duration > 0 && typeof measured === "number") {- const rate = measured * 1000 / duration- const value = rate < 10 ? rate.toFixed(1) : String(Math.round(rate))- const estimated = (usage.estimated_tokens || 0) > 0 ? "~" : ""- parts.push(`${estimated}${value} tok/s`)- }- const cacheHitRate = (- typeof usage.cached_tokens === "number"- && typeof usage.prompt_tokens === "number"- && usage.prompt_tokens > 0- )- ? Math.min(100, Math.max(0, Math.round(- usage.cached_tokens * 100 / usage.prompt_tokens,- )))- : null- if (width >= 72) {- const prompt = usage.prompt_tokens- const completion = usage.completion_tokens- if (typeof prompt === "number" || typeof completion === "number") {- const cache = cacheHitRate === null ? "" : ` (${cacheHitRate}% cached)`- parts.push(`${formatTelemetryTokens(prompt || 0)} in${cache}`)- parts.push(`${formatTelemetryTokens(completion || 0)} out`)- }- } else if (cacheHitRate !== null) {- parts.push(`${cacheHitRate}% cached`)- }- if (width >= 128 && typeof usage.cost_usd === "number" && usage.cost_usd > 0) {- parts.push(`$${usage.cost_usd < 0.01 ? usage.cost_usd.toFixed(4) : usage.cost_usd.toFixed(2)}`)- }- return footerMetrics(parts, theme)-}--function formatTelemetryTokens(value: number): string {- const count = Math.max(0, value)- for (const [threshold, suffix] of [[1_000_000_000, "B"], [1_000_000, "M"], [1_000, "K"]] as const) {- if (count < threshold) continue- const scaled = count / threshold- const compact = scaled >= 10 ? Math.round(scaled) : Math.round(scaled * 10) / 10- return `${compact}${suffix}`- }- return String(Math.round(count))-}--function footerMetrics(parts: readonly string[], theme: FooterHintTheme): StyledText {- const chunks: TextChunk[] = []- parts.forEach((text, index) => {- if (index) chunks.push(chunk(" · ", theme.separator))- chunks.push(chunk(text, index === 0 ? theme.accent : theme.muted, index === 0))- })- return new StyledText(chunks)+ if (+ typeof contextTokens !== "number"+ || !Number.isFinite(contextTokens)+ || contextTokens < 0+ || typeof contextWindowTokens !== "number"+ || !Number.isFinite(contextWindowTokens)+ || contextWindowTokens <= 0+ ) return new StyledText([])+ const percentage = Math.min(100, Math.round(+ contextTokens * 100 / contextWindowTokens,+ ))+ return new StyledText([chunk(`${percentage}% context`, theme.accent, true)])}/** Give shortcuts visual hierarchy without turning the footer into a toolbar. */