Skip to content

The agent that grows with you

fix(tui): /usage shows main's session totals on the canonical gateway

Tekniumbd7e828489f9
diff --git a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts b/ui-tui/src/__tests__/canonicalSlashCommands.test.ts
index 6764f2b5d06..2a59f5a35d1 100644
--- a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts
+++ b/ui-tui/src/__tests__/canonicalSlashCommands.test.ts
@@ -43,6 +43,14 @@ function harness() {
return { session_id: 'owner', operation: 'reasoning', revision: 8, execution_generation: 4, effort: params.payload.effort }
}
+ if (method === 'session.stats') {
+ return {
+ api_calls: 2, compression_count: 0, context_length: 128000, context_source: 'provider_usage',
+ input_tokens: 200, last_prompt_tokens: 100, model: 'fake-model', output_tokens: 40, prompt_tokens: 200,
+ total_tokens: 240
+ }
+ }
+
if (method === 'prompt.receipt') {
return { status: 'terminal', result: { model: 'm', input_tokens: 5, output_tokens: 7, total_tokens: 12, api_calls: 1 } }
}
@@ -121,33 +129,36 @@ it('/title renames and /undo, /retry rewind through session.mutate with the snap
expect(request.mock.calls.some(([method]) => LEGACY.includes(method))).toBe(false)
})
-it('/usage renders the committed turn result and /tools says what the shared gateway lacks', async () => {
+it("/usage renders main's session totals from session.stats and /tools says what the shared gateway lacks", async () => {
const { panel, request, slash, sys } = harness()
- slash('/usage')
- await flush()
- expect(sys).toHaveBeenCalledWith('no completed turn in this view yet')
-
noteCanonicalCompletion('owner', 'adm-1')
slash('/usage')
await flush()
- expect(request).toHaveBeenCalledWith('prompt.receipt', { admission_id: 'adm-1', include_result: true, session_id: 'owner' })
- expect(panel).toHaveBeenCalledWith('Usage · last turn', [
- { rows: expect.arrayContaining([['Total tokens', '12'], ['API calls', '1']]) }
+ expect(request).toHaveBeenCalledWith('session.stats', { session_id: 'owner' })
+ // Main's one Usage panel with session totals and the context line; no "last turn" panel.
+ expect(panel).toHaveBeenCalledTimes(1)
+ expect(panel).toHaveBeenCalledWith('Usage', [
+ {
+ rows: [
+ ['Model', 'fake-model'],
+ ['Input tokens', '200'],
+ ['Output tokens', '40'],
+ ['Total tokens', '240'],
+ ['API calls', '2']
+ ]
+ },
+ { text: expect.stringContaining('100 / 128,000 (0%)') }
])
- expect(sys).toHaveBeenCalledWith('session totals are not available on the shared gateway yet')
+ expect(sys.mock.calls.some(([line]) => /not available on the shared gateway/.test(line))).toBe(false)
+ expect(getUiState().usage).toMatchObject({ calls: 2, total: 240, context_max: 128000 })
slash('/tools')
await flush()
expect(sys).toHaveBeenCalledWith('toolsets fixed at session launch: terminal, web')
expect(sys).toHaveBeenCalledWith('/tools is not available on the shared gateway yet')
expect(sys.mock.calls.some(([line]) => /request_failed|unsupported_command|unknown_method/.test(line))).toBe(false)
- // Session totals are the owner's reviewed /usage read; no other legacy route.
- expect(
- request.mock.calls.some(
- ([method, params]) => LEGACY.includes(method) && !(method === 'slash.exec' && params.command === 'usage')
- )
- ).toBe(false)
+ expect(request.mock.calls.some(([method]) => LEGACY.includes(method))).toBe(false)
})
it('/status reads through the gateway; /save, /bg and /btw refuse instead of calling sidecar-only RPCs', async () => {
diff --git a/ui-tui/src/__tests__/canonicalUsageTotals.test.ts b/ui-tui/src/__tests__/canonicalUsageTotals.test.ts
index b35ec994857..50831ffece8 100644
--- a/ui-tui/src/__tests__/canonicalUsageTotals.test.ts
+++ b/ui-tui/src/__tests__/canonicalUsageTotals.test.ts
@@ -5,23 +5,22 @@ import { noteCanonicalCompletion } from '../app/slash/canonicalSessionCommands.j
import { patchUiState, resetUiState } from '../app/uiStore.js'
const flush = () => new Promise(resolve => setTimeout(resolve, 5))
-const REPORT = 'Session token usage\nModel: reads-model\nAPI calls: 3\nTotal tokens: 1,234'
+
+// The owner's session-cumulative counters (`gateway/session_usage.py::usage_stats`).
+const STATS = {
+ api_calls: 11, compression_count: 1, context_length: 128000, context_source: 'provider_usage', input_tokens: 1100,
+ last_prompt_tokens: 900, model: 'reads-model', output_tokens: 134, prompt_tokens: 1100, total_tokens: 1234
+}
beforeEach(() => {
resetUiState()
patchUiState({ sid: 'owner', info: { model: 'm', skills: {}, tools: {} } as any })
})
-// The owner serves `/usage` as a reviewed session read (slash.exec, as the classic CLI uses it):
-// Ink on the shared gateway shows those session totals instead of "not available yet".
-it('/usage shows the session totals the shared gateway reports, then the last turn', async () => {
- const request = vi.fn(async (method: string, params: any) => {
- if (method === 'slash.exec' && params.command === 'usage') {
- return { output: REPORT }
- }
-
- if (method === 'prompt.receipt') {
- return { result: { api_calls: 1, input_tokens: 5, model: 'm', output_tokens: 7, total_tokens: 12 } }
+function harness(stats: Record<string, unknown>) {
+ const request = vi.fn(async (method: string) => {
+ if (method === 'session.stats') {
+ return stats
}
throw new Error(`unknown_method: ${method}`)
@@ -40,12 +39,46 @@ it('/usage shows the session totals the shared gateway reports, then the last tu
transcript: { page, panel, send: vi.fn(), setHistoryItems: vi.fn(), sys, trimLastExchange: (x: unknown[]) => x }
} as any)
+ return { page, panel, request, slash, sys }
+}
+
+// FINDINGS rows 5/18: main's /usage is ONE "Usage" panel of session totals (all API calls of the
+// session, the context line, compressions) — not the messaging gateway's markdown page and not a
+// "last turn" panel with a fabricated $0.0000 cost.
+it("/usage shows main's session totals panel from the owner's session.stats", async () => {
+ const { page, panel, request, slash, sys } = harness(STATS)
+
noteCanonicalCompletion('owner', 'adm-1')
slash('/usage')
await flush()
- expect(request).toHaveBeenCalledWith('slash.exec', { command: 'usage', session_id: 'owner' })
- expect(page).toHaveBeenCalledWith(REPORT, 'Usage')
- expect(panel).toHaveBeenCalledWith('Usage · last turn', [{ rows: expect.arrayContaining([['Total tokens', '12']]) }])
+ expect(request).toHaveBeenCalledWith('session.stats', { session_id: 'owner' })
+ expect(request).not.toHaveBeenCalledWith('slash.exec', expect.anything())
+ expect(request).not.toHaveBeenCalledWith('prompt.receipt', expect.anything())
+ expect(page).not.toHaveBeenCalled()
+ expect(panel).toHaveBeenCalledTimes(1)
+ expect(panel).toHaveBeenCalledWith('Usage', [
+ {
+ rows: [
+ ['Model', 'reads-model'],
+ ['Input tokens', '1,100'],
+ ['Output tokens', '134'],
+ ['Total tokens', '1,234'],
+ ['API calls', '11']
+ ]
+ },
+ { text: expect.stringContaining('900 / 128,000 (1%)') },
+ { text: expect.stringContaining('1') }
+ ])
expect(sys).not.toHaveBeenCalledWith('session totals are not available on the shared gateway yet')
})
+
+it('/usage before any API call says so, as main did', async () => {
+ const { panel, slash, sys } = harness({ ...STATS, api_calls: 0, total_tokens: 0 })
+
+ slash('/usage')
+ await flush()
+
+ expect(panel).not.toHaveBeenCalled()
+ expect(sys.mock.calls[0]?.[0]).toMatch(/no API calls/i)
+})
diff --git a/ui-tui/src/app/slash/canonicalSessionCommands.ts b/ui-tui/src/app/slash/canonicalSessionCommands.ts
index d39d5bf1037..2f9839a4282 100644
--- a/ui-tui/src/app/slash/canonicalSessionCommands.ts
+++ b/ui-tui/src/app/slash/canonicalSessionCommands.ts
@@ -3,14 +3,14 @@
// `session.mutate` rename / rewind (`gateway/session_mutations.py`), the committed admission
// result (`prompt.receipt include_result`) and the frozen launch policy (`session.info`).
-import type { SlashExecResponse } from '../../gatewayTypes.js'
+import { usageFromTick } from '../../domain/usage.js'
import { t } from '../../i18n/runtime.js'
import { asRpcResult } from '../../lib/rpc.js'
-import type { PanelSection } from '../../types.js'
-import { getUiState, patchUiState } from '../uiStore.js'
+import { patchUiState } from '../uiStore.js'
import { mutateCanonical, type MutationSnapshot } from './canonicalSessionControls.js'
import type { SlashRunCtx } from './types.js'
+import { usageTotalsSections } from './usagePanel.js'
const COMPACTION_MARKERS = ['[CONTEXT COMPACTION', '[CONTEXT SUMMARY]:', '[END OF PRIOR CONTEXT']
@@ -190,61 +190,32 @@ interface CommittedResult {
total_tokens?: number
}
-/** `/usage`: session totals are the owner's own `/usage` report for this session (a reviewed read,
- * as the classic CLI shows it); every settled turn also commits its own usage with the admission,
- * so the last one this view saw follows. */
+/** `/usage`: main's session totals panel. The owner's `session.stats` is the same session-cumulative
+ * dict its `session.usage` ticks carry (`gateway/session_usage.py`), mapped onto main's `Usage` shape
+ * and rendered exactly as main's sidecar `/usage` did (Usage panel, or "no API calls yet", then the
+ * plan CTA). */
export function canonicalUsage(ctx: SlashRunCtx) {
const sid = ctx.sid!
- const admissionId = lastAdmission.get(sid)
- const unavailable = () => !ctx.stale() && ctx.transcript.sys(t('canonical.controls.usageTotalsUnavailable'))
-
- const totals = ctx.gateway.gw
- .request<SlashExecResponse>('slash.exec', { command: 'usage', session_id: sid })
- .then(r => {
- if (!r?.output) {
- return unavailable()
- }
-
- if (!ctx.stale()) {
- ctx.transcript.page(r.output, t('slashCmd.session.usage.usageTitle'))
- }
- }, unavailable)
- if (!admissionId) {
- return void totals.then(() => !ctx.stale() && ctx.transcript.sys(t('canonical.controls.usageNoTurn')))
- }
-
- void totals
- .then(() =>
- ctx.gateway.gw.request('prompt.receipt', { admission_id: admissionId, include_result: true, session_id: sid })
- )
+ void ctx.gateway.gw
+ .request('session.stats', { session_id: sid })
.then(raw => {
if (ctx.stale()) {
return
}
- const result = asRpcResult<{ result?: CommittedResult }>(raw)?.result
-
- if (!result) {
- return ctx.transcript.sys(t('canonical.controls.usageNoTurn'))
- }
-
- const f = (value: number | undefined) => (value ?? 0).toLocaleString()
+ const usage = usageFromTick(asRpcResult<Record<string, unknown>>(raw))
- const rows: [string, string][] = [
- [t('slashCmd.session.usage.rowModel'), result.model ?? getUiState().info?.model ?? ''],
- [t('slashCmd.session.usage.rowInputTokens'), f(result.input_tokens)],
- [t('slashCmd.session.usage.rowOutputTokens'), f(result.output_tokens)],
- [t('slashCmd.session.usage.rowTotalTokens'), f(result.total_tokens)],
- [t('slashCmd.session.usage.rowApiCalls'), f(result.api_calls)],
- ...(typeof result.estimated_cost_usd === 'number'
- ? ([[t('canonical.controls.rowCost'), `$${result.estimated_cost_usd.toFixed(4)}`]] as [string, string][])
- : [])
- ]
+ if (!usage?.calls) {
+ ctx.transcript.sys(t('slashCmd.session.usage.noCalls'))
+ ctx.transcript.sys(t('slashCmd.session.usage.cta'))
- const sections: PanelSection[] = [{ rows }]
+ return
+ }
- ctx.transcript.panel(t('canonical.controls.usageLastTurnTitle'), sections)
+ patchUiState(state => ({ ...state, usage: { ...state.usage, ...usage } }))
+ ctx.transcript.panel(t('slashCmd.session.usage.usageTitle'), usageTotalsSections(usage))
+ ctx.transcript.sys(t('slashCmd.session.usage.cta'))
})
.catch(ctx.guardedErr)
}
diff --git a/ui-tui/src/app/slash/commands/session.ts b/ui-tui/src/app/slash/commands/session.ts
index f330a9f9079..32c2def7a8d 100644
--- a/ui-tui/src/app/slash/commands/session.ts
+++ b/ui-tui/src/app/slash/commands/session.ts
@@ -23,6 +23,7 @@ import { getUiState, patchUiState } from '../../uiStore.js'
import { canonicalReasoning, canonicalUsage } from '../canonicalSessionCommands.js'
import { runCanonicalSessionControl } from '../canonicalSessionControls.js'
import type { SlashCommand, SlashRunCtx } from '../types.js'
+import { usageTotalsSections } from '../usagePanel.js'
const TUI_SESSION_MODEL_RE = new RegExp(`(?:^|\\s)${TUI_SESSION_MODEL_FLAG}(?:\\s|$)`)
const REASONING_SESSION_FLAGS = new Set(['--session'])
@@ -889,35 +890,7 @@ export const sessionCommands: SlashCommand[] = [
return
}
- const f = (v: number | undefined) => (v ?? 0).toLocaleString()
-
- const rows: [string, string][] = [
- [t('slashCmd.session.usage.rowModel'), r.model ?? ''],
- [t('slashCmd.session.usage.rowInputTokens'), f(r.input)],
- [t('slashCmd.session.usage.rowOutputTokens'), f(r.output)],
- [t('slashCmd.session.usage.rowTotalTokens'), f(r.total)],
- [t('slashCmd.session.usage.rowApiCalls'), f(r.calls)]
- ]
-
- const sections: PanelSection[] = [{ rows }]
-
- if (r.context_max) {
- const mark = r.context_estimated ? '~' : ''
- sections.push({
- text: t(
- 'slashCmd.session.usage.context',
- `${mark}${f(r.context_used)}`,
- f(r.context_max),
- `${mark}${r.context_percent}`
- )
- })
- }
-
- if (r.compressions) {
- sections.push({ text: t('slashCmd.session.usage.compressions', String(r.compressions)) })
- }
-
- ctx.transcript.panel(t('slashCmd.session.usage.usageTitle'), sections)
+ ctx.transcript.panel(t('slashCmd.session.usage.usageTitle'), usageTotalsSections(r))
sys(t('slashCmd.session.usage.cta'))
})
diff --git a/ui-tui/src/app/slash/usagePanel.ts b/ui-tui/src/app/slash/usagePanel.ts
new file mode 100644
index 00000000000..376cc2d312a
--- /dev/null
+++ b/ui-tui/src/app/slash/usagePanel.ts
@@ -0,0 +1,50 @@
+import { t } from '../../i18n/runtime.js'
+import type { PanelSection } from '../../types.js'
+
+/** Main's `/usage` session-totals panel (model, input / output / total tokens, API calls, the
+ * context line, compressions), from main's `Usage` shape: the sidecar's `session.usage` RPC, or a
+ * canonical owner's `session.stats` mapped through `usageFromTick`. */
+export interface UsageTotals {
+ calls?: null | number
+ compressions?: null | number
+ context_estimated?: boolean | null
+ context_max?: null | number
+ context_percent?: null | number
+ context_used?: null | number
+ input?: null | number
+ model?: null | string
+ output?: null | number
+ total?: null | number
+}
+
+export function usageTotalsSections(r: UsageTotals): PanelSection[] {
+ const f = (v: null | number | undefined) => (v ?? 0).toLocaleString()
+
+ const rows: [string, string][] = [
+ [t('slashCmd.session.usage.rowModel'), r.model ?? ''],
+ [t('slashCmd.session.usage.rowInputTokens'), f(r.input)],
+ [t('slashCmd.session.usage.rowOutputTokens'), f(r.output)],
+ [t('slashCmd.session.usage.rowTotalTokens'), f(r.total)],
+ [t('slashCmd.session.usage.rowApiCalls'), f(r.calls)]
+ ]
+
+ const sections: PanelSection[] = [{ rows }]
+
+ if (r.context_max) {
+ const mark = r.context_estimated ? '~' : ''
+ sections.push({
+ text: t(
+ 'slashCmd.session.usage.context',
+ `${mark}${f(r.context_used)}`,
+ f(r.context_max),
+ `${mark}${r.context_percent}`
+ )
+ })
+ }
+
+ if (r.compressions) {
+ sections.push({ text: t('slashCmd.session.usage.compressions', String(r.compressions)) })
+ }
+
+ return sections
+}
diff --git a/ui-tui/src/i18n/en/canonical.ts b/ui-tui/src/i18n/en/canonical.ts
index a3f40b79929..69423e9905b 100644
--- a/ui-tui/src/i18n/en/canonical.ts
+++ b/ui-tui/src/i18n/en/canonical.ts
@@ -15,11 +15,7 @@ export const canonicalEn = {
notAvailable: (command: string) => `/${command} is not available on the shared gateway yet`,
prefNotSaved: (command: string) => `/${command} applies to this view only; not saved on the shared gateway`,
launchToolsets: (toolsets: string) => `toolsets fixed at session launch: ${toolsets}`,
- usageLastTurnTitle: 'Usage · last turn',
- usageNoTurn: 'no completed turn in this view yet',
- usageTotalsUnavailable: 'session totals are not available on the shared gateway yet',
- retryUnsupported: '/retry: retry does not support media or unknown content parts',
- rowCost: 'Estimated cost'
+ retryUnsupported: '/retry: retry does not support media or unknown content parts'
},
// app/submissionCore.ts — durable admission receipts.
submit: {