Skip to content

Commit 7cb34ff

Browse files
committed
feat(tui): add persistent token usage display in session footer
Add cumulative input/output token counts and live tokens-per-second to the TUI session footer. Displays alongside existing LSP/MCP status items. Format: '142 tok/s · 4.5M in · 19K out · • 2 LSP · ⊙ 1 MCP' - tok/s shown during streaming (bright) and 3s after (muted) - Cumulative in/out tokens with compact K/M suffixes - Token stats computed from AssistantMessage.tokens in the sync store - TPS calculated via createEffect (no side effects in memos) - Formatting utilities in util/tokens.ts with 8 tests covering edge cases (K/M rollover, TPS threshold at 10) Closes anomalyco#17449 Relates to anomalyco#6096, anomalyco#10354, anomalyco#13003
1 parent 4167e25 commit 7cb34ff

3 files changed

Lines changed: 195 additions & 2 deletions

File tree

‎packages/opencode/src/cli/cmd/tui/routes/session/footer.tsx‎

Lines changed: 100 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
import { createMemo, Match, onCleanup, onMount, Show, Switch } from "solid-js"
1+
import { createEffect, createMemo, Match, on, onCleanup, onMount, Show, Switch } from "solid-js"
22
import { useTheme } from "../../context/theme"
33
import { useSync } from "../../context/sync"
44
import { useDirectory } from "../../context/directory"
55
import { useConnected } from "../../component/dialog-model"
66
import { createStore } from "solid-js/store"
77
import { useRoute } from "../../context/route"
8+
import type { AssistantMessage } from "@opencode-ai/sdk/v2"
9+
import { formatTokenCount, formatTps } from "../../util/tokens"
810

