Skip to content

The agent that grows with you

refactor(shared): one session.usage tick mapper for Ink and Desktop

yoniebanscf71b1aa3059
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
index 91f802f98fe..3ea0b9af6d3 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts
@@ -1,3 +1,5 @@
+import { usageFromTick } from '@hermes/shared'
+
import { finalizeInterruptedMessages } from '@/lib/chat-messages'
import { normalizePersonalityValue } from '@/lib/chat-runtime'
import { modelOptionsQueryKey } from '@/lib/model-options'
@@ -31,7 +33,6 @@ import {
setYoloActive
} from '@/store/session'
import { reportInstallMethodWarning } from '@/store/updates'
-import type { UsageStats } from '@/types/hermes'
import {
applySessionInfoStatePatch,
@@ -42,106 +43,6 @@ import {
import type { GatewayEventContext } from './types'
-function finiteCount(value: number | null | undefined): number | undefined {
- return value !== null && value !== undefined && Number.isFinite(value) ? value : undefined
-}
-
-function firstPositiveOrDefined(
- primary: number | null | undefined,
- fallback: number | null | undefined
-): number | undefined {
- const first = finiteCount(primary)
- const second = finiteCount(fallback)
-
- return (first || second) ?? first
-}
-
-function canonicalContextUsage(payload: NonNullable<GatewayEventContext['payload']>): Partial<UsageStats> {
- const contextMax = finiteCount(payload.context_length)
-
- if (contextMax === undefined) {
- return {}
- }
-
- const compressionCount = finiteCount(payload.compression_count)
- const fields: Partial<UsageStats> = compressionCount === undefined ? {} : { compressions: compressionCount }
- const contextUsed = finiteCount(payload.last_prompt_tokens)
-
- if (!contextUsed || contextUsed <= 0 || contextMax <= 0) {
- return fields
- }
-
- const clamped = Math.min(contextUsed, contextMax)
- const source = payload.context_source || 'provider_usage'
-
- return {
- ...fields,
- context_estimated: source !== 'provider_usage',
- context_max: contextMax,
- context_percent: Math.max(0, Math.min(100, Math.round((clamped / contextMax) * 100))),
- context_source: source,
- context_used: clamped
- }
-}
-
-function canonicalRateUsage(payload: NonNullable<GatewayEventContext['payload']>): Partial<UsageStats> {
- const fields: Partial<UsageStats> = {}
- const prompt = finiteCount(payload.prompt_tokens)
- const cacheRead = finiteCount(payload.cache_read_tokens)
- const tokensPerSecond = finiteCount(payload.tokens_per_s)
-
- if (prompt !== undefined && prompt > 0 && cacheRead !== undefined && cacheRead > 0) {
- fields.cache_hit_pct = Math.max(0, Math.min(100, Math.round((cacheRead / prompt) * 100)))
- }
-
- if (tokensPerSecond !== undefined) {
- fields.avg_tps = Math.round(tokensPerSecond * 10) / 10
- }
-
- return fields
-}
-
-function canonicalCounterUsage(payload: NonNullable<GatewayEventContext['payload']>): Partial<UsageStats> {
- const usage: Partial<UsageStats> = {}
- const input = firstPositiveOrDefined(payload.input_tokens, payload.prompt_tokens)
- const output = firstPositiveOrDefined(payload.output_tokens, payload.completion_tokens)
- const total = finiteCount(payload.total_tokens)
- const calls = finiteCount(payload.api_calls)
-
- if (input !== undefined) {
- usage.input = input
- }
-
- if (output !== undefined) {
- usage.output = output
- }
-
- if (total !== undefined) {
- usage.total = total
- }
-
- if (calls !== undefined) {
- usage.calls = calls
- }
-
- return usage
-}
-
-/** Normalize canonical top-level counters; legacy ticker frames stay nested. */
-function canonicalUsage(payload: GatewayEventContext['payload']): Partial<UsageStats> | undefined {
- if (!payload || payload.usage) {
- return payload?.usage
- }
-
- const usage: Partial<UsageStats> = {
- ...canonicalCounterUsage(payload),
- ...canonicalContextUsage(payload),
- ...canonicalRateUsage(payload)
- }
-
- return Object.keys(usage).length > 0 ? usage : undefined
-}
-
/**
* Whether a `session.info` payload's `stored_session_id` may be treated as the
* selected conversation's, so its cwd and branch can be claimed for it
@@ -639,7 +540,7 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {
// Live usage tick emitted while a turn is mid-flight (see tui_gateway
// _start_usage_ticker) so the status-bar context window tracks growth
// during the turn instead of only jumping at message.complete.
- const usage = canonicalUsage(payload)
+ const usage = usageFromTick(payload)
if (usage && sessionId) {
// Per-session twin first: a focused secondary tile reads this cache,
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsx
index ea7357e5bfe..96a0dfbabd2 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsx
@@ -78,11 +78,41 @@ describe('useMessageStream status-bar usage scoping', () => {
calls: 3,
input: 1_200,
output: 80,
+ prompt: 1_000,
total: 1_280
})
expect(sessionStates.get(SID)?.usage).toEqual($currentUsage.get())
})
+ it('maps latency and active subagents from a canonical tick the same way Ink does', () => {
+ mountStream()
+
+ act(() =>
+ stream.handleEvent({
+ payload: { active_subagents: 2, api_calls: 1, avg_latency_s: 0.84, total_tokens: 10 },
+ session_id: SID,
+ type: 'session.usage'
+ })
+ )
+
+ expect($currentUsage.get()).toMatchObject({ active_subagents: 2, avg_latency_s: 0.8, calls: 1, total: 10 })
+ })
+
+ it('merges a partial canonical tick without zeroing counters it does not carry', () => {
+ mountStream()
+
+ act(() => stream.handleEvent({ payload: { api_calls: 3 }, session_id: SID, type: 'session.usage' }))
+ act(() =>
+ stream.handleEvent({
+ payload: { context_length: 10_000, last_prompt_tokens: 4_200 },
+ session_id: SID,
+ type: 'session.usage'
+ })
+ )
+
+ expect($currentUsage.get()).toMatchObject({ ...BASELINE, calls: 3, context_percent: 42, context_used: 4_200 })
+ })
+
it('falls back to prompt_tokens and completion_tokens when input_tokens and output_tokens are zero', () => {
mountStream()
@@ -104,8 +134,10 @@ describe('useMessageStream status-bar usage scoping', () => {
expect($currentUsage.get()).toEqual({
...BASELINE,
calls: 3,
+ completion: 80,
input: 1_000,
output: 80,
+ prompt: 1_000,
total: 1_080
})
})
diff --git a/apps/shared/package.json b/apps/shared/package.json
index a62f7e2ae83..1dc8ebfb573 100644
--- a/apps/shared/package.json
+++ b/apps/shared/package.json
@@ -20,7 +20,8 @@
"./reconnect-backoff": "./src/reconnect-backoff.ts",
"./skin": "./src/skin.ts",
"./slash": "./src/slash.ts",
- "./theme-presets": "./src/theme-presets.ts"
+ "./theme-presets": "./src/theme-presets.ts",
+ "./usage-tick": "./src/usage-tick.ts"
},
"types": "./src/index.ts",
"scripts": {
diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.ts
index b67989b3607..0a360d911e1 100644
--- a/apps/shared/src/index.ts
+++ b/apps/shared/src/index.ts
@@ -175,6 +175,7 @@ export {
type WindowsBackgroundMaterial
} from './translucency'
export { type UpdateDebt, updateDebt, type UpdateDebtReceipt, type UpdateDebtStep } from './update-debt'
+export { usageFromTick, type UsageTickPayload } from './usage-tick'
export {
buildHermesWebSocketUrl,
type GatewayAuthMode,
diff --git a/apps/shared/src/usage-tick.ts b/apps/shared/src/usage-tick.ts
new file mode 100644
index 00000000000..c2b2d1c5e46
--- /dev/null
+++ b/apps/shared/src/usage-tick.ts
@@ -0,0 +1,135 @@
+import type { SessionStats, SessionUsagePayload, Usage } from './gateway-contract.generated.js'
+
+/** The owner's `session.usage` tick (`SessionUsagePayload`, canonical counters at the top level or the classic sidecar ticker's nested `usage`) or its `session.stats` reply (`SessionStats`). */
+export type UsageTickPayload = SessionStats | SessionUsagePayload
+
+/** What `usageFromTick` computes from top-level counters: the `Usage` fields both status bars read. */
+export interface TickUsage {
+ active_subagents?: number
+ avg_latency_s?: number
+ avg_tps?: number
+ cache_hit_pct?: number
+ calls: number
+ completion: number
+ compressions?: number
+ context_estimated?: boolean
+ context_max?: number
+ context_percent?: number
+ context_source?: string
+ context_used?: number
+ input: number
+ model?: string
+ output: number
+ prompt: number
+ reasoning: number
+ total: number
+}
+
+type Count = 'calls' | 'completion' | 'input' | 'output' | 'prompt' | 'reasoning' | 'total'
+type CountSource =
+ | 'api_calls'
+ | 'completion_tokens'
+ | 'input_tokens'
+ | 'output_tokens'
+ | 'prompt_tokens'
+ | 'reasoning_tokens'
+ | 'total_tokens'
+
+const num = (value: null | number | undefined): number | undefined =>
+ value !== null && value !== undefined && Number.isFinite(value) ? value : undefined
+
+const round1 = (value: number) => Math.round(value * 10) / 10
+const pct = (part: number, whole: number) => Math.max(0, Math.min(100, Math.round((part / whole) * 100)))
+
+// `TickUsage` key ← owner stats key(s), first non-zero wins (`gateway/session_usage.py::tui_usage`).
+const COUNTERS: [Count, CountSource[]][] = [
+ ['calls', ['api_calls']],
+ ['input', ['input_tokens', 'prompt_tokens']],
+ ['output', ['output_tokens', 'completion_tokens']],
+ ['reasoning', ['reasoning_tokens']],
+ ['prompt', ['prompt_tokens']],
+ ['completion', ['completion_tokens']],
+ ['total', ['total_tokens']]
+]
+
+function contextFields(p: UsageTickPayload): Partial<TickUsage> {
+ const used = num(p.last_prompt_tokens) ?? 0
+ const max = num(p.context_length) ?? 0
+ const compressions = num(p.compression_count)
+ const fields: Partial<TickUsage> = p.context_length == null || compressions === undefined ? {} : { compressions }
+
+ if (!used || !max) {
+ return fields
+ }
+
+ const source = p.context_source || 'provider_usage'
+ const clamped = Math.min(used, max)
+
+ return {
+ ...fields,
+ context_estimated: source !== 'provider_usage',
+ context_max: max,
+ context_percent: pct(clamped, max),
+ context_source: source,
+ context_used: clamped
+ }
+}
+
+function rateFields(p: UsageTickPayload): Partial<TickUsage> {
+ const fields: Partial<TickUsage> = {}
+ const promptTotal = num(p.prompt_tokens) ?? 0
+ const cacheRead = num(p.cache_read_tokens) ?? 0
+ const latency = num(p.avg_latency_s)
+ const tps = num(p.tokens_per_s)
+ const subagents = num(p.active_subagents)
+
+ if (promptTotal > 0 && cacheRead > 0) {
+ fields.cache_hit_pct = pct(cacheRead, promptTotal)
+ }
+
+ if (latency !== undefined) {
+ fields.avg_latency_s = round1(latency)
+ }
+
+ if (tps !== undefined) {
+ fields.avg_tps = round1(tps)
+ }
+
+ if (subagents !== undefined) {
+ fields.active_subagents = subagents
+ }
+
+ return fields
+}
+
+/** A canonical local viewer's `session.usage` tick carries the owner's session-cumulative counters at the top level; the classic sidecar ticker's nested `usage` passes through unchanged. Each figure maps only when its source is present, so a partial tick never zeroes a counter it did not carry (`session_usage.tui_usage` is the Python twin used for `message.complete.usage`). */
+export function usageFromTick<Nested = Usage>(
+ payload: null | undefined | (UsageTickPayload & { usage?: Nested | null })
+): Nested | Partial<TickUsage> | undefined {
+ if (!payload) {
+ return undefined
+ }
+
+ if ('usage' in payload && payload.usage) {
+ return payload.usage
+ }
+
+ const usage: Partial<TickUsage> = {}
+
+ for (const [key, sources] of COUNTERS) {
+ const values = sources.map(source => num(payload[source]))
+ const value = values.find(Boolean) ?? values.find(v => v !== undefined)
+
+ if (value !== undefined) {
+ usage[key] = value
+ }
+ }
+
+ const derived = { ...usage, ...contextFields(payload), ...rateFields(payload) }
+
+ if (Object.keys(derived).length === 0) {
+ return undefined
+ }
+
+ return payload.model ? { ...derived, model: payload.model } : derived
+}
diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.usage.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.usage.test.ts
index 67ffe7a1171..9dea14e7f37 100644
--- a/ui-tui/src/__tests__/createGatewayEventHandler.usage.test.ts
+++ b/ui-tui/src/__tests__/createGatewayEventHandler.usage.test.ts
@@ -8,7 +8,12 @@ const ref = <T>(current: T) => ({ current })
const ctx = () =>
({
- composer: { dequeue: () => undefined, queueEditRef: ref<null | number>(null), sendQueued: vi.fn(), setInput: vi.fn() },
+ composer: {
+ dequeue: () => undefined,
+ queueEditRef: ref<null | number>(null),
+ sendQueued: vi.fn(),
+ setInput: vi.fn()
+ },
gateway: { gw: { request: vi.fn(async () => null) }, rpc: vi.fn(async () => null) },
session: {
STARTUP_RESUME_ID: '',
@@ -26,9 +31,19 @@ const ctx = () =>
// The owner's session-cumulative counters (`gateway/session_usage.py::usage_stats`).
const STATS = {
- api_calls: 2, avg_latency_s: 0.14, cache_read_tokens: 0, compression_count: 1, context_length: 128000,
- context_source: 'provider_usage', input_tokens: 100, last_prompt_tokens: 900, model: 'fake-model',
- output_tokens: 40, prompt_tokens: 100, tokens_per_s: 229.4, total_tokens: 140
+ api_calls: 2,
+ avg_latency_s: 0.14,
+ cache_read_tokens: 0,
+ compression_count: 1,
+ context_length: 128000,
+ context_source: 'provider_usage',
+ input_tokens: 100,
+ last_prompt_tokens: 900,
+ model: 'fake-model',
+ output_tokens: 40,
+ prompt_tokens: 100,
+ tokens_per_s: 229.4,
+ total_tokens: 140
}
describe('canonical session.usage tick', () => {
@@ -39,8 +54,16 @@ describe('canonical session.usage tick', () => {
onEvent({ payload: STATS, session_id: 'sess-1', type: 'session.usage' } as any)
expect(getUiState().usage).toMatchObject({
- avg_latency_s: 0.1, avg_tps: 229.4, calls: 2, compressions: 1, context_max: 128000,
- context_percent: 1, context_used: 900, input: 100, output: 40, total: 140
+ avg_latency_s: 0.1,
+ avg_tps: 229.4,
+ calls: 2,
+ compressions: 1,
+ context_max: 128000,
+ context_percent: 1,
+ context_used: 900,
+ input: 100,
+ output: 40,
+ total: 140
})
})
@@ -56,4 +79,16 @@ describe('canonical session.usage tick', () => {
expect(usage).not.toHaveProperty('context_max')
expect(usage).not.toHaveProperty('avg_tps')
})
+
+ it('maps a partial tick to only the figures it carries', () => {
+ expect(usageFromTick({ input_tokens: 1200, output_tokens: 80 })).toEqual({ input: 1200, output: 80 })
+ expect(usageFromTick({ api_calls: 3 })).toEqual({ calls: 3 })
+ expect(usageFromTick({ context_length: 10000, last_prompt_tokens: 4200 })).toMatchObject({
+ context_max: 10000,
+ context_percent: 42,
+ context_used: 4200
+ })
+ expect(usageFromTick({ input_tokens: 0, prompt_tokens: 1000 })).toEqual({ input: 1000, prompt: 1000 })
+ expect(usageFromTick({ model: 'only-a-model' })).toBeUndefined()
+ })
})
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index ebf0c12ebae..2aa379a61ee 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -579,8 +579,8 @@ function handleErrorEvent(
/** Live usage tick while a turn runs (see tui_gateway _start_usage_ticker): keeps the status-bar
* context window current mid-turn instead of only at message.complete. The session filter at the
* top of the handler already dropped ticks for non-focused sessions. */
-function applyUsageTick(payload: unknown): void {
- const usage = usageFromTick(payload as Parameters<typeof usageFromTick>[0]) // canonical: the owner's counters at the top level
+function applyUsageTick(payload: Extract<AnyGatewayEvent, { type: 'session.usage' }>['payload']): void {
+ const usage = usageFromTick(payload) // canonical: the owner's counters at the top level
if (usage) {
patchUiState(state => ({ ...state, usage: { ...state.usage, ...usage } }))
diff --git a/ui-tui/src/app/slash/canonicalSessionCommands.ts b/ui-tui/src/app/slash/canonicalSessionCommands.ts
index 5dcee65432e..ebd6427654b 100644
--- a/ui-tui/src/app/slash/canonicalSessionCommands.ts
+++ b/ui-tui/src/app/slash/canonicalSessionCommands.ts
@@ -3,6 +3,8 @@
// `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 { SessionStats } from '@hermes/shared/gateway-events'
+
import { CANONICAL_REASONING_EFFORTS } from '../../domain/slash.js'
import { usageFromTick } from '../../domain/usage.js'
import { t } from '../../i18n/runtime.js'
@@ -191,7 +193,7 @@ export function canonicalUsage(ctx: SlashRunCtx) {
return
}
- const usage = usageFromTick(asRpcResult<Record<string, unknown>>(raw))
+ const usage = usageFromTick(asRpcResult<SessionStats>(raw))
if (!usage?.calls) {
ctx.transcript.sys(t('slashCmd.session.usage.noCalls'))
diff --git a/ui-tui/src/domain/usage.ts b/ui-tui/src/domain/usage.ts
index 48030ae1086..8aa5ecc3fea 100644
--- a/ui-tui/src/domain/usage.ts
+++ b/ui-tui/src/domain/usage.ts
@@ -1,98 +1,5 @@
import type { Usage } from '@hermes/shared/gateway-events'
-export const ZERO: Usage = { calls: 0, input: 0, output: 0, total: 0 }
-
-const num = (value: unknown): number | undefined =>
- typeof value === 'number' && Number.isFinite(value) ? value : undefined
-
-const round1 = (value: number) => Math.round(value * 10) / 10
-const pct = (part: number, whole: number) => Math.max(0, Math.min(100, Math.round((part / whole) * 100)))
-
-// Main `Usage` key ← owner stats key(s), first non-zero wins (`gateway/session_usage.py::tui_usage`).
-const COUNTERS: [keyof Usage, string[]][] = [
- ['calls', ['api_calls']],
- ['input', ['input_tokens', 'prompt_tokens']],
- ['output', ['output_tokens', 'completion_tokens']],
- ['reasoning', ['reasoning_tokens']],
- ['prompt', ['prompt_tokens']],
- ['completion', ['completion_tokens']],
- ['total', ['total_tokens']]
-]
-
-function contextFields(p: Record<string, unknown>): Partial<Usage> {
- const used = num(p.last_prompt_tokens) ?? 0
- const max = num(p.context_length) ?? 0
- const fields: Partial<Usage> = p.context_length == null ? {} : { compressions: num(p.compression_count) ?? 0 }
-
- if (!used || !max) {
- return fields
- }
-
- const source = typeof p.context_source === 'string' && p.context_source ? p.context_source : 'provider_usage'
- const clamped = Math.min(used, max)
-
- return {
- ...fields,
- context_estimated: source !== 'provider_usage',
- context_max: max,
- context_percent: pct(clamped, max),
- context_source: source,
- context_used: clamped
- }
-}
-
-function rateFields(p: Record<string, unknown>): Partial<Usage> {
- const fields: Partial<Usage> = {}
- const promptTotal = num(p.prompt_tokens) ?? 0
- const cacheRead = num(p.cache_read_tokens) ?? 0
- const latency = num(p.avg_latency_s)
- const tps = num(p.tokens_per_s)
-
- if (promptTotal > 0 && cacheRead > 0) {
- fields.cache_hit_pct = pct(cacheRead, promptTotal)
- }
-
- if (latency !== undefined) {
- fields.avg_latency_s = round1(latency)
- }
+export { usageFromTick } from '@hermes/shared/usage-tick'
- if (tps !== undefined) {
- fields.avg_tps = round1(tps)
- }
-
- if (num(p.active_subagents) !== undefined) {
- fields.active_subagents = num(p.active_subagents)
- }
-
- return fields
-}
-
-/** A canonical local viewer's `session.usage` tick carries the owner's session-cumulative counters at
- * the top level (`gateway/session_usage.py::usage_stats`, the `session.stats` dict); main's sidecar
- * ticker sent its `_get_usage` shape under `usage`. Both land as the same status-bar `Usage`
- * (`session_usage.tui_usage` is the Python twin used for `message.complete.usage`). */
-export function usageFromTick(payload: unknown): Partial<Usage> | undefined {
- if (!payload || typeof payload !== 'object') {
- return undefined
- }
-
- const p = payload as Record<string, unknown>
-
- if (p.usage && typeof p.usage === 'object') {
- return p.usage as Partial<Usage>
- }
-
- if (num(p.api_calls) === undefined && num(p.total_tokens) === undefined) {
- return undefined
- }
-
- const usage: Partial<Usage> = Object.fromEntries(
- COUNTERS.map(([key, sources]) => [key, sources.map(source => num(p[source])).find(Boolean) ?? 0])
- )
-
- if (typeof p.model === 'string' && p.model) {
- usage.model = p.model
- }
-
- return { ...usage, ...contextFields(p), ...rateFields(p) }
-}
+export const ZERO: Usage = { calls: 0, input: 0, output: 0, total: 0 }