The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(tui): Ink /usage shows session totals on the shared gateway
Tekniumac7bd7a1b8f4
diff --git a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts b/ui-tui/src/__tests__/canonicalSlashCommands.test.tsindex d3f641a6591..43e927a8941 100644--- a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts+++ b/ui-tui/src/__tests__/canonicalSlashCommands.test.ts@@ -138,7 +138,12 @@ it('/usage renders the committed turn result and /tools says what the shared gatexpect(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)- expect(request.mock.calls.some(([method]) => LEGACY.includes(method))).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)})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.tsnew file mode 100644index 00000000000..b35ec994857--- /dev/null+++ b/ui-tui/src/__tests__/canonicalUsageTotals.test.ts@@ -0,0 +1,51 @@+import { beforeEach, expect, it, vi } from 'vitest'++import { createSlashHandler } from '../app/createSlashHandler.js'+import { noteCanonicalCompletion } from '../app/slash/canonicalSessionCommands.js'+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'++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 } }+ }++ throw new Error(`unknown_method: ${method}`)+ })++ const sys = vi.fn()+ const page = vi.fn()+ const panel = vi.fn()++ const slash = createSlashHandler({+ composer: { enqueue: vi.fn() },+ gateway: { gw: { isCanonical: true, request }, rpc: request },+ local: { getHistoryItems: () => [], getLastUserMsg: () => '', maybeWarn: vi.fn() },+ session: { resumeById: vi.fn() },+ slashFlightRef: { current: 0 },+ transcript: { page, panel, send: vi.fn(), setHistoryItems: vi.fn(), sys, trimLastExchange: (x: unknown[]) => x }+ } as any)++ 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(sys).not.toHaveBeenCalledWith('session totals are not available on the shared gateway yet')+})diff --git a/ui-tui/src/app/slash/canonicalSessionCommands.ts b/ui-tui/src/app/slash/canonicalSessionCommands.tsindex 4cbd2bd9369..73f636c2e22 100644--- a/ui-tui/src/app/slash/canonicalSessionCommands.ts+++ b/ui-tui/src/app/slash/canonicalSessionCommands.ts@@ -3,6 +3,7 @@// `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 { t } from '../../i18n/runtime.js'import { asRpcResult } from '../../lib/rpc.js'import type { PanelSection } from '../../types.js'@@ -120,21 +121,34 @@ interface CommittedResult {total_tokens?: number}-/** `/usage`: the shared gateway keeps no session-wide ledger, but every settled turn commits its- * own usage with the admission. Show the last one this view saw, and say what is missing. */+/** `/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. */export function canonicalUsage(ctx: SlashRunCtx) {const sid = ctx.sid!const admissionId = lastAdmission.get(sid)- const unavailable = () => ctx.transcript.sys(t('canonical.controls.usageTotalsUnavailable'))+ const unavailable = () => !ctx.stale() && ctx.transcript.sys(t('canonical.controls.usageTotalsUnavailable'))- if (!admissionId) {- ctx.transcript.sys(t('canonical.controls.usageNoTurn'))+ 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)- return unavailable()+ if (!admissionId) {+ return void totals.then(() => !ctx.stale() && ctx.transcript.sys(t('canonical.controls.usageNoTurn')))}- void ctx.gateway.gw- .request('prompt.receipt', { admission_id: admissionId, include_result: true, session_id: sid })+ void totals+ .then(() =>+ ctx.gateway.gw.request('prompt.receipt', { admission_id: admissionId, include_result: true, session_id: sid })+ ).then(raw => {if (ctx.stale()) {return@@ -143,9 +157,7 @@ export function canonicalUsage(ctx: SlashRunCtx) {const result = asRpcResult<{ result?: CommittedResult }>(raw)?.resultif (!result) {- ctx.transcript.sys(t('canonical.controls.usageNoTurn'))-- return unavailable()+ return ctx.transcript.sys(t('canonical.controls.usageNoTurn'))}const f = (value: number | undefined) => (value ?? 0).toLocaleString()@@ -164,7 +176,6 @@ export function canonicalUsage(ctx: SlashRunCtx) {const sections: PanelSection[] = [{ rows }]ctx.transcript.panel(t('canonical.controls.usageLastTurnTitle'), sections)- unavailable()}).catch(ctx.guardedErr)}