911
export function Footer() {
1012
const { theme } = useTheme()
@@ -20,12 +22,95 @@ export function Footer() {
2022
const directory = useDirectory()
2123
const connected = useConnected()
2224

25+
// Compute cumulative token stats for the current session
26+
const tokenStats = createMemo(() => {
27+
if (route.data.type !== "session") return null
28+
const messages = sync.data.message[route.data.sessionID] ?? []
29+
let inputTokens = 0
30+
let outputTokens = 0
31+
for (const msg of messages) {
32+
if (msg.role !== "assistant") continue
33+
const am = msg as AssistantMessage
34+
if (!am.tokens) continue
35+
inputTokens += am.tokens.input ?? 0
36+
outputTokens += am.tokens.output ?? 0
37+
}
38+
if (inputTokens === 0 && outputTokens === 0) return null
39+
return { inputTokens, outputTokens }
40+
})
41+
42+
// Track streaming tokens-per-second
43+
const [tpsStore, setTpsStore] = createStore({
44+
/** Current or last-computed TPS rate */
45+
tps: 0,
46+
/** Whether to show TPS in the footer (true during streaming + 3s after) */
47+
showTps: false,
48+
})
49+
50+
// Internal tracking for TPS calculation (not reactive)
51+
let prevOutputTokens = 0
52+
let prevTimestamp = 0
53+
let tpsTimeout: ReturnType<typeof setTimeout> | undefined
54+
55+
const sessionStatus = createMemo(() => {
56+
if (route.data.type !== "session") return undefined
57+
return sync.data.session_status[route.data.sessionID]
58+
})
59+
60+
const isStreaming = createMemo(() => sessionStatus()?.type === "busy")
61+
62+
// Find the last assistant message's output token count (reactive)
63+
const lastAssistantOutputTokens = createMemo(() => {
64+
if (route.data.type !== "session") return 0
65+
const messages = sync.data.message[route.data.sessionID] ?? []
66+
for (let i = messages.length - 1; i >= 0; i--) {
67+
const msg = messages[i]
68+
if (msg.role === "assistant") {
69+
return (msg as AssistantMessage).tokens?.output ?? 0
70+
}
71+
}
72+
return 0
73+
})
74+
75+
// Update TPS when output tokens change during streaming (effect, not memo)
76+
createEffect(
77+
on([isStreaming, lastAssistantOutputTokens], ([streaming, outputTokens]) => {
78+
if (!streaming || outputTokens === 0) return
79+
80+
const now = Date.now()
81+
if (prevOutputTokens > 0 && prevTimestamp > 0 && outputTokens > prevOutputTokens) {
82+
const elapsed = (now - prevTimestamp) / 1000
83+
if (elapsed > 0) {
84+
setTpsStore("tps", (outputTokens - prevOutputTokens) / elapsed)
85+
setTpsStore("showTps", true)
86+
}
87+
}
88+
prevOutputTokens = outputTokens
89+
prevTimestamp = now
90+
}),
91+
)
92+
93+
// When streaming stops, keep TPS visible for 3 seconds then hide
94+
createEffect(
95+
on(isStreaming, (streaming) => {
96+
if (!streaming && tpsStore.showTps) {
97+
clearTimeout(tpsTimeout)
98+
tpsTimeout = setTimeout(() => {
99+
setTpsStore("showTps", false)
100+
prevOutputTokens = 0
101+
prevTimestamp = 0
102+
}, 3000)
103+
}
104+
}),
105+
)
106+
107+
onCleanup(() => clearTimeout(tpsTimeout))
108+
23109
const [store, setStore] = createStore({
24110
welcome: false,
25111
})
26112

27113
onMount(() => {
28-
// Track all timeouts to ensure proper cleanup
29114
const timeouts: ReturnType<typeof setTimeout>[] = []
30115

31116
function tick() {
@@ -60,6 +145,19 @@ export function Footer() {
60145
</text>
61146
</Match>
62147
<Match when={connected()}>
148+
<Show when={tokenStats()}>
149+
{(stats) => (
150+
<text fg={theme.textMuted}>
151+
<Show when={tpsStore.showTps && tpsStore.tps > 0}>
152+
<span style={{ fg: isStreaming() ? theme.text : theme.textMuted }}>
153+
{formatTps(tpsStore.tps)} tok/s
154+
</span>
155+
{" · "}
156+
</Show>
157+
{formatTokenCount(stats().inputTokens)} in · {formatTokenCount(stats().outputTokens)} out
158+
</text>
159+
)}
160+
</Show>
63161
<Show when={permissions().length > 0}>
64162
<text fg={theme.warning}>
65163
<span style={{ fg: theme.warning }}>△</span> {permissions().length} Permission
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { formatTokenCount, formatTps } from "./tokens"
3+
4+
describe("formatTokenCount", () => {
5+
test("formats small numbers as-is", () => {
6+
expect(formatTokenCount(0)).toBe("0")
7+
expect(formatTokenCount(42)).toBe("42")
8+
expect(formatTokenCount(999)).toBe("999")
9+
})
10+
11+
test("formats thousands with K suffix", () => {
12+
expect(formatTokenCount(1_000)).toBe("1.0K")
13+
expect(formatTokenCount(1_500)).toBe("1.5K")
14+
expect(formatTokenCount(10_000)).toBe("10K")
15+
expect(formatTokenCount(10_500)).toBe("11K")
16+
expect(formatTokenCount(99_999)).toBe("100K")
17+
expect(formatTokenCount(500_000)).toBe("500K")
18+
})
19+
20+
test("rolls K to M at boundary", () => {
21+
expect(formatTokenCount(999_499)).toBe("999K")
22+
expect(formatTokenCount(999_500)).toBe("1.0M")
23+
expect(formatTokenCount(999_999)).toBe("1.0M")
24+
})
25+
26+
test("formats millions with M suffix", () => {
27+
expect(formatTokenCount(1_000_000)).toBe("1.0M")
28+
expect(formatTokenCount(1_500_000)).toBe("1.5M")
29+
expect(formatTokenCount(4_470_000)).toBe("4.5M")
30+
expect(formatTokenCount(10_000_000)).toBe("10M")
31+
})
32+
})
33+
34+
describe("formatTps", () => {
35+
test("formats sub-1 as <1", () => {
36+
expect(formatTps(0)).toBe("<1")
37+
expect(formatTps(0.01)).toBe("<1")
38+
expect(formatTps(0.5)).toBe("<1")
39+
expect(formatTps(0.99)).toBe("<1")
40+
})
41+
42+
test("formats single digits with one decimal", () => {
43+
expect(formatTps(1.0)).toBe("1.0")
44+
expect(formatTps(5.7)).toBe("5.7")
45+
expect(formatTps(9.9)).toBe("9.9")
46+
expect(formatTps(9.94)).toBe("9.9")
47+
})
48+
49+
test("transitions cleanly at 10 boundary", () => {
50+
expect(formatTps(9.95)).toBe("10")
51+
expect(formatTps(9.99)).toBe("10")
52+
expect(formatTps(10)).toBe("10")
53+
})
54+
55+
test("formats 10+ as integers", () => {
56+
expect(formatTps(10.5)).toBe("11")
57+
expect(formatTps(142.3)).toBe("142")
58+
expect(formatTps(1000)).toBe("1000")
59+
})
60+
})
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Token usage formatting utilities for the TUI footer display.
3+
*
4+
* Provides compact formatting for token counts (K/M suffixes)
5+
* and tokens-per-second calculation during streaming.
6+
*/
7+
8+
/**
9+
* Format a token count with compact suffixes.
10+
* 0-999: "123"
11+
* 1,000-999,999: "1.2K" (rolls to M at boundary)
12+
* 1,000,000+: "1.2M"
13+
*/
14+
export function formatTokenCount(count: number): string {
15+
if (count < 1_000) return count.toString()
16+
if (count < 1_000_000) {
17+
const k = count / 1_000
18+
if (Math.round(k) >= 1_000) return "1.0M"
19+
return k >= 10 ? `${Math.round(k)}K` : `${k.toFixed(1)}K`
20+
}
21+
const m = count / 1_000_000
22+
return m >= 10 ? `${Math.round(m)}M` : `${m.toFixed(1)}M`
23+
}
24+
25+
/**
26+
* Format tokens-per-second with appropriate precision.
27+
* <1: "<1"
28+
* 1-9.9: "5.7" (one decimal)
29+
* 10+: "142" (integer)
30+
*/
31+
export function formatTps(tps: number): string {
32+
if (tps < 1) return "<1"
33+
if (tps < 9.95) return tps.toFixed(1)
34+
return Math.round(tps).toString()
35+
}

0 commit comments

Comments
 (0)