Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Show cached work statistics for known harnesses (#256)

Dee83f147708b1c
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index ec3d02266..b8d2a34f4 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -45,6 +45,7 @@ import { preTrustClaudeProject, preTrustCodexProject } from './lib/claudeTrust.j
import { projectPreview } from './lib/projectPreview.js'
import { readGitProject } from './lib/gitProject.js'
import { agentFrame, lastActivityAt, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'
+import { agentTokenUsage } from './lib/agentTokenUsage.js'
import { installedDsh, listInstalledDsh } from './dsh/installed.js'
import { OrchestratorService } from './orchestrator/service.js'
import { OrchestratorError } from './orchestrator/model.js'
@@ -2582,7 +2583,8 @@ export class BackendSocket {
}
private async toStoppedProject(s: RegisteredSession): Promise<AgentFrame> {
- const frame = await agentFrame(s, { selectedModel: s.model, terminalAvailable: false, dsh: this.dshFrameProvider?.(s) ?? null })
+ const frame = await agentFrame(s, { selectedModel: s.model, terminalAvailable: false, dsh: this.dshFrameProvider?.(s) ?? null,
+ tokenUsage: agentTokenUsage.get(s) })
return {
...frame,
status: 'stopped',
@@ -2596,6 +2598,7 @@ export class BackendSocket {
/** Map a registered tmux session onto the web's Project shape (tabs in ProjectTabs). */
private toProject(s: RegisteredSession): Promise<AgentFrame> {
return agentFrame(s, {
+ tokenUsage: agentTokenUsage.get(s),
selectedModel: this.runtimeProfileProvider?.(s) ?? null,
terminalAvailable: registry.terminalAvailable(s.agentId),
dsh: this.dshFrameProvider?.(s) ?? null,
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 525b1e806..d0c59711f 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -216,6 +216,7 @@ import {
import { probeGatewayRuntime } from './lib/gatewayRuntime.js'
import { probeGridAssignment, sameGridAssignment } from './lib/gridAssignment.js'
import { agentFrame, type AgentFrame } from './lib/agentFrame.js'
+import { agentTokenUsage } from './lib/agentTokenUsage.js'
import { SessionInputController } from './lib/sessionInput.js'
import { adaptSlashCommand } from './lib/goalCommand.js'
import { RuntimeProfileManager, parseRuntimeProfile } from './lib/runtimeProfile.js'
@@ -1193,6 +1194,7 @@ let dshFrameContextRef: ((s: RegisteredSession) => AgentDshContext | null) | nul
function projectFrame(s: RegisteredSession, selectedModel: string | null): Promise<AgentFrame> {
return agentFrame(s, {
+ tokenUsage: agentTokenUsage.get(s),
selectedModel,
terminalAvailable: registry.terminalAvailable(s.agentId),
dsh: dshFrameContextRef?.(s) ?? null,
@@ -1573,6 +1575,19 @@ async function runForeground(session: AuthSession): Promise<void> {
backendRef?.send({ type: 'agent_renamed', payload: { agentId: s.agentId, name, engine: s.engine } })
if (opts.device !== false) backendRef?.sendCommander({ type: 'agent_renamed', payload: { agentId: s.agentId, name, engine: s.engine } })
}
+ agentTokenUsage.onChanged = (target) => {
+ const current = registry.resolve(target.agentId)
+ if (current?.sessionId === target.sessionId && current.engine === target.engine) {
+ if (registry.terminalAvailable(current.agentId)) syncSession(current, { device: false })
+ return
+ }
+ try {
+ const saved = stoppedAgents.get(target.agentId)
+ if (saved?.sessionId === target.sessionId && saved.engine === target.engine) {
+ void backendRef?.publishStoppedAgent(saved).catch(() => {})
+ }
+ } catch { /* A concurrently removed archive has nothing to update. */ }
+ }
// New process observations, session bindings, runtime-profile changes, reconnects and periodic
// reconciliation refresh web and device from the same authoritative snapshot. Device agent_synced is
// idempotent and can upsert a sessionless tile, so re-announcing at bind is both safe and necessary.
@@ -2554,6 +2569,8 @@ async function runForeground(session: AuthSession): Promise<void> {
emitSessionEvents = (sessionId: string, events: ReturnType<CursorNormalizer['ingest']>, opts?: { resumed?: boolean; replay?: boolean }): void => {
if (!events.length || !registry.bySession(sessionId)?.active) return
+ const usageSession = registry.bySession(sessionId)
+ if (usageSession?.engine === 'opencode') agentTokenUsage.changed(usageSession)
for (const event of events) {
const agentId = agentIdFor(sessionId)
const frame = correlateAgentEvent(event, sessionId, agentId)
@@ -3892,6 +3909,7 @@ async function runForeground(session: AuthSession): Promise<void> {
if (!registry.has(evt.sessionId)) return null // scope to terminal-registered sessions
const session = registry.bySession(evt.sessionId)
if (!session || session.engine !== evt.engine) return null
+ agentTokenUsage.changed(session)
runtimeProfiles.ingest(session, evt.text)
let events
if (session.engine === 'codex') {
diff --git a/cli/src/lib/agentFrame.spec.ts b/cli/src/lib/agentFrame.spec.ts
index 95ff980ab..9a7337708 100644
--- a/cli/src/lib/agentFrame.spec.ts
+++ b/cli/src/lib/agentFrame.spec.ts
@@ -20,6 +20,12 @@ function session(grid: RegisteredSession['grid'], codexHome: RegisteredSession['
const assignment = { baseUrl: 'https://grid.autonomous.ai/grid-abc/relay', model: 'DeepSeek-V4-Flash-0731' }
describe('agentFrame', () => {
+ it('carries only the owning machine’s cached token snapshot, including a measured zero', async () => {
+ const context = { selectedModel: null, terminalAvailable: true }
+ const usage = { totalTokens: 0, updatedAt: '2026-09-22T16:00:00Z' }
+ expect((await agentFrame(session(null), { ...context, tokenUsage: usage })).tokenUsage).toEqual(usage)
+ expect((await agentFrame(session(null), context)).tokenUsage).toBeNull()
+ })
// The regression this file exists for: `agent_synced` was built by a SECOND, hand-maintained copy
// of this shape that never grew a `grid` field. The desktop rebuilds its Agent from every push, so
// each sync reset an agent's grid to null and the "N agents are on an older target" banner came
@@ -116,15 +122,20 @@ describe('agentFrame updatedAt', () => {
expect((await agentFrame(row, context)).updatedAt).toBe('2026-09-17T07:00:00.000Z')
})
- it("prefers the transcript's mtime", async () => {
+ it('uses actual conversation activity even when an idle transcript was rewritten hours later', async () => {
const dir = await mkdtemp(join(tmpdir(), 'agent-frame-'))
try {
const transcriptPath = join(dir, 'session.jsonl')
- await writeFile(transcriptPath, '{}\n')
- const written = new Date('2026-09-18T01:02:03.000Z')
- await utimes(transcriptPath, written, written)
+ const activity = '2026-09-18T01:02:03.000Z'
+ await writeFile(transcriptPath, [
+ JSON.stringify({ type: 'assistant', timestamp: activity, message: { content: [] } }),
+ JSON.stringify({ type: 'ai-title', timestamp: '2026-09-18T10:00:00.000Z', title: 'Playtest' }),
+ '',
+ ].join('\n'))
+ const rewritten = new Date('2026-09-18T10:02:03.000Z')
+ await utimes(transcriptPath, rewritten, rewritten)
const row = { ...session(null), transcriptPath, updatedAt: Date.now(), lastHookAt: lastHook }
- expect((await agentFrame(row, context)).updatedAt).toBe(written.toISOString())
+ expect((await agentFrame(row, context)).updatedAt).toBe(activity)
} finally {
await rm(dir, { recursive: true, force: true })
}
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index 12f26d41e..edc60e61b 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -18,8 +18,10 @@
* makes the shape testable without a registry, which is the whole reason the drift went unnoticed.
*/
-import { stat } from 'node:fs/promises'
import { agentProject, type AgentProject } from './agentProject.js'
+import { transcriptActivityAt } from './transcriptActivity.js'
+import type { AgentTokenUsage } from './agentTokenUsage.js'
+import type { AgentOutputStats } from './agentOutputStats.js'
import type { GridAssignment } from './gridAssignment.js'
import type { GridWebSearchStatus } from './gridLaunch.js'
import { projectDisplayName, sessionDisplayTitle, type RegisteredSession } from './registry.js'
@@ -56,6 +58,9 @@ export type AgentFrame = {
launch: NonNullable<RegisteredSession['launch']>
createdAt: string
updatedAt: string
+ /** Cached usage from this conversation's owning machine; null means unreported, never zero. */
+ tokenUsage: AgentTokenUsage | null
+ outputStats: (AgentOutputStats & { updatedAt: string }) | null
tmuxPane: string | null
terminal: { available: boolean; primary: string; runtimes: RegisteredSession['runtimes'] }
engine: RegisteredSession['engine']
@@ -109,21 +114,22 @@ export interface AgentFrameContext {
selectedModel: string | null
/** `registry.terminalAvailable(agentId)` — the caller already holds the registry. */
terminalAvailable: boolean
+ tokenUsage?: AgentTokenUsage | null
/** The DSH companions' state for this agent; absent when the caller has none to give. */
dsh?: AgentDshContext | null
}
/**
- * When the conversation last moved, in epoch ms: the transcript's mtime, else the last time the engine
+ * When the conversation last moved, in epoch ms: dated work in the transcript, else the last time the engine
* reported in (a hook, or a session bind — the agent's creation at the latest).
*
* ⚠️ Never the registry's `updatedAt`. That is bookkeeping: discovery rewrites it on every pass
* (`updateRuntimes`), so falling back to it stamped every agent without a readable transcript "now"
- * — and a client sorting by recency put exactly those agents above the ones just used.
+ * — and a client sorting by recency put exactly those agents above the ones just used. File mtime is
+ * bookkeeping too: an idle transcript can be rewritten without a new conversation event.
*/
export async function lastActivityAt(s: RegisteredSession): Promise<number> {
- const st = s.transcriptPath ? await stat(s.transcriptPath).catch(() => null) : null
- return st?.mtimeMs ?? s.lastHookAt
+ return await transcriptActivityAt(s.transcriptPath, s.engine) ?? s.lastHookAt
}
function frameTitle(s: RegisteredSession): string | null {
@@ -137,7 +143,7 @@ function frameTitle(s: RegisteredSession): string | null {
*/
export async function agentFrame(
s: RegisteredSession,
- { selectedModel, terminalAvailable, dsh }: AgentFrameContext,
+ { selectedModel, terminalAvailable, dsh, tokenUsage }: AgentFrameContext,
): Promise<AgentFrame> {
return {
id: s.agentId,
@@ -149,6 +155,9 @@ export async function agentFrame(
launch: s.launch ?? { state: 'ready' },
createdAt: new Date(s.registeredAt).toISOString(),
updatedAt: new Date(await lastActivityAt(s)).toISOString(),
+ tokenUsage: tokenUsage?.totalTokens != null
+ ? { totalTokens: tokenUsage.totalTokens, updatedAt: tokenUsage.updatedAt } : null,
+ outputStats: tokenUsage?.output ? { ...tokenUsage.output, updatedAt: tokenUsage.updatedAt } : null,
tmuxPane: s.tmuxPane || null,
terminal: { available: terminalAvailable, primary: s.primaryRuntimeKey, runtimes: s.runtimes },
engine: s.engine,
diff --git a/cli/src/lib/agentOutputStats.spec.ts b/cli/src/lib/agentOutputStats.spec.ts
new file mode 100644
index 000000000..08c91829e
--- /dev/null
+++ b/cli/src/lib/agentOutputStats.spec.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest'
+import { emptyOutputLedger, ingestOutput, outputSnapshot, validOutputLedger } from './agentOutputStats.js'
+
+const call = (id: string, name: string, input: unknown) => ({ type: 'assistant', message: { content: [{ type: 'tool_use', id, name, input }] } })
+const reply = (id: string, content: string, receipt?: unknown, failed = false) => ({ type: 'user', toolUseResult: receipt,
+ message: { content: [{ type: 'tool_result', tool_use_id: id, content, is_error: failed }] } })
+const codex = (payload: Record<string, unknown>) => ({ type: 'response_item', payload })
+const patch = '*** Begin Patch\n*** Update File: a.ts\n@@\n-old\n+new\n+added\n*** End Patch'
+const url = 'https://github.com/team/project/pull/42'
+
+describe('cached output receipts', () => {
+ it('counts confirmed Claude edits once, including multi-match patches', () => {
+ const state = emptyOutputLedger()
+ for (let i = 0; i < 3; i++) {
+ ingestOutput(state, call('edit', 'Edit', {}), 'claude')
+ ingestOutput(state, reply('edit', 'Updated', { structuredPatch: [{ lines: [' context', '-old', '+new'] }, { lines: ['-old', '+new', '+added'] }] }), 'claude')
+ }
+ expect(outputSnapshot(state)).toEqual({ linesAdded: 3, linesRemoved: 2, pullRequestsCreated: null })
+ expect(validOutputLedger(JSON.parse(JSON.stringify(state)))).toBe(true)
+ expect(JSON.stringify(state)).not.toContain('context')
+ })
+
+ it('never counts failed, unfinished, read-only or unreported edits', () => {
+ const state = emptyOutputLedger()
+ for (const [id, name, fail] of [['failed', 'Edit', true], ['read', 'Read', false]] as const) {
+ ingestOutput(state, call(id, name, {}), 'claude')
+ ingestOutput(state, reply(id, 'Error', { structuredPatch: [{ lines: ['+x'] }] }, fail), 'claude')
+ }
+ ingestOutput(state, call('pending', 'Write', {}), 'claude')
+ ingestOutput(state, call('unknown', 'Edit', {}), 'claude')
+ ingestOutput(state, reply('unknown', 'Updated'), 'claude')
+ expect(outputSnapshot(state)).toBeNull()
+ })
+
+ it('counts new-file lines without a phantom trailing line', () => {
+ const state = emptyOutputLedger()
+ ingestOutput(state, call('new', 'Write', {}), 'claude')
+ ingestOutput(state, reply('new', 'Created', { type: 'create', content: 'a\nb\n' }), 'claude')
+ ingestOutput(state, call('overwrite', 'Write', {}), 'claude')
+ ingestOutput(state, reply('overwrite', 'Updated', { type: 'update', content: 'c\n' }), 'claude')
+ expect(outputSnapshot(state)?.linesAdded).toBe(2)
+ })
+
+ it('credits only PR creation receipts, not mentions, reads, errors or duplicates', () => {
+ const state = emptyOutputLedger()
+ for (const [id, command, output, failed] of [
+ ['one', 'gh pr create --title "hi" --body-file /tmp/body', url, false],
+ ['two', 'cd project && gh pr create --body-file /tmp/body', url, false],
+ ['view', 'gh pr view --json url', url, false],
+ ['echo', 'echo "gh pr create"', url, false],
+ ['masked', 'gh pr create || true', 'https://github.com/team/project/pull/45', false],
+ ['later', 'gh pr create; gh pr view', 'https://github.com/team/project/pull/46', false],
+ ['comment', '# gh pr create\necho hello', url, false],
+ ['heredoc', "cat <<'EOF'\ngh pr create\nEOF", url, false],
+ ['failed', 'gh pr create', 'https://github.com/team/project/pull/43', true],
+ ['mentioned', 'gh pr create', 'Already exists: https://github.com/team/project/pull/44', true],
+ ] as const) {
+ ingestOutput(state, call(id, 'Bash', { command }), 'claude')
+ ingestOutput(state, reply(id, output, undefined, failed), 'claude')
+ }
+ expect(outputSnapshot(state)).toEqual({ linesAdded: null, linesRemoved: null, pullRequestsCreated: 1 })
+ expect(JSON.stringify(state)).not.toContain('team/project')
+ })
+
+ it('counts Codex patches only after success and preserves pending work across reloads', () => {
+ let state = emptyOutputLedger()
+ ingestOutput(state, codex({ type: 'custom_tool_call', call_id: 'patch', name: 'apply_patch', input: patch }), 'codex')
+ state = JSON.parse(JSON.stringify(state))
+ const result = codex({ type: 'custom_tool_call_output', call_id: 'patch', output: 'Success. Updated the following files:\nM a.ts' })
+ ingestOutput(state, result, 'codex')
+ ingestOutput(state, result, 'codex')
+ ingestOutput(state, codex({ type: 'custom_tool_call', call_id: 'bad', name: 'apply_patch', input: patch }), 'codex')
+ ingestOutput(state, codex({ type: 'custom_tool_call_output', call_id: 'bad', output: 'Failed', is_error: true }), 'codex')
+ expect(outputSnapshot(state)).toEqual({ linesAdded: 2, linesRemoved: 1, pullRequestsCreated: null })
+ })
+
+ it('supports literal code-mode calls and structured receipts without executing JavaScript', () => {
+ const state = emptyOutputLedger()
+ ingestOutput(state, codex({ type: 'custom_tool_call', call_id: 'patch', name: 'exec', input: `text(await tools.apply_patch(${JSON.stringify(patch)}));` }), 'codex')
+ ingestOutput(state, codex({ type: 'custom_tool_call_output', call_id: 'patch', output: 'Success. Updated the following files:\nM a.ts' }), 'codex')
+ ingestOutput(state, codex({ type: 'custom_tool_call', call_id: 'pr', name: 'exec', input: 'text(await tools.exec_command({cmd:"gh pr create --body-file /tmp/body"}));' }), 'codex')
+ ingestOutput(state, codex({ type: 'custom_tool_call_output', call_id: 'pr', output: `Script completed\nWall time 1s\nOutput:\n${JSON.stringify({ output: url, exit_code: 0 })}` }), 'codex')
+ expect(outputSnapshot(state)).toEqual({ linesAdded: 2, linesRemoved: 1, pullRequestsCreated: 1 })
+ })
+
+ it('rejects process failures, dynamic/compound scripts and incomplete deletion patches', () => {
+ const state = emptyOutputLedger()
+ for (const [id, name, input, output] of [
+ ['bad', 'exec_command', JSON.stringify({ cmd: 'gh pr create' }), JSON.stringify({ exit_code: 1, output: url })],
+ ['bad2', 'exec_command', JSON.stringify({ cmd: 'gh pr create' }), `Process exited with code 1\n${url}`],
+ ['unfinished', 'exec_command', JSON.stringify({ cmd: 'gh pr create' }), JSON.stringify({ exit_code: null, session_id: 12, output: url })],
+ ['dynamic', 'exec', 'text(await tools.exec_command({cmd: command}));', url],
+ ['compound', 'exec', 'await tools.exec_command({cmd:"gh pr create"}); await tools.exec_command({cmd:"gh pr view"});', url],
+ ['delete', 'apply_patch', '*** Begin Patch\n*** Delete File: a\n*** End Patch', 'Success. Updated the following files:\nD a'],
+ ]) {
+ ingestOutput(state, codex({ type: 'function_call', call_id: id, name, arguments: input }), 'codex')
+ ingestOutput(state, codex({ type: 'function_call_output', call_id: id, output }), 'codex')
+ }
+ expect(outputSnapshot(state)).toBeNull()
+ })
+
+ it('keeps unknown distinct from measured zero and rejects corrupt checkpoints', () => {
+ const state = emptyOutputLedger()
+ expect(outputSnapshot(state)).toBeNull()
+ expect(validOutputLedger(state)).toBe(true)
+ expect(validOutputLedger({ ...state, added: -1 })).toBe(false)
+ expect(validOutputLedger({ ...state, completedCount: 500 })).toBe(false)
+ expect(validOutputLedger({ ...state, pending: { raw: { kind: 'edit' } } })).toBe(false)
+ })
+})
diff --git a/cli/src/lib/agentOutputStats.ts b/cli/src/lib/agentOutputStats.ts
new file mode 100644
index 000000000..f1f94d68d
--- /dev/null
+++ b/cli/src/lib/agentOutputStats.ts
@@ -0,0 +1,206 @@
+/** Output observed in this conversation's successful tool receipts. Pure: no Git, subprocesses,
+ * network, directory scans or polling. Collected during the existing incremental usage read.
+ * These are recorded edits, not a checkout diff; unreported work stays unknown. */
+import { createHash } from 'node:crypto'
+
+export type AgentOutputStats = {
+ linesAdded: number | null
+ linesRemoved: number | null
+ pullRequestsCreated: number | null
+}
+type Pending = { kind: 'edit' | 'pr' } | { kind: 'patch'; added: number; removed: number }
+export type OutputLedger = {
+ added: number; removed: number; edits: boolean; completedCount: number
+ prs: Record<string, true>; completed: Record<string, true>; pending: Record<string, Pending>
+}
+const object = (value: unknown): Record<string, unknown> | null =>
+ value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null
+const digest = (value: string) => createHash('sha256').update(value).digest('hex')
+const count = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
+const MAX_PENDING = 128
+const MAX_RECEIPTS = 20_000
+export const emptyOutputLedger = (): OutputLedger => ({ added: 0, removed: 0, edits: false, completedCount: 0, prs: {}, completed: {}, pending: {} })
+
+export function validOutputLedger(value: unknown): value is OutputLedger {
+ const row = object(value)
+ const map = (value: unknown, valid: (v: unknown) => boolean, limit: number) => {
+ const entries = object(value)
+ return entries && Object.keys(entries).length <= limit
+ && Object.entries(entries).every(([k, v]) => /^[a-f0-9]{64}$/.test(k) && valid(v))
+ }
+ return !!row && count(row.added) && count(row.removed) && typeof row.edits === 'boolean'
+ && !!map(row.prs, v => v === true, MAX_RECEIPTS)
+ && !!map(row.completed, v => v === true, MAX_RECEIPTS)
+ && row.completedCount === Object.keys(row.completed as object).length
+ && !!map(row.pending, v => {
+ const item = object(v)
+ return !!item && (item.kind === 'edit' || item.kind === 'pr'
+ || item.kind === 'patch' && count(item.added) && count(item.removed))
+ }, MAX_PENDING)
+}
+
+export function outputSnapshot(state: OutputLedger): AgentOutputStats | null {
+ const prs = Object.keys(state.prs).length
+ return state.edits || prs ? {
+ linesAdded: state.edits ? state.added : null, linesRemoved: state.edits ? state.removed : null,
+ pullRequestsCreated: prs || null,
+ } : null
+}
+
+function parse(value: unknown): unknown {
+ if (typeof value !== 'string') return value
+ try { return JSON.parse(value) } catch { return value }
+}
+function text(value: unknown): string {
+ if (typeof value === 'string') return value
+ if (Array.isArray(value)) return value.map(v => text(object(v)?.text)).join('\n')
+ return ''
+}
+
+/** Recognize a real shell command, never `echo "gh pr create"`, heredocs or comments. No execution. */
+function createsPr(command: string): boolean {
+ if (command.includes('<<') || command.includes('`') || command.includes('$(') || command.includes('||')) return false
+ const commands: string[][] = [[]]
+ let word = '', quote = '', escaped = false, comment = false
+ const flush = () => { if (word) { commands.at(-1)!.push(word); word = '' } }
+ for (const char of command) {
+ if (comment) { if (char !== '\n') continue; comment = false }
+ if (escaped) { word += char; escaped = false; continue }
+ if (char === '\\' && quote !== "'") { escaped = true; continue }
+ if (quote) { if (char === quote) quote = ''; else word += char; continue }
+ if (char === "'" || char === '"') { quote = char; continue }
+ if (char === '#' && !word) { comment = true; continue }
+ if (';&|\n'.includes(char)) { flush(); commands.push([]) }
+ else if (/\s/.test(char)) flush()
+ else word += char
+ }
+ flush()
+ if (quote || escaped) return false
+ const ran = commands.filter(words => words.length)
+ const last = ran.at(-1)
+ // Its result must be the command's result, not a later command masking a failed creation.
+ return last?.[0] === 'gh' && last[1] === 'pr' && last[2] === 'create'
+ && ran.filter(words => words[0] === 'gh' && words[1] === 'pr' && words[2] === 'create').length === 1
+}
+
+/** Extract one literal tools.* call from Codex code mode. Never evaluate model-written JavaScript.
+ * Compound/dynamic scripts stay unknown: their outputs cannot be attributed to one operation. */
+function unwrap(name: string, input: unknown): [string, unknown] {
+ if (name !== 'exec' || typeof input !== 'string') return [name, input]
+ const calls = [...input.matchAll(/\btools\.([a-zA-Z0-9_]+)\s*\(/g)]
+ if (calls.length !== 1) return [name, input]
+ const tool = calls[0][1]
+ const rest = input.slice(calls[0].index! + calls[0][0].length).trimStart()
+ if (tool === 'apply_patch') {
+ const literal = /^"(?:\\.|[^"\\])*"/.exec(rest)?.[0]
+ return literal ? [tool, parse(literal)] : [name, input]
+ }
+ if (tool === 'exec_command') {
+ const literal = /(?:\bcmd\b|"cmd")\s*:\s*("(?:\\.|[^"\\])*")/.exec(rest)?.[1]
+ if (literal) return [tool, { cmd: parse(literal) }]
+ }
+ return [name, input]
+}
+
+function patchCounts(patch: string): { added: number; removed: number } | null {
+ if (!patch.startsWith('*** Begin Patch\n') || !patch.trimEnd().endsWith('*** End Patch')) return null
+ // A deleted file's contents are absent from the patch; don't invent its removed-line count.
+ if (patch.includes('\n*** Delete File:')) return null
+ let added = 0, removed = 0
+ for (const line of patch.split('\n')) {
+ if (line.startsWith('+')) added++
+ else if (line.startsWith('-')) removed++
+ }
+ return { added, removed }
+}
+
+function start(state: OutputLedger, id: unknown, rawName: unknown, raw: unknown): void {
+ if (typeof id !== 'string' || typeof rawName !== 'string') return
+ const key = digest(id)
+ if (state.completed[key] || state.pending[key]) return
+ const [name, input] = unwrap(rawName.replace(/^functions\./, ''), parse(raw))
+ const args = object(input)
+ let pending: Pending | null = null
+ if (['Edit', 'Write', 'MultiEdit'].includes(name)) pending = { kind: 'edit' }
+ else if (name === 'apply_patch') {
+ const patch = typeof input === 'string' ? input : args?.patch ?? args?.input
+ const counts = typeof patch === 'string' ? patchCounts(patch) : null
+ if (counts) pending = { kind: 'patch', ...counts }
+ } else if (['Bash', 'exec_command', 'shell', 'local_shell', 'unified_exec'].includes(name)) {
+ const command = args?.command ?? args?.cmd
+ // shell's ["bash", "-lc", command] is safe to inspect when its shape is unambiguous.
+ const source = Array.isArray(command) && command.length === 3 && ['-c', '-lc'].includes(command[1])
+ ? command[2] : command
+ if (typeof source === 'string' && createsPr(source)) pending = { kind: 'pr' }
+ }
+ if (pending && Object.keys(state.pending).length < MAX_PENDING) state.pending[key] = pending
+}
+
+function finish(state: OutputLedger, id: unknown, rawOutput: unknown, failed: boolean, receipt?: unknown): void {
+ if (typeof id !== 'string') return
+ const key = digest(id), pending = state.pending[key]
+ if (!pending || state.completed[key]) return
+ delete state.pending[key]
+ if (state.completedCount >= MAX_RECEIPTS) return
+ state.completed[key] = true
+ state.completedCount++
+ let output = text(rawOutput)
+ const wrapped = /^Script completed[\s\S]*?\nOutput:\n([\s\S]+)$/.exec(output)
+ if (wrapped) output = wrapped[1]
+ const result = object(parse(output))
+ // The native exec result is structured on some versions, a textual wrapper on others.
+ if (result && typeof result.output === 'string') output = result.output
+ const native = object(receipt)
+ if (failed || result?.isError === true || native?.interrupted === true
+ || (result?.session_id != null && result.exit_code == null)
+ || (typeof result?.exit_code === 'number' && result.exit_code !== 0)
+ || /(?:Process exited with code|"exit_code"\s*:)\s*[1-9]\d*/.test(output)) return
+ if (pending.kind === 'pr') {
+ // `gh pr create` prints the created URL on its own line. Quotes, mentions, read/list output,
+ // errors and unrelated links never become productivity credit.
+ const urls = [...new Set(output.split('\n').map(s => s.trim()).filter(s =>
+ /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/[1-9]\d*$/.test(s)))]
+ if (urls.length === 1) state.prs[digest(urls[0].toLowerCase())] = true
+ return
+ }
+ let counts: { added: number; removed: number } | null = null
+ if (pending.kind === 'patch' && /(?:^|\n)Success\. Updated the following files:/m.test(output)) counts = pending
+ if (pending.kind === 'edit') {
+ const patches = native?.structuredPatch
+ if (Array.isArray(patches) && patches.length && patches.every(p => Array.isArray(object(p)?.lines))) {
+ counts = { added: 0, removed: 0 }
+ for (const patch of patches) for (const line of object(patch)!.lines as unknown[]) {
+ if (typeof line === 'string' && line.startsWith('+')) counts.added++
+ else if (typeof line === 'string' && line.startsWith('-')) counts.removed++
+ }
+ } else if (native?.type === 'create' && typeof native.content === 'string') {
+ const content = native.content
+ counts = { added: content ? content.split('\n').length - (content.endsWith('\n') ? 1 : 0) : 0, removed: 0 }
+ }
+ }
+ if (counts && Number.isSafeInteger(state.added + counts.added) && Number.isSafeInteger(state.removed + counts.removed)) {
+ state.added += counts.added; state.removed += counts.removed; state.edits = true
+ }
+}
+
+export function ingestOutput(state: OutputLedger, row: Record<string, unknown>, engine: string): void {
+ if (engine === 'claude') {
+ const content = object(row.message)?.content
+ if (!Array.isArray(content)) return
+ for (const value of content) {
+ const item = object(value)
+ if (!item) continue
+ if (row.type === 'assistant' && item.type === 'tool_use') start(state, item.id, item.name, item.input)
+ if (row.type === 'user' && item.type === 'tool_result')
+ finish(state, item.tool_use_id, item.content, item.is_error === true,
+ content.filter(v => object(v)?.type === 'tool_result').length === 1 ? row.toolUseResult : undefined)
+ }
+ } else if (engine === 'codex' && row.type === 'response_item') {
+ const item = object(row.payload)
+ if (!item) return
+ if (item.type === 'function_call' || item.type === 'custom_tool_call')
+ start(state, item.call_id ?? item.id, item.name, item.arguments ?? item.input)
+ else if (item.type === 'function_call_output' || item.type === 'custom_tool_call_output')
+ finish(state, item.call_id ?? item.id, item.output, item.is_error === true || item.status === 'failed')
+ }
+}
diff --git a/cli/src/lib/agentTokenUsage.spec.ts b/cli/src/lib/agentTokenUsage.spec.ts
new file mode 100644
index 000000000..3e7f2cfdc
--- /dev/null
+++ b/cli/src/lib/agentTokenUsage.spec.ts
@@ -0,0 +1,268 @@
+import { appendFile, mkdtemp, readFile, readdir, rename, rm, stat, utimes, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { AgentTokenUsageCache } from './agentTokenUsage.js'
+import type { RegisteredSession } from './registry.js'
+
+const at = '2026-09-22T16:00:00Z'
+const claude = (id: string, input = 100, output = 20, extra: Record<string, unknown> = {}) => JSON.stringify({
+ type: 'assistant', timestamp: at, sessionId: 'conversation', requestId: `req-${id}`,
+ message: { id, usage: { input_tokens: input, output_tokens: output, cache_read_input_tokens: 80,
+ cache_creation_input_tokens: 10, output_tokens_details: { thinking_tokens: 5 } } }, ...extra,
+}) + '\n'
+const codex = (input: number, output: number, last?: [number, number], timestamp = at) => JSON.stringify({
+ type: 'event_msg', timestamp, payload: { type: 'token_count', info: {
+ total_token_usage: { input_tokens: input, cached_input_tokens: Math.floor(input / 2), output_tokens: output, reasoning_output_tokens: Math.floor(output / 2) },
+ ...(last ? { last_token_usage: { input_tokens: last[0], cached_input_tokens: Math.floor(last[0] / 2), output_tokens: last[1], reasoning_output_tokens: Math.floor(last[1] / 2) } } : {}),
+ } },
+}) + '\n'
+
+describe('owning-machine token cache', () => {
+ let dir: string
+ let now: number
+ let bytes: number
+ let store: AgentTokenUsageCache
+ let target: Pick<RegisteredSession, 'agentId' | 'sessionId' | 'engine' | 'transcriptPath' | 'registeredAt'>
+ const read = async () => { store.changed(target); await store.settled(); return store.get(target) }
+ beforeEach(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'harness-token-test-'))
+ now = Date.parse('2026-09-23T00:00:00Z')
+ bytes = 0
+ target = { agentId: 'harness', sessionId: 'conversation', engine: 'claude', transcriptPath: join(dir, 'transcript.jsonl'), registeredAt: 1 }
+ store = new AgentTokenUsageCache(join(dir, 'cache'), { now: () => now, onRead: n => { bytes += n } })
+ })
+ afterEach(async () => { store.dispose(); await store.settled(); vi.useRealTimers(); await rm(dir, { recursive: true, force: true }) })
+
+ it('coalesces activity bursts, captures their final usage, and does not poll idle harnesses', async () => {
+ await writeFile(target.transcriptPath!, claude('one'))
+ await read()
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ await appendFile(target.transcriptPath!, claude('two'))
+ for (let i = 0; i < 100; i++) store.changed(target)
+ expect(vi.getTimerCount()).toBe(1)
+ now += 15_000
+ await vi.advanceTimersByTimeAsync(15_000)
+ await store.settled()
+ expect(store.get(target)?.totalTokens).toBe(420)
+ const reads = bytes
+ await vi.advanceTimersByTimeAsync(60_000)
+ await store.settled()
+ expect(bytes).toBe(reads)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('snapshots queued identity so a rebind cannot write another conversation’s usage into its cache', async () => {
+ await writeFile(target.transcriptPath!, claude('one'))
+ const original = { ...target }
+ store.get(target)
+ target.sessionId = 'replacement-conversation'
+ target.transcriptPath = '/missing/replacement.jsonl'
+ await store.settled()
+ expect(store.get(original)?.totalTokens).toBe(210)
+ expect(store.get(target)).toBeNull()
+ })
+
+ it('keeps 200-harness repeated display lookups free of transcript reads', async () => {
+ const targets = Array.from({ length: 200 }, (_, i) => ({ ...target, agentId: `harness-${i}`,
+ transcriptPath: join(dir, `harness-${i}.jsonl`) }))
+ await Promise.all(targets.map(s => writeFile(s.transcriptPath!, claude('one'))))
+ for (const s of targets) store.get(s)
+ await store.settled()
+ const reads = bytes
+ now += 3_600_000 // A warm display never schedules work, even after a long idle.
+ const start = performance.now()
+ for (let round = 0; round < 50; round++) {
+ for (const s of targets) expect(store.get(s)?.totalTokens).toBe(210)
+ }
+ const elapsed = performance.now() - start
+ await store.settled()
+ expect(bytes).toBe(reads)
+ console.log(`200 harnesses × 50 cached lookups: ${elapsed.toFixed(1)} ms including assertions; 0 transcript bytes read`)
+ })
+
+ it('returns immediately while cold, merges streaming repeats, and counts cache/reasoning once', async () => {
+ await writeFile(target.transcriptPath!, claude('one', 100, 10) + claude('one') + claude('two'))
+ const changed = vi.fn()
+ store.onChanged = changed
+ expect(store.get(target)).toBeNull()
+ expect((await read())?.totalTokens).toBe(420)
+ expect(changed).toHaveBeenCalledTimes(1)
+ const reads = bytes
+ for (let i = 0; i < 1000; i++) expect(store.get(target)?.totalTokens).toBe(420)
+ await store.settled()
+ expect(bytes).toBe(reads)
+ now += 30_000
+ await read()
+ expect(bytes).toBe(reads)
+ })
+
+ it('reads only appended bytes plus a bounded checkpoint, and survives pause/resume and daemon restart', async () => {
+ await writeFile(target.transcriptPath!, JSON.stringify({ type: 'user', text: 'x'.repeat(250_000) }) + '\n' + claude('one'))
+ expect((await read())?.totalTokens).toBe(210)
+ const oldBytes = bytes
+ now += 30_000
+ await appendFile(target.transcriptPath!, claude('one') + claude('two'))
+ expect((await read())?.totalTokens).toBe(420)
+ expect(bytes - oldBytes).toBeLessThan(2048)
+ const cacheFile = join(dir, 'cache', (await readdir(join(dir, 'cache')))[0])
+ const checkpoint = await readFile(cacheFile, 'utf8')
+ expect(checkpoint).not.toContain('x'.repeat(100))
+ expect(checkpoint).not.toContain('req-one')
+ expect((await stat(cacheFile)).mode & 0o777).toBe(0o600)
+ store.dispose()
+ store = new AgentTokenUsageCache(join(dir, 'cache'), { now: () => now, onRead: n => { bytes += n } })
+ const restartedBytes = bytes
+ expect((await read())?.totalTokens).toBe(420)
+ expect(bytes).toBe(restartedBytes)
+ now += 30_000
+ await appendFile(target.transcriptPath!, claude('three'))
+ expect((await read())?.totalTokens).toBe(630)
+ })
+
+ it('waits for a complete JSONL record without double counting its prefix', async () => {
+ const line = claude('two')
+ await writeFile(target.transcriptPath!, claude('one') + line.slice(0, 100))
+ expect((await read())?.totalTokens).toBe(210)
+ now += 30_000
+ await appendFile(target.transcriptPath!, line.slice(100))
+ expect((await read())?.totalTokens).toBe(420)
+ })
+
+ it('rebuilds after truncation, replacement, and same-size rewrites', async () => {
+ await writeFile(target.transcriptPath!, claude('one') + claude('two'))
+ expect((await read())?.totalTokens).toBe(420)
+ now += 30_000
+ await writeFile(target.transcriptPath!, claude('new'))
+ expect((await read())?.totalTokens).toBe(210)
+ now += 30_000
+ await writeFile(join(dir, 'replacement'), claude('new', 200))
+ await rename(join(dir, 'replacement'), target.transcriptPath!)
+ expect((await read())?.totalTokens).toBe(310)
+ now += 30_000
+ await writeFile(target.transcriptPath!, claude('new', 300))
+ await utimes(target.transcriptPath!, now / 1000, now / 1000)
+ expect((await read())?.totalTokens).toBe(410)
+ })
+
+ it('never borrows another conversation, profile, or machine cache', async () => {
+ await writeFile(target.transcriptPath!, claude('one'))
+ expect((await read())?.totalTokens).toBe(210)
+ expect(store.get({ ...target, sessionId: 'another' })).toBeNull()
+ expect(store.get({ ...target, engine: 'codex', codexHome: '/different-profile' })).toBeNull()
+ const remote = new AgentTokenUsageCache(join(dir, 'other-machine-cache'))
+ expect(remote.get({ ...target, transcriptPath: '/missing/on/this/machine' })).toBeNull()
+ await remote.settled()
+ remote.dispose()
+ })
+
+ it('hides unavailable or unsupported usage rather than making up zero', async () => {
+ expect(await read()).toBeNull()
+ expect(store.get({ ...target, engine: 'hermes' })).toBeNull()
+ now += 30_000
+ await writeFile(target.transcriptPath!, '{"type":"user"}\n')
+ expect(await read()).toBeNull()
+ now += 30_000
+ await appendFile(target.transcriptPath!, '{"type":"assistant","message":{"usage":{}}}\n')
+ expect(await read()).toBeNull()
+ })
+
+ it('keeps a previously measured total when the original transcript is unavailable', async () => {
+ await writeFile(target.transcriptPath!, claude('one'))
+ await read()
+ await rm(target.transcriptPath!)
+ now += 30_000
+ expect((await read())?.totalTokens).toBe(210)
+ })
+
+ it('drops invalidated measurements after a readable transcript is replaced with unreported data', async () => {
+ await writeFile(target.transcriptPath!, claude('one'))
+ expect((await read())?.totalTokens).toBe(210)
+ now += 30_000
+ await writeFile(target.transcriptPath!, '{"type":"user","message":"New empty history"}\n')
+ expect(await read()).toBeNull()
+ })
+
+ it('omits inherited fork history but includes the fork’s own usage', async () => {
+ const fork = { ...target, forkedFrom: { agentId: 'parent', name: 'Parent' }, registeredAt: Date.parse(at) + 1000 }
+ await writeFile(target.transcriptPath!, claude('old') + claude('new', 100, 20, { timestamp: '2026-09-22T17:00:00Z' }))
+ store.get(fork)
+ await store.settled()
+ expect(store.get(fork)?.totalTokens).toBe(210)
+ })
+
+ it('recovers a malformed disk checkpoint without affecting the harness', async () => {
+ await writeFile(target.transcriptPath!, claude('one'))
+ await read()
+ const file = join(dir, 'cache', (await readdir(join(dir, 'cache')))[0])
+ await writeFile(file, '{broken')
+ store.dispose()
+ store = new AgentTokenUsageCache(join(dir, 'cache'), { now: () => now })
+ expect((await read())?.totalTokens).toBe(210)
+ })
+
+ it('counts Codex deltas, excludes rate-limit-only updates and repeated records', async () => {
+ target.engine = 'codex'
+ await writeFile(target.transcriptPath!, codex(100, 20) + codex(200, 50, [100, 30])
+ + codex(200, 50, [100, 30]) + JSON.stringify({ type: 'event_msg', payload: { type: 'token_count', info: null } }) + '\n')
+ expect((await read())?.totalTokens).toBe(250)
+ now += 30_000
+ await appendFile(target.transcriptPath!, codex(300, 80, [100, 30], '2026-09-22T16:02:00Z'))
+ expect((await read())?.totalTokens).toBe(380)
+ })
+
+ it('handles Codex counter resets and stale regressions without rebilling history', async () => {
+ target.engine = 'codex'
+ await writeFile(target.transcriptPath!, codex(1000, 100) + codex(990, 99, [10, 1])
+ + codex(10, 1) + codex(110, 11, [100, 10]))
+ expect((await read())?.totalTokens).toBe(1210)
+ })
+
+ it('reads one OpenCode aggregate by session id and includes reasoning once', async () => {
+ const query = vi.fn().mockResolvedValue({ ok: true, via: 'builtin', rows: [{
+ tokens_input: 100, tokens_output: 20, tokens_reasoning: 5, tokens_cache_read: 80, tokens_cache_write: 10,
+ }] })
+ store.dispose()
+ store = new AgentTokenUsageCache(join(dir, 'cache'), { readSqlite: query, now: () => now })
+ target.engine = 'opencode'
+ target.transcriptPath = null
+ expect((await read())?.totalTokens).toBe(215)
+ expect(query).toHaveBeenCalledTimes(1)
+ expect(query.mock.calls[0][2]).toEqual(['conversation'])
+ expect(query.mock.calls[0][1]).toContain('WHERE id = ?')
+ now += 3_600_000
+ for (let i = 0; i < 1000; i++) store.get(target)
+ await store.settled()
+ expect(query).toHaveBeenCalledTimes(1)
+ })
+
+ it('collects output in the same incremental pass, persists it, and does not credit inherited work', async () => {
+ const receipt = (id: string, timestamp = at) => [
+ { type: 'assistant', timestamp, sessionId: 'conversation', message: { content: [{ type: 'tool_use', id, name: 'Bash', input: { command: 'gh pr create --body-file /tmp/body' } }] } },
+ { type: 'user', timestamp, sessionId: 'conversation', message: { content: [{ type: 'tool_result', tool_use_id: id, content: 'https://github.com/team/project/pull/42' }] } },
+ ].map(v => JSON.stringify(v) + '\n').join('')
+ await writeFile(target.transcriptPath!, receipt('old') + claude('usage'))
+ expect((await read())?.output?.pullRequestsCreated).toBe(1)
+ const before = bytes
+ now += 3_600_000
+ for (let i = 0; i < 1000; i++) store.get(target)
+ await store.settled()
+ expect(bytes).toBe(before)
+ store.dispose()
+ store = new AgentTokenUsageCache(join(dir, 'cache'), { now: () => now, onRead: n => { bytes += n } })
+ expect((await read())?.output?.pullRequestsCreated).toBe(1)
+ expect(bytes).toBe(before)
+ const fork = { ...target, forkedFrom: { agentId: 'parent', name: 'Parent' }, registeredAt: Date.parse(at) + 1000 }
+ store.get(fork)
+ await store.settled()
+ expect(store.get(fork)).toBeNull()
+ })
+
+ it('publishes recorded output even when token usage is unreported', async () => {
+ await writeFile(target.transcriptPath!, [
+ { type: 'assistant', message: { content: [{ type: 'tool_use', id: 'edit', name: 'Write', input: {} }] } },
+ { type: 'user', toolUseResult: { type: 'create', content: 'line\n' }, message: { content: [{ type: 'tool_result', tool_use_id: 'edit', content: 'Created' }] } },
+ ].map(v => JSON.stringify(v) + '\n').join(''))
+ expect(await read()).toMatchObject({ totalTokens: null, output: { linesAdded: 1, linesRemoved: 0, pullRequestsCreated: null } })
+ })
+})
diff --git a/cli/src/lib/agentTokenUsage.ts b/cli/src/lib/agentTokenUsage.ts
new file mode 100644
index 000000000..82a621a6d
--- /dev/null
+++ b/cli/src/lib/agentTokenUsage.ts
@@ -0,0 +1,322 @@
+/** Per-conversation token totals, computed on the owning machine. No Git or vendor requests.
+ * Frames read a tiny in-memory snapshot; a bounded background queue maintains private checkpoints.
+ * JSONL is scanned once, then only appended bytes are read. Nothing walks transcript directories. */
+import { createHash, randomUUID } from 'node:crypto'
+import { mkdir, open, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { env } from '../config/env.js'
+import type { RegisteredSession } from './registry.js'
+import { sqliteReadAll } from './sqliteRead.js'
+import { emptyOutputLedger, ingestOutput, outputSnapshot, validOutputLedger, type AgentOutputStats, type OutputLedger } from './agentOutputStats.js'
+
+export type AgentTokenUsage = { totalTokens: number | null; updatedAt: string; output?: AgentOutputStats }
+type Target = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath' | 'codexHome' | 'agentId' | 'forkedFrom' | 'registeredAt'>
+type Buckets = [number, number, number, number]
+type CodexTotals = [number, number, number, number]
+type Checkpoint = {
+ version: 2; key: string; offset: number; size: number; mtime: number; inode: string;
+ boundary: string; total: number; observed: boolean; updatedAt: string | null;
+ claude: Record<string, Buckets>; codex: CodexTotals | null; seen: Record<string, true>;
+ output: OutputLedger;
+}
+type Entry = {
+ target: Target; value: AgentTokenUsage | null; checked: number; pending: Promise<void> | null;
+ fingerprint?: string;
+ dirty?: boolean;
+ timer?: NodeJS.Timeout;
+}
+const REFRESH_MS = 15_000
+const MAX_CACHE_BYTES = 8 * 1024 * 1024
+const MAX_TRANSCRIPT_BYTES = 128 * 1024 * 1024
+const MAX_LINE_BYTES = 8 * 1024 * 1024
+const MAX_ENTRIES = 512
+const hash = (value: string | Buffer) => createHash('sha256').update(value).digest('hex')
+const object = (value: unknown): Record<string, unknown> | null =>
+ value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null
+const tokens = (value: unknown): number => typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : 0
+const sum = (values: number[]) => values.reduce((a, b) => a + b, 0)
+
+function keyFor(s: Target): string | null {
+ if (!s.sessionId || !['claude', 'codex', 'opencode'].includes(s.engine)) return null
+ if (s.engine !== 'opencode' && !s.transcriptPath) return null
+ return hash(JSON.stringify([s.engine, s.codexHome ?? '', s.sessionId, s.transcriptPath,
+ s.forkedFrom ? s.registeredAt : null]))
+}
+function targetSnapshot(s: Target): Target {
+ return { agentId: s.agentId, sessionId: s.sessionId, engine: s.engine, transcriptPath: s.transcriptPath,
+ codexHome: s.codexHome, registeredAt: s.registeredAt, forkedFrom: s.forkedFrom ? { ...s.forkedFrom } : null }
+}
+function empty(key: string): Checkpoint {
+ return { version: 2, key, offset: 0, size: 0, mtime: 0, inode: '', boundary: '', total: 0,
+ observed: false, updatedAt: null, claude: {}, codex: null, seen: {}, output: emptyOutputLedger() }
+}
+function rawCodex(value: unknown): CodexTotals | null {
+ const row = object(value)
+ return row && ['input_tokens', 'output_tokens', 'cached_input_tokens'].some(key => typeof row[key] === 'number')
+ ? [tokens(row.input_tokens), tokens(row.cached_input_tokens ?? row.cache_read_input_tokens),
+ tokens(row.output_tokens), tokens(row.reasoning_output_tokens)] : null
+}
+
+/** Same counting rules as the desktop usage ledger: cached input is included once, reasoning is
+ * already inside output, Claude streaming repeats merge, and Codex cumulative snapshots are deltas. */
+function ingest(state: Checkpoint, line: string, target: Target): void {
+ if (!line.includes(target.engine === 'claude' ? '"usage"' : '"token_count"')
+ && !line.includes('"tool_use"') && !line.includes('"tool_result"') && !line.includes('"response_item"')) return
+ const row = object(JSON.parse(line))
+ if (!row) return
+ // Forks carry old messages into a new conversation. Only work after the fork belongs to it.
+ if (target.forkedFrom && (typeof row.timestamp !== 'string' || !Number.isFinite(Date.parse(row.timestamp))
+ || Date.parse(row.timestamp) < target.registeredAt)) return
+ if (target.engine === 'claude' && typeof row.sessionId === 'string' && row.sessionId !== target.sessionId) return
+ ingestOutput(state.output, row, target.engine)
+ if (target.engine === 'claude') {
+ if (row.type !== 'assistant') return
+ if (typeof row.sessionId === 'string' && row.sessionId !== target.sessionId) return
+ const message = object(row.message)
+ const usage = object(message?.usage)
+ if (!usage || !['input_tokens', 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens']
+ .some(key => typeof usage[key] === 'number')) return
+ const next: Buckets = [tokens(usage.input_tokens), tokens(usage.output_tokens),
+ tokens(usage.cache_read_input_tokens), tokens(usage.cache_creation_input_tokens)]
+ const id = typeof message?.id === 'string' && message.id
+ ? `${message.id}:${typeof row.requestId === 'string' ? row.requestId : ''}`
+ : typeof row.uuid === 'string' ? row.uuid : line
+ const key = hash(id)
+ const old = state.claude[key] ?? [0, 0, 0, 0]
+ const merged = next.map((value, i) => Math.max(value, old[i])) as Buckets
+ state.claude[key] = merged
+ state.total += sum(merged) - sum(old)
+ state.observed = true
+ } else {
+ const payload = object(row.payload)
+ const info = object(payload?.info)
+ if (row.type !== 'event_msg' || payload?.type !== 'token_count' || !info) return
+ const total = rawCodex(info.total_token_usage)
+ const last = rawCodex(info.last_token_usage)
+ if (!total && !last) return
+ const id = hash(JSON.stringify([row.timestamp, total, last]))
+ if (state.seen[id]) return
+ state.seen[id] = true
+ const previous = state.codex
+ let delta: CodexTotals | null = null
+ if (total && previous) {
+ if (total.every((n, i) => n === previous[i])) return
+ const regressed = total.some((n, i) => n < previous[i])
+ if (regressed && last && (sum(total) * 100 >= sum(previous) * 98 || sum(total) + sum(last) * 2 >= sum(previous))) return
+ delta = last ?? (regressed ? null : total.map((n, i) => Math.max(0, n - previous[i])) as CodexTotals)
+ } else delta = last ?? total
+ state.codex = total ?? (last && previous ? previous.map((n, i) => n + last[i]) as CodexTotals : null)
+ if (delta) {
+ // Codex input includes cache reads; output includes reasoning.
+ state.total += Math.max(delta[0], delta[1]) + delta[2]
+ state.observed = true
+ }
+ }
+ if (!Number.isSafeInteger(state.total)) throw new Error('Token total exceeds safe precision')
+}
+
+export class AgentTokenUsageCache {
+ private entries = new Map<string, Entry>()
+ private queue: Promise<void> = Promise.resolve()
+ private disposed = false
+ onChanged?: (target: Target) => void
+ constructor(private readonly directory: string, private readonly options: {
+ now?: () => number; refreshMs?: number; opencodeDb?: string;
+ readSqlite?: typeof sqliteReadAll;
+ onRead?: (bytes: number) => void;
+ } = {}) {}
+
+ /** Synchronous cache lookup. A cold or unsupported count is unknown, never invented as zero. */
+ get(target: Target): AgentTokenUsage | null {
+ if (this.disposed) return null
+ const key = keyFor(target)
+ if (!key) return null
+ let entry = this.entries.get(key)
+ if (!entry) {
+ if (this.entries.size >= MAX_ENTRIES) {
+ const oldest = [...this.entries].find(([, entry]) => !entry.pending && !entry.timer)
+ if (!oldest) return null
+ this.entries.delete(oldest[0])
+ }
+ entry = { target: targetSnapshot(target), value: null, checked: -Infinity, pending: null }
+ this.entries.set(key, entry)
+ this.schedule(key, entry)
+ }
+ entry.target = targetSnapshot(target)
+ // Once hydrated, frames only read memory. Existing transcript events drive refreshes;
+ // opening the monitor or an idle roster poll must not rescan files or query SQLite.
+ return entry.value
+ }
+
+ /** Called by existing transcript events; coalesces a burst into one refresh, including its end.
+ * No recurring timer, directory watcher, or refresh loop is added for idle harnesses. */
+ changed(target: Target): void {
+ if (this.disposed) return
+ this.get(target)
+ const key = keyFor(target)
+ const entry = key && this.entries.get(key)
+ if (!entry || entry.timer) return
+ if (this.now() - entry.checked >= (this.options.refreshMs ?? REFRESH_MS)) {
+ this.schedule(key!, entry)
+ return
+ }
+ const delay = Math.max(500, (this.options.refreshMs ?? REFRESH_MS) - (this.now() - entry.checked))
+ entry.timer = setTimeout(() => {
+ entry.timer = undefined
+ this.schedule(key!, entry)
+ }, delay)
+ entry.timer.unref()
+ }
+
+ /** Useful for a clean shutdown and isolated integration tests. Never awaited by a list frame. */
+ async settled(): Promise<void> { await this.queue }
+ dispose(): void {
+ this.disposed = true
+ for (const entry of this.entries.values()) if (entry.timer) clearTimeout(entry.timer)
+ this.onChanged = undefined
+ }
+ private now(): number { return this.options.now?.() ?? Date.now() }
+ private schedule(key: string, entry: Entry): void {
+ if (this.disposed) return
+ if (entry.pending) { entry.dirty = true; return }
+ const task = this.queue.then(async () => {
+ if (this.disposed) return
+ entry.dirty = false
+ entry.checked = this.now()
+ try { await this.refresh(key, entry) } catch { /* An unreadable usage file must never affect a harness. */ }
+ })
+ entry.pending = task
+ this.queue = task.finally(() => {
+ entry.pending = null
+ if (entry.dirty) this.changed(entry.target)
+ })
+ }
+ private publish(entry: Entry, state: Checkpoint): void {
+ const output = outputSnapshot(state.output)
+ if (!state.updatedAt) return
+ const previous = entry.value
+ if (!state.observed && !output) {
+ entry.value = null
+ if (previous) this.onChanged?.(entry.target)
+ return
+ }
+ entry.value = { totalTokens: state.observed ? state.total : null, updatedAt: state.updatedAt,
+ ...(output ? { output } : {}) }
+ if (previous?.totalTokens !== entry.value.totalTokens
+ || JSON.stringify(previous?.output) !== JSON.stringify(output ?? undefined)) this.onChanged?.(entry.target)
+ }
+ private async load(key: string): Promise<Checkpoint> {
+ try {
+ const file = join(this.directory, `${key}.json`)
+ if ((await stat(file)).size > MAX_CACHE_BYTES) return empty(key)
+ const raw = JSON.parse(await readFile(file, 'utf8')) as Checkpoint
+ if (raw.version === 2 && raw.key === key && Number.isSafeInteger(raw.total) && raw.total >= 0
+ && typeof raw.observed === 'boolean'
+ && (raw.updatedAt === null || typeof raw.updatedAt === 'string' && Number.isFinite(Date.parse(raw.updatedAt)))
+ && Number.isSafeInteger(raw.size) && raw.size >= 0 && Number.isFinite(raw.mtime)
+ && Number.isSafeInteger(raw.offset) && raw.offset >= 0 && raw.offset <= raw.size
+ && typeof raw.inode === 'string' && typeof raw.boundary === 'string'
+ && object(raw.claude) && Object.values(raw.claude).every(validBuckets)
+ && object(raw.seen) && Object.values(raw.seen).every(value => value === true)
+ && (raw.codex === null || validBuckets(raw.codex)) && validOutputLedger(raw.output)) return raw
+ } catch { /* First run, corrupt cache, or removed cache: rebuild from the trusted transcript. */ }
+ return empty(key)
+ }
+ private async save(key: string, state: Checkpoint): Promise<void> {
+ const bytes = JSON.stringify(state)
+ if (Buffer.byteLength(bytes) > MAX_CACHE_BYTES) throw new Error('Usage checkpoint is too large')
+ await mkdir(this.directory, { recursive: true, mode: 0o700 })
+ const file = join(this.directory, `${key}.json`)
+ const temporary = `${file}.${randomUUID()}.tmp`
+ try {
+ await writeFile(temporary, bytes, { mode: 0o600, flag: 'wx' })
+ await rename(temporary, file)
+ } finally { await unlink(temporary).catch(() => {}) }
+ }
+ private async refresh(key: string, entry: Entry): Promise<void> {
+ let nextFingerprint: string | undefined
+ // Warm, unchanged transcripts need one stat, no checkpoint or transcript reads.
+ if (entry.fingerprint && entry.target.transcriptPath) {
+ const info = await stat(entry.target.transcriptPath).catch(() => null)
+ if (info && entry.fingerprint === `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`) return
+ }
+ let state = await this.load(key)
+ this.publish(entry, state)
+ if (entry.target.engine === 'opencode') {
+ const read = this.options.readSqlite ?? sqliteReadAll
+ const database = this.options.opencodeDb ?? join(env.OPENCODE_DATA_DIR, 'opencode.db')
+ const limits = { busyTimeoutMs: 20, cliTimeoutMs: 1000, maxBuffer: 4096 }
+ let result = await read(database,
+ 'SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?',
+ [entry.target.sessionId], limits)
+ if (!result.ok) result = await read(database,
+ 'SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, 0 AS tokens_cache_write FROM session WHERE id = ?',
+ [entry.target.sessionId], limits)
+ if (!result.ok || result.rows.length !== 1) return
+ const row = result.rows[0]
+ if (!['tokens_input', 'tokens_output', 'tokens_reasoning', 'tokens_cache_read', 'tokens_cache_write']
+ .every(key => typeof row[key] === 'number' && Number.isSafeInteger(row[key]) && Number(row[key]) >= 0)) return
+ state.total = sum(Object.values(row).map(tokens))
+ state.observed = true
+ } else {
+ const path = entry.target.transcriptPath!
+ const file = await open(path, 'r')
+ try {
+ const info = await file.stat()
+ if (!info.isFile() || info.size > MAX_TRANSCRIPT_BYTES) return
+ const inode = `${info.dev}:${info.ino}`
+ const fingerprint = `${inode}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`
+ if (state.inode === inode && state.size === info.size && state.mtime === info.mtimeMs) {
+ entry.fingerprint = fingerprint
+ return
+ }
+ const boundary = async (offset: number) => {
+ const length = Math.min(256, offset)
+ const buffer = Buffer.alloc(length)
+ const { bytesRead } = await file.read(buffer, 0, length, offset - length)
+ this.options.onRead?.(bytesRead)
+ return hash(buffer.subarray(0, bytesRead))
+ }
+ if (state.inode !== inode || info.size < state.size || (info.size === state.size && info.mtimeMs !== state.mtime)
+ || state.offset > 0 && await boundary(state.offset) !== state.boundary) state = empty(key)
+ let offset = state.offset
+ let partial = Buffer.alloc(0)
+ while (offset < info.size) {
+ const buffer = Buffer.alloc(Math.min(64 * 1024, info.size - offset))
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, offset)
+ if (!bytesRead) throw new Error('Transcript changed during usage read')
+ this.options.onRead?.(bytesRead)
+ offset += bytesRead
+ const chunk = Buffer.concat([partial, buffer.subarray(0, bytesRead)])
+ let start = 0
+ for (let end = chunk.indexOf(10); end !== -1; end = chunk.indexOf(10, start)) {
+ const line = chunk.subarray(start, end).toString('utf8')
+ if (line.length) ingest(state, line, entry.target)
+ start = end + 1
+ }
+ partial = chunk.subarray(start)
+ if (partial.length > MAX_LINE_BYTES) throw new Error('Transcript record too large')
+ // File I/O yields between chunks; only one transcript backfill runs at once.
+ }
+ state.offset = offset - partial.length
+ state.size = info.size
+ state.inode = inode
+ state.mtime = info.mtimeMs
+ state.boundary = await boundary(state.offset)
+ nextFingerprint = fingerprint
+ } finally { await file.close() }
+ }
+ if (!Number.isSafeInteger(state.total)) return
+ state.updatedAt = new Date(this.now()).toISOString()
+ await this.save(key, state)
+ entry.fingerprint = nextFingerprint
+ this.publish(entry, state)
+ }
+}
+
+function validBuckets(value: unknown): value is Buckets {
+ return Array.isArray(value) && value.length === 4
+ && value.every(n => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0)
+}
+
+export const agentTokenUsage = new AgentTokenUsageCache(join(env.ADAPTER_DATA_DIR, 'agent-token-usage'))
diff --git a/cli/src/lib/transcriptActivity.spec.ts b/cli/src/lib/transcriptActivity.spec.ts
new file mode 100644
index 000000000..f2ee274f0
--- /dev/null
+++ b/cli/src/lib/transcriptActivity.spec.ts
@@ -0,0 +1,66 @@
+import { appendFile, mkdtemp, rename, rm, utimes, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it } from 'vitest'
+import { transcriptActivityAt } from './transcriptActivity.js'
+
+let dir: string
+let file: string
+const work = '2026-09-22T16:11:03.605Z'
+const metadata = '2026-09-23T01:04:42.169Z'
+const line = (row: unknown) => JSON.stringify(row) + '\n'
+beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'transcript-activity-')); file = join(dir, 'history.jsonl') })
+afterEach(async () => { await rm(dir, { recursive: true, force: true }) })
+
+it('ignores a fresh file mtime and bookkeeping events on a long-idle Claude harness', async () => {
+ await writeFile(file, line({ type: 'assistant', timestamp: work })
+ + line({ type: 'ai-title', timestamp: metadata }) + line({ type: 'permission-mode', timestamp: metadata }))
+ await utimes(file, new Date(metadata), new Date(metadata))
+ expect(await transcriptActivityAt(file, 'claude')).toBe(Date.parse(work))
+ await appendFile(file, line({ type: 'mode', timestamp: metadata }))
+ expect(await transcriptActivityAt(file, 'claude')).toBe(Date.parse(work))
+})
+
+it('crosses chunk boundaries and large metadata records without inventing recent work', async () => {
+ await writeFile(file, line({ type: 'user', timestamp: work, text: 'old work' })
+ + line({ type: 'ai-title', timestamp: metadata, padding: 'x'.repeat(180_000) }))
+ expect(await transcriptActivityAt(file, 'claude')).toBe(Date.parse(work))
+})
+
+it('advances for real work and turn completion, and tolerates unfinished final JSON', async () => {
+ await writeFile(file, line({ type: 'assistant', timestamp: work }) + '{"type":"assistant",')
+ expect(await transcriptActivityAt(file, 'claude')).toBe(Date.parse(work))
+ await appendFile(file, `"timestamp":"${metadata}"}\n`)
+ expect(await transcriptActivityAt(file, 'claude')).toBe(Date.parse(metadata))
+ await appendFile(file, line({ type: 'system', subtype: 'turn_duration', timestamp: '2026-09-23T01:05:00Z' }))
+ expect(await transcriptActivityAt(file, 'claude')).toBe(Date.parse('2026-09-23T01:05:00Z'))
+})
+
+it('uses Codex messages and tool activity, not context or rate-limit snapshots', async () => {
+ await writeFile(file, line({ type: 'response_item', timestamp: work, payload: { type: 'function_call' } })
+ + line({ type: 'turn_context', timestamp: metadata })
+ + line({ type: 'event_msg', timestamp: metadata, payload: { type: 'token_count', info: null } }))
+ expect(await transcriptActivityAt(file, 'codex')).toBe(Date.parse(work))
+ await appendFile(file, line({ type: 'event_msg', timestamp: metadata, payload: { type: 'item_completed', item: { type: 'AgentMessage' } } }))
+ expect(await transcriptActivityAt(file, 'codex')).toBe(Date.parse(metadata))
+})
+
+it('invalidates cached activity after truncation or file replacement', async () => {
+ await writeFile(file, line({ type: 'assistant', timestamp: metadata }))
+ expect(await transcriptActivityAt(file, 'claude')).toBe(Date.parse(metadata))
+ await writeFile(file, '{}\n')
+ expect(await transcriptActivityAt(file, 'claude')).toBeNull()
+ await writeFile(join(dir, 'replacement'), line({ type: 'user', timestamp: work }))
+ await rename(join(dir, 'replacement'), file)
+ expect(await transcriptActivityAt(file, 'claude')).toBe(Date.parse(work))
+})
+
+it('returns unknown for missing, unsupported, malformed, or unbounded metadata-only histories', async () => {
+ expect(await transcriptActivityAt(file, 'claude')).toBeNull()
+ await writeFile(file, line({ type: 'assistant', timestamp: 'invalid' }) + 'bad\n')
+ expect(await transcriptActivityAt(file, 'claude')).toBeNull()
+ expect(await transcriptActivityAt(file, 'opencode')).toBeNull()
+ await writeFile(file, line({ type: 'assistant', timestamp: work })
+ + line({ type: 'ai-title', padding: 'x'.repeat(2 * 1024 * 1024 + 1) }))
+ expect(await transcriptActivityAt(file, 'claude')).toBeNull()
+})
diff --git a/cli/src/lib/transcriptActivity.ts b/cli/src/lib/transcriptActivity.ts
new file mode 100644
index 000000000..9fa4014c9
--- /dev/null
+++ b/cli/src/lib/transcriptActivity.ts
@@ -0,0 +1,108 @@
+import { open, stat } from 'node:fs/promises'
+
+const CHUNK_BYTES = 64 * 1024
+const MAX_TAIL_BYTES = 2 * 1024 * 1024
+const cache = new Map<string, { signature: string; value: Promise<number | null> }>()
+let reading = 0
+const waiting: Array<() => void> = []
+
+function object(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown> : null
+}
+
+const codexEvents = new Set([
+ 'user_message', 'UserMessage', 'agent_message', 'AgentMessage',
+ 'task_started', 'task_complete', 'turn_aborted', 'context_compacted',
+])
+const codexResponses = new Set([
+ 'reasoning', 'function_call', 'custom_tool_call', 'tool_search_call',
+ 'function_call_output', 'custom_tool_call_output', 'tool_search_output',
+])
+
+/** Metadata can be rewritten when an idle harness is discovered or resumed. Only conversation
+ * records count; a fresh file mtime, title, context snapshot, or rate-limit reading does not. */
+function activity(line: string, engine: string): number | null {
+ let row: Record<string, unknown> | null
+ try { row = object(JSON.parse(line)) } catch { return null }
+ if (!row || typeof row.timestamp !== 'string') return null
+ const at = Date.parse(row.timestamp)
+ if (!Number.isFinite(at)) return null
+ if (engine === 'claude') {
+ return row.type === 'user' || row.type === 'assistant'
+ || row.type === 'system' && ['turn_duration', 'stop_hook_summary', 'compact_boundary'].includes(String(row.subtype))
+ ? at : null
+ }
+ const direct = object(row.payload)
+ const item = object(direct?.item) ?? direct
+ if (row.type === 'event_msg' && codexEvents.has(String(item?.type))) return at
+ if (row.type === 'response_item' && item) {
+ if (codexResponses.has(String(item.type))) return at
+ if (item.type === 'message' && (item.role === 'user' || item.role === 'assistant')) return at
+ }
+ return row.type === 'compacted' ? at : null
+}
+
+async function readActivity(path: string, size: number, engine: string): Promise<number | null> {
+ if (reading >= 4) await new Promise<void>(resolve => waiting.push(resolve))
+ else reading++
+ try {
+ const file = await open(path, 'r')
+ try {
+ let end = size
+ let remaining = MAX_TAIL_BYTES
+ let prefix = Buffer.alloc(0)
+ while (end > 0 && remaining > 0) {
+ const length = Math.min(CHUNK_BYTES, end, remaining)
+ const start = end - length
+ const buffer = Buffer.alloc(length)
+ const { bytesRead } = await file.read(buffer, 0, length, start)
+ // The file was truncated while being read. Let the next frame retry its new signature.
+ if (bytesRead !== length) return null
+ const chunk = Buffer.concat([buffer, prefix])
+ const newline = start === 0 ? -1 : chunk.indexOf(10)
+ if (start === 0 || newline !== -1) {
+ const complete = start === 0 ? chunk : chunk.subarray(newline + 1)
+ let latest: number | null = null
+ for (const line of complete.toString('utf8').split('\n')) {
+ const at = activity(line, engine)
+ if (at !== null) latest = Math.max(latest ?? at, at)
+ }
+ if (latest !== null) return latest
+ prefix = start === 0 ? Buffer.alloc(0) : chunk.subarray(0, newline + 1)
+ } else {
+ // Keep a partial large record until the preceding chunk completes it.
+ prefix = chunk
+ }
+ end = start
+ remaining -= length
+ }
+ return null
+ } finally {
+ await file.close()
+ }
+ } catch {
+ return null
+ } finally {
+ const next = waiting.shift()
+ if (next) next()
+ else reading--
+ }
+}
+
+/** Read the latest dated work from known JSONL formats. Bounded tail reads are shared by list/push
+ * frames and cached until the file changes; no transcript text is retained. Other engines use the
+ * caller's last hook instead of pretending their database/file modification time is activity. */
+export async function transcriptActivityAt(path: string | null, engine: string): Promise<number | null> {
+ if (!path || (engine !== 'claude' && engine !== 'codex')) return null
+ const info = await stat(path).catch(() => null)
+ if (!info?.isFile() || !info.size) return null
+ const key = `${engine}:${path}`
+ const signature = `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`
+ const found = cache.get(key)
+ if (found?.signature === signature) return found.value
+ if (cache.size >= 512) cache.delete(cache.keys().next().value!)
+ const value = readActivity(path, info.size, engine)
+ cache.set(key, { signature, value })
+ return value
+}
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 7b2b047cc..9e6dafd85 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -211,6 +211,47 @@ final _automaticHarnessName = RegExp(
bool isAutomaticHarnessName(String name) =>
_automaticHarnessName.hasMatch(name);
+/// Only measurements confirmed by this harness's own tool receipts.
+class AgentOutputStats {
+ const AgentOutputStats({
+ this.linesAdded,
+ this.linesRemoved,
+ this.pullRequestsCreated,
+ this.updatedAt,
+ });
+ final int? linesAdded, linesRemoved, pullRequestsCreated;
+ final DateTime? updatedAt;
+ bool get hasEdits => linesAdded != null && linesRemoved != null;
+ bool get isEmpty => !hasEdits && pullRequestsCreated == null;
+ static AgentOutputStats? fromJson(Object? value) {
+ if (value is! Map) return null;
+ int? count(Object? n) =>
+ n is int && n >= 0 && n <= 9007199254740991 ? n : null;
+ final added = count(value['linesAdded']),
+ removed = count(value['linesRemoved']);
+ final stats = AgentOutputStats(
+ linesAdded: removed == null ? null : added,
+ linesRemoved: added == null ? null : removed,
+ pullRequestsCreated: count(value['pullRequestsCreated']),
+ updatedAt: value['updatedAt'] is String
+ ? DateTime.tryParse(value['updatedAt'] as String)
+ : null,
+ );
+ return stats.isEmpty ? null : stats;
+ }
+
+ @override
+ bool operator ==(Object other) =>
+ other is AgentOutputStats &&
+ linesAdded == other.linesAdded &&
+ linesRemoved == other.linesRemoved &&
+ pullRequestsCreated == other.pullRequestsCreated &&
+ updatedAt == other.updatedAt;
+ @override
+ int get hashCode =>
+ Object.hash(linesAdded, linesRemoved, pullRequestsCreated, updatedAt);
+}
+
class Agent {
final String id;
final String? sessionId;
@@ -241,6 +282,13 @@ class Agent {
/// The CLI's transcript/hook activity time, not its registry refresh time.
final DateTime? lastActivityAt;
+
+ /// Cached conversation usage reported by this agent's owning machine.
+ final int? tokensUsed;
+ final DateTime? tokensUpdatedAt;
+ final AgentOutputStats? outputStats;
+ bool get hasMonitorStats =>
+ tokensUsed != null || (outputStats != null && !outputStats!.isEmpty);
final String status;
final String launchState;
final String? launchError;
@@ -311,6 +359,9 @@ class Agent {
this.parentAgentId,
this.project,
this.lastActivityAt,
+ this.tokensUsed,
+ this.tokensUpdatedAt,
+ this.outputStats,
this.status = 'active',
this.launchState = 'ready',
this.launchError,
@@ -389,6 +440,9 @@ class Agent {
_ => 'ready',
};
final grid = j['grid'] as Map<String, dynamic>?;
+ final usage = j['tokenUsage'];
+ final total = usage is Map ? usage['totalTokens'] : null;
+ final validTokens = total is int && total >= 0 && total <= 9007199254740991;
return Agent(
id: j['id'] as String,
sessionId: _safeLabel(j['sessionId']),
@@ -405,6 +459,12 @@ class Agent {
lastActivityAt: j['updatedAt'] is String
? DateTime.tryParse(j['updatedAt'] as String)
: null,
+ tokensUsed: validTokens ? total : null,
+ tokensUpdatedAt:
+ validTokens && usage is Map && usage['updatedAt'] is String
+ ? DateTime.tryParse(usage['updatedAt'] as String)
+ : null,
+ outputStats: AgentOutputStats.fromJson(j['outputStats']),
status: (j['status'] as String?) ?? 'active',
launchState: launchState,
launchError: launchState == 'failed' ? _safeLabel(launch['error']) : null,
@@ -447,6 +507,9 @@ class Agent {
parentAgentId: parentAgentId,
project: project,
lastActivityAt: lastActivityAt,
+ tokensUsed: tokensUsed,
+ tokensUpdatedAt: tokensUpdatedAt,
+ outputStats: outputStats,
status: status ?? this.status,
launchState: launchState,
launchError: launchError,
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 452746d88..3840fef62 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -704,6 +704,23 @@ class AppNotifier extends ChangeNotifier {
// terminal streams and nothing else — its web panes are unloaded until it is shown again.
static const maxClosedSwarms = 24;
final List<ClosedWork> _closedHistory = [];
+ // The monitor follows user-visible panes, never the daemon's entire process
+ // inventory. Keep identities after a pane is minimized, paused or closed.
+ final _monitorHarnesses = <(String, String)>{};
+ bool hasOpenedHarness(String machineId, String agentId) =>
+ _monitorHarnesses.contains((machineId, agentId));
+
+ /// Record pane intent, never daemon discovery. Saved with the existing layout.
+ void rememberOpenedHarness(String machineId, String agentId) {
+ if (machineId.isEmpty || agentId.isEmpty) return;
+ final identity = (machineId, agentId);
+ _monitorHarnesses.remove(identity);
+ _monitorHarnesses.add(identity);
+ if (_monitorHarnesses.length > 4096) {
+ _monitorHarnesses.remove(_monitorHarnesses.first);
+ }
+ }
+
int _nextClosedHistoryId = 1;
List<ClosedWork> get closedHistory =>
List.unmodifiable(_closedHistory.reversed);
@@ -749,6 +766,15 @@ class AppNotifier extends ChangeNotifier {
}
void _rememberClosed(ClosedWork entry) {
+ if (entry is ClosedAgent) {
+ rememberOpenedHarness(entry.machineId, entry.agentId);
+ } else if (entry is ClosedSwarm) {
+ for (final pane in entry.panes) {
+ if (pane.agentId case final id?) {
+ rememberOpenedHarness(pane.machineId, id);
+ }
+ }
+ }
// An unused starter has no work to recover. This also covers empty pages
// restored from builds that did not mark them as drafts.
if (entry is ClosedSwarm &&
@@ -2963,6 +2989,7 @@ class AppNotifier extends ChangeNotifier {
expandedMachines.clear();
selectedMachineId = null;
_closedHistory.clear();
+ _monitorHarnesses.clear();
_draftSwarmReturns.clear();
_localMismatchReported.clear();
_dismissedLinkPrompts.clear();
@@ -3145,6 +3172,7 @@ class AppNotifier extends ChangeNotifier {
if (_disposed || signingIn || signingOut || signOutError != null) return;
final revision = _invalidateAuthWork();
_closedHistory.clear();
+ _monitorHarnesses.clear();
_lastError = null;
status = AppStatus.bootstrapping;
signingIn = true;
@@ -3305,6 +3333,7 @@ class AppNotifier extends ChangeNotifier {
_lastError = null;
pendingAuthorizeUrl = null;
_closedHistory.clear();
+ _monitorHarnesses.clear();
status = AppStatus.unauthenticated;
currentUser = null;
analyticsAccount.clear();
@@ -4087,6 +4116,9 @@ class AppNotifier extends ChangeNotifier {
prev.parentAgentId != agent.parentAgentId ||
prev.project != agent.project ||
prev.lastActivityAt != agent.lastActivityAt ||
+ prev.tokensUsed != agent.tokensUsed ||
+ prev.outputStats != agent.outputStats ||
+ prev.tokensUpdatedAt != agent.tokensUpdatedAt ||
prev.launchState != agent.launchState ||
prev.launchError != agent.launchError ||
prev.launchDetail != agent.launchDetail ||
@@ -9453,6 +9485,11 @@ class AppNotifier extends ChangeNotifier {
}
void _persistLayout() {
+ for (final pane in allPanes) {
+ if (pane.agentId case final id?) {
+ rememberOpenedHarness(pane.machineId, id);
+ }
+ }
_draftSwarmReturns.removeWhere((id, _) {
final swarm = swarms.where((swarm) => swarm.id == id).firstOrNull;
return swarm == null ||
@@ -9474,6 +9511,7 @@ class AppNotifier extends ChangeNotifier {
saved.any((swarm) => swarm.id == savedActive)
? savedActive!
: saved.last.id,
+ monitorHarnesses: _monitorHarnesses,
),
);
}
@@ -9492,7 +9530,15 @@ class AppNotifier extends ChangeNotifier {
final revision = _layoutRevision;
final authRevision = _authRevision;
final saved = await store.loadSwarms();
- if (!_authWorkCurrent(authRevision) || revision != _layoutRevision) return;
+ final known = await store.loadMonitorHarnesses(saved);
+ if (!_authWorkCurrent(authRevision)) return;
+ for (final (machine, agent) in known) {
+ rememberOpenedHarness(machine, agent);
+ }
+ if (revision != _layoutRevision) {
+ _persistLayout();
+ return;
+ }
if (saved != null &&
allPanes.isEmpty &&
swarms.length == 1 &&
@@ -10265,6 +10311,7 @@ class AppNotifier extends ChangeNotifier {
_stopMachineRecovery();
if (signingIn) cliLogin.cancel();
_closedHistory.clear();
+ _monitorHarnesses.clear();
_daemonSupervisionTimer?.cancel();
_updateCheckTimer?.cancel();
_environmentRecheckTimer?.cancel();
diff --git a/desktop/lib/state/harness_sessions.dart b/desktop/lib/state/harness_sessions.dart
index 6aaf5779a..277c7d6f5 100644
--- a/desktop/lib/state/harness_sessions.dart
+++ b/desktop/lib/state/harness_sessions.dart
@@ -93,21 +93,25 @@ List<HarnessSession> harnessSessions(AppNotifier app) {
for (final pane in app.allPanes)
if (pane.agentId != null) (pane.machineId, pane.agentId),
};
+ bool known(String machine, String agent) =>
+ open.contains((machine, agent)) || app.hasOpenedHarness(machine, agent);
return [
for (final machine in app.machineStates.values)
for (final agent in machine.agents)
- HarnessSession(
- machine: machine,
- agent: agent,
- open: open.contains((machine.machine.machineId, agent.id)),
- working: machine.processingAgentIds.contains(agent.id),
- question: machine.blockedAgents[agent.id],
- ),
+ if (known(machine.machine.machineId, agent.id))
+ HarnessSession(
+ machine: machine,
+ agent: agent,
+ open: open.contains((machine.machine.machineId, agent.id)),
+ working: machine.processingAgentIds.contains(agent.id),
+ question: machine.blockedAgents[agent.id],
+ ),
// Keep a real pending question visible while its roster entry is missing.
// It must never become an invented terminal or a target for Pause.
for (final machine in app.machineStates.values)
for (final question in machine.blockedAgents.values)
- if (!machine.agents.any((agent) => agent.id == question.agentId))
+ if (known(machine.machine.machineId, question.agentId) &&
+ !machine.agents.any((agent) => agent.id == question.agentId))
HarnessSession(
machine: machine,
agent: Agent(id: question.agentId, name: 'Unavailable harness'),
diff --git a/desktop/lib/state/pane_layout_store.dart b/desktop/lib/state/pane_layout_store.dart
index d4ae5bcc7..39956a30f 100644
--- a/desktop/lib/state/pane_layout_store.dart
+++ b/desktop/lib/state/pane_layout_store.dart
@@ -138,7 +138,49 @@ class PaneLayoutStore {
}
}
- Future<void> saveSwarms(List<Swarm> swarms, String activeId) {
+ /// Migrate only explicit navigation history from earlier builds. Discovery
+ /// alone never earns a place in the monitor.
+ Future<List<(String, String)>> loadMonitorHarnesses(
+ Map<String, dynamic>? layout,
+ ) async {
+ final result = <(String, String)>[];
+ final known = layout?['monitorHarnesses'];
+ if (known is List) {
+ for (final entry in known.take(4096)) {
+ if (entry is List &&
+ entry.length == 2 &&
+ entry[0] is String &&
+ entry[1] is String &&
+ (entry[0] as String).length <= 256 &&
+ (entry[1] as String).length <= 256) {
+ result.add((entry[0] as String, entry[1] as String));
+ }
+ }
+ } else {
+ try {
+ final raw = await storage.read('swarm_recent_v1');
+ final recent = raw == null ? null : jsonDecode(raw);
+ if (recent is List) {
+ for (final id in recent.take(64)) {
+ if (id is! String || !id.startsWith('agent:') || id.length > 520) {
+ continue;
+ }
+ final parts = id.substring(6).split('\u0000');
+ if (parts.length == 2) result.add((parts[0], parts[1]));
+ }
+ }
+ } catch (_) {
+ /* A missing history is an empty history. */
+ }
+ }
+ return result;
+ }
+
+ Future<void> saveSwarms(
+ List<Swarm> swarms,
+ String activeId, {
+ Iterable<(String, String)> monitorHarnesses = const [],
+ }) {
// Capture each request before yielding, but keep only the latest snapshot
// while a write is pending. Holding a navigation key must not queue a full
// state-file rewrite for every intermediate focus or tab selection.
@@ -147,6 +189,9 @@ class PaneLayoutStore {
'version': 1,
'activeId': activeId,
'swarms': swarms.map((s) => s.toJson()).toList(),
+ 'monitorHarnesses': [
+ for (final (machine, agent) in monitorHarnesses) [machine, agent],
+ ],
});
} catch (_) {
return Future<void>.value();
diff --git a/desktop/lib/widgets/harness_session_manager.dart b/desktop/lib/widgets/harness_session_manager.dart
index 499c2a115..390397636 100644
--- a/desktop/lib/widgets/harness_session_manager.dart
+++ b/desktop/lib/widgets/harness_session_manager.dart
@@ -10,6 +10,8 @@ import '../shared/widgets/app_menu.dart';
import '../state/app_state.dart';
import '../state/harness_sessions.dart';
import '../state/swarm_navigation.dart';
+import '../core/models.dart';
+import '../usage/ledger/usage_overview.dart' show formatTokens;
import 'engine_identity.dart';
/// A compact, live inventory. Action receipts belong to AppNotifier, so
@@ -187,6 +189,11 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
26,
) +
(showingQuestions ? scale.scale(AppType.monoMetaSize) * 1.4 + 6 : 0);
+ double heightFor(HarnessSession row) =>
+ rowHeight +
+ (row.agent.hasMonitorStats
+ ? scale.scale(AppType.monoMetaSize) * 1.4 + 6
+ : 0);
return FocusScope(
child: CallbackShortcuts(
bindings: {
@@ -236,10 +243,14 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
// Materialize a distant row, then use its real bounds. Question
// text, errors, row padding and enlarged type all affect height.
_scroll.jumpTo(
- (6 + next * (rowHeight + 2)).clamp(
- 0,
- _scroll.position.maxScrollExtent,
- ),
+ (6 +
+ rows
+ .take(next)
+ .fold<double>(
+ 0,
+ (height, row) => height + heightFor(row) + 2,
+ ))
+ .clamp(0, _scroll.position.maxScrollExtent),
);
WidgetsBinding.instance.addPostFrameCallback((_) => reveal());
}
@@ -446,17 +457,15 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
),
const SizedBox(height: 12),
Text(
- all.isEmpty
- ? 'Your harnesses live here'
- : showingQuestions &&
- _search.text.trim().isEmpty
+ showingQuestions && _search.text.trim().isEmpty
? 'No harnesses need your input'
+ : all.isEmpty
+ ? 'Your harnesses live here'
: 'No matching harnesses',
style: AppType.label(height: 1.3),
),
if (!showingQuestions ||
- _search.text.trim().isNotEmpty ||
- all.isEmpty) ...[
+ _search.text.trim().isNotEmpty) ...[
const SizedBox(height: 6),
Text(
all.isEmpty
@@ -506,7 +515,7 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
() => GlobalKey(),
),
row: row,
- height: rowHeight,
+ height: heightFor(row),
now: now,
showQuestion: showingQuestions,
selected:
@@ -628,6 +637,14 @@ class _SessionRow extends StatelessWidget {
row.project?.shownBranch,
row.question?.prompt,
activity,
+ if (row.agent.tokensUsed case final count?)
+ '$count tokens used',
+ if (row.agent.outputStats case final stats?) ...[
+ if (stats.hasEdits)
+ '${stats.linesAdded} lines added, ${stats.linesRemoved} lines removed in recorded edits',
+ if (stats.pullRequestsCreated case final count?)
+ '$count pull requests created',
+ ],
busy ? pendingLabel : row.status,
].whereType<String>().join(', '),
onTap: canOpen ? onOpen : null,
@@ -662,6 +679,26 @@ class _SessionRow extends StatelessWidget {
),
),
),
+ if (row.lastActiveAt != null)
+ Padding(
+ padding: const EdgeInsets.only(
+ left: 8,
+ ),
+ child: Tooltip(
+ message:
+ 'Last active ${row.lastActiveAt!.toLocal()}',
+ child: Text(
+ '· ${harnessActivityAge(row.lastActiveAt, now)}',
+ key: ValueKey(
+ 'session-age:${row.id}',
+ ),
+ style: AppType.monoMeta(
+ color:
+ AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ ),
if (attention != null && !busy)
Padding(
padding: const EdgeInsets.only(
@@ -703,20 +740,15 @@ class _SessionRow extends StatelessWidget {
),
],
],
- const SizedBox(width: 12),
- detail(
- LucideIcons.clock3,
- harnessActivityAge(
- row.lastActiveAt,
- now,
- ),
- AppPalette.textSecondary,
- tooltip: row.lastActiveAt == null
- ? activity
- : 'Last active ${row.lastActiveAt!.toLocal()}',
- ),
],
),
+ if (row.agent.hasMonitorStats) ...[
+ const SizedBox(height: 6),
+ _MonitorStats(
+ agent: row.agent,
+ id: row.id,
+ ),
+ ],
if (showQuestion)
if (row.question
case final question?) ...[
@@ -825,3 +857,85 @@ class _SessionRow extends StatelessWidget {
);
}
}
+
+class _MonitorStats extends StatelessWidget {
+ const _MonitorStats({required this.agent, required this.id});
+ final Agent agent;
+ final String id;
+
+ @override
+ Widget build(BuildContext context) {
+ final style = AppType.monoMeta(
+ color: AppPalette.textSecondary,
+ height: 1.3,
+ );
+ String measured(DateTime? time) =>
+ time == null ? '' : '\nUpdated ${time.toLocal()}';
+ final stats = agent.outputStats;
+ final items = <Widget>[
+ if (agent.tokensUsed case final count?)
+ Tooltip(
+ message:
+ '$count tokens · input, output and cached input${measured(agent.tokensUpdatedAt)}',
+ child: Text(
+ '${formatTokens(count)} tokens',
+ key: ValueKey('session-tokens:$id'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: style,
+ ),
+ ),
+ if (stats != null && stats.hasEdits)
+ Tooltip(
+ message:
+ '${stats.linesAdded} lines added · ${stats.linesRemoved} removed\n'
+ 'Recorded edits by this harness, including repeated edits. Not the current branch diff.'
+ '${measured(stats.updatedAt)}',
+ child: Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: '+${formatTokens(stats.linesAdded!)}',
+ style: const TextStyle(color: Color(0xff8dbb79)),
+ ),
+ const TextSpan(text: ' '),
+ TextSpan(
+ text: '−${formatTokens(stats.linesRemoved!)}',
+ style: const TextStyle(color: Color(0xffd28f87)),
+ ),
+ ],
+ ),
+ key: ValueKey('session-edits:$id'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: style,
+ ),
+ ),
+ if (stats?.pullRequestsCreated case final count?)
+ Tooltip(
+ message:
+ '$count ${count == 1 ? 'pull request' : 'pull requests'} created by this harness\n'
+ 'Confirmed creation receipts. Cached; not a live GitHub status.${measured(stats?.updatedAt)}',
+ child: Text(
+ '$count ${count == 1 ? 'PR' : 'PRs'}',
+ key: ValueKey('session-prs:$id'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: style,
+ ),
+ ),
+ ];
+ return Row(
+ children: [
+ for (var i = 0; i < items.length; i++) ...[
+ if (i > 0)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ child: Text('·', style: style),
+ ),
+ Flexible(child: items[i]),
+ ],
+ ],
+ );
+ }
+}
diff --git a/desktop/test/agent_model_test.dart b/desktop/test/agent_model_test.dart
index e76cd2043..e7a9a5fd1 100644
--- a/desktop/test/agent_model_test.dart
+++ b/desktop/test/agent_model_test.dart
@@ -1,7 +1,110 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
void main() {
+ test(
+ 'cached output stats survive renames and participate in roster equality',
+ () {
+ final raw = <String, dynamic>{
+ 'id': 'a',
+ 'name': 'Work',
+ 'outputStats': {
+ 'linesAdded': 124,
+ 'linesRemoved': 38,
+ 'pullRequestsCreated': 2,
+ 'updatedAt': '2026-09-23T00:00:00Z',
+ },
+ };
+ final agent = Agent.fromJson(raw);
+ expect(agent.outputStats?.linesAdded, 124);
+ expect(agent.copyWith(name: 'Renamed').outputStats, agent.outputStats);
+ expect(agent.hasMonitorStats, isTrue);
+ expect(AppNotifier.agentsEqual([agent], [Agent.fromJson(raw)]), isTrue);
+ expect(
+ AppNotifier.agentsEqual(
+ [agent],
+ [
+ Agent.fromJson({
+ ...raw,
+ 'outputStats': {
+ 'linesAdded': 125,
+ 'linesRemoved': 38,
+ 'pullRequestsCreated': 2,
+ },
+ }),
+ ],
+ ),
+ isFalse,
+ );
+ for (final invalid in [-1, 1.5, '12', 9007199254740992]) {
+ final parsed = Agent.fromJson({
+ 'id': 'a',
+ 'outputStats': {
+ 'linesAdded': invalid,
+ 'linesRemoved': 38,
+ 'pullRequestsCreated': invalid,
+ },
+ });
+ expect(parsed.outputStats, isNull);
+ expect(parsed.hasMonitorStats, isFalse);
+ }
+ },
+ );
+ test('cached token usage survives rename/pause and participates in roster updates', () {
+ final agent = Agent.fromJson({
+ 'id': 'remote-harness',
+ 'tokenUsage': {
+ 'totalTokens': 1234567,
+ 'updatedAt': '2026-09-22T16:00:00Z',
+ },
+ });
+ expect(agent.tokensUsed, 1234567);
+ expect(agent.tokensUpdatedAt, DateTime.utc(2026, 9, 22, 16));
+ expect(
+ agent.copyWith(name: 'Renamed', status: 'stopped').tokensUsed,
+ 1234567,
+ );
+ expect(
+ AppNotifier.agentsEqual(
+ [agent],
+ [
+ Agent.fromJson({
+ 'id': agent.id,
+ 'tokenUsage': {
+ 'totalTokens': 2345678,
+ 'updatedAt': '2026-09-22T16:00:00Z',
+ },
+ }),
+ ],
+ ),
+ isFalse,
+ );
+ for (final value in [
+ null,
+ -1,
+ 1.5,
+ '12',
+ double.infinity,
+ 9007199254740992,
+ ]) {
+ expect(
+ Agent.fromJson({
+ 'id': 'legacy',
+ 'tokenUsage': {'totalTokens': value},
+ }).tokensUsed,
+ isNull,
+ );
+ }
+ expect(Agent.fromJson({'id': 'legacy'}).tokensUsed, isNull);
+ expect(
+ Agent.fromJson({
+ 'id': 'new',
+ 'tokenUsage': {'totalTokens': 0},
+ }).tokensUsed,
+ 0,
+ );
+ });
_dshTests();
_cloneTests();
test('uses explicit terminal availability from a new CLI', () {
diff --git a/desktop/test/harness_monitor_visibility_test.dart b/desktop/test/harness_monitor_visibility_test.dart
new file mode 100644
index 000000000..db74ca548
--- /dev/null
+++ b/desktop/test/harness_monitor_visibility_test.dart
@@ -0,0 +1,109 @@
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_sessions.dart';
+import 'package:harness/state/pane_layout_store.dart';
+import 'package:harness/state/swarm_navigation.dart';
+
+import 'swarm_attention_test.dart' show waitingQuestion;
+import 'swarm_state_test.dart' show MemoryStore, createApp;
+
+void main() {
+ test('discovery and internal questions never add unseen harnesses to the monitor', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents.addAll([
+ const Agent(
+ id: 'probe',
+ name: 'Performance probe 123',
+ engine: 'terminal',
+ ),
+ const Agent(
+ id: 'child',
+ name: 'Background worker',
+ engine: 'codex',
+ parentAgentId: 'a0',
+ ),
+ ]);
+ app.machineStates['m']!.blockedAgents['child'] = waitingQuestion('child');
+ expect(harnessSessions(app), isEmpty);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(harnessSessions(app).map((row) => row.agent.id), ['a0']);
+ expect(harnessSessions(app).where((row) => row.needsInput), isEmpty);
+ // Explicitly opening another engine makes it user-visible too.
+ await app.addAgentToSwarm('m', 'probe');
+ expect(harnessSessions(app).map((row) => row.agent.id), ['a0', 'probe']);
+ });
+
+ test(
+ 'closed and paused harnesses survive restart without retaining streams',
+ () async {
+ final storage = MemoryStore();
+ final app = createApp(store: storage);
+ await app.addAgentToSwarm('m', 'a0');
+ await app.closePane(app.panes.single.id);
+ await app.flushPaneLayout();
+ expect(app.allPanes, isEmpty);
+ expect(harnessSessions(app).single.agent.id, 'a0');
+ app.dispose();
+ final restored = createApp(store: storage);
+ addTearDown(restored.dispose);
+ restored.machineStates['m']!.agents = [
+ const Agent(
+ id: 'a0',
+ name: 'Saved work',
+ engine: 'claude',
+ sessionId: 'saved-conversation',
+ status: 'stopped',
+ ),
+ const Agent(
+ id: 'probe',
+ name: 'Performance probe 123',
+ engine: 'terminal',
+ status: 'stopped',
+ ),
+ ];
+ await restored.restorePaneLayoutForTest();
+ expect(restored.allPanes, isEmpty);
+ expect(harnessSessions(restored).single.agent.id, 'a0');
+ expect(harnessSessions(restored).single.agent.isStopped, isTrue);
+ },
+ );
+
+ test(
+ 'identities include the owning machine and repeated panes deduplicate',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.machineStates['remote'] = MachineState(
+ const Machine(
+ machineId: 'remote',
+ name: 'Remote',
+ authMode: MachineAuthMode.remote,
+ ),
+ )..agents = [const Agent(id: 'a0', name: 'Different harness')];
+ await app.addAgentToSwarm('m', 'a0');
+ app.newSwarm(name: 'Another view');
+ await app.addAgentToSwarm('m', 'a0');
+ expect(harnessSessions(app), hasLength(1));
+ expect(harnessSessions(app).single.machineId, 'm');
+ },
+ );
+
+ test('migrates only explicit recent visits from older builds', () async {
+ final storage = MemoryStore();
+ storage.values['swarm_recent_v1'] = jsonEncode([
+ agentDestinationId('m', 'a0'),
+ 'swarm:old',
+ 9,
+ 'agent:malformed',
+ ]);
+ final store = PaneLayoutStore(storage: storage);
+ expect(await store.loadMonitorHarnesses(null), [('m', 'a0')]);
+ expect(await store.loadMonitorHarnesses({'monitorHarnesses': []}), isEmpty);
+ storage.values['swarm_recent_v1'] = '{broken';
+ expect(await store.loadMonitorHarnesses(null), isEmpty);
+ });
+}
diff --git a/desktop/test/harness_session_manager_test.dart b/desktop/test/harness_session_manager_test.dart
index 578ca9897..282d72168 100644
--- a/desktop/test/harness_session_manager_test.dart
+++ b/desktop/test/harness_session_manager_test.dart
@@ -51,6 +51,8 @@ void main() {
setUp(() {
connection = RestartConnection();
app = createApp(connectionForTest: (_) => connection);
+ app.rememberOpenedHarness('m', 'a0');
+ app.rememberOpenedHarness('m', 'saved');
app.machineStates['m']!
..machine = const Machine(
machineId: 'm',
@@ -119,6 +121,9 @@ void main() {
);
test('recent follows real activity before navigation recency', () {
+ for (final id in ['older', 'newer', 'unknown']) {
+ app.rememberOpenedHarness('m', id);
+ }
app.machineStates['m']!.agents = [
Agent.fromJson({'id': 'older', 'updatedAt': '2026-09-21T10:00:00Z'}),
Agent.fromJson({'id': 'newer', 'updatedAt': '2026-09-22T10:00:00Z'}),
@@ -133,7 +138,51 @@ void main() {
);
});
+ testWidgets(
+ 'displays remote cached tokens beneath context and leaves missing usage empty',
+ (tester) async {
+ app.machineStates['m']!.agents = [
+ Agent.fromJson({
+ 'id': 'a0',
+ 'name': 'Measured harness',
+ 'engine': 'claude',
+ 'sessionId': 'conversation',
+ 'terminal': {'available': true},
+ 'tokenUsage': {
+ 'totalTokens': 1234567,
+ 'updatedAt': '2026-09-22T16:00:00Z',
+ },
+ 'outputStats': {
+ 'linesAdded': 124,
+ 'linesRemoved': 38,
+ 'pullRequestsCreated': 2,
+ 'updatedAt': '2026-09-22T16:00:00Z',
+ },
+ }),
+ _paused,
+ ];
+ await open(tester);
+ expect(find.text('1.2M tokens'), findsOneWidget);
+ expect(find.text('+124 −38'), findsOneWidget);
+ expect(find.text('2 PRs'), findsOneWidget);
+ expect(find.text('0 tokens'), findsNothing);
+ expect(
+ find.byKey(
+ ValueKey('session-tokens:${agentDestinationId('m', 'saved')}'),
+ ),
+ findsNothing,
+ );
+ expect(
+ tester.getTopLeft(find.text('1.2M tokens')).dy,
+ greaterThan(tester.getTopLeft(find.text('iMac — Office').first).dy),
+ );
+ expect(connection.requests, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
test('attention filters live questions, retains missing agents, excludes paused history', () {
+ app.rememberOpenedHarness('m', 'missing');
app.machineStates['m']!.blockedAgents.addAll({
'a0': question('a0'),
'saved': question('saved'),
@@ -477,6 +526,7 @@ void main() {
terminalAvailable: true,
),
);
+ app.rememberOpenedHarness('m', 'unsupported');
await open(tester);
expect(
tester.widget<IconButton>(toggle('unsupported')).onPressed,
@@ -762,6 +812,12 @@ void main() {
app.notifyListeners();
await tester.pumpAndSettle();
expect(updates.last['attention'], 1);
+ app.machineStates['m']!.blockedAgents['hidden-worker'] = question(
+ 'hidden-worker',
+ );
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(updates.last['attention'], 1);
app.machineStates['m']!.blockedAgents.clear();
app.notifyListeners();
await tester.pumpAndSettle();
@@ -771,6 +827,25 @@ void main() {
testWidgets('session manager fits the minimum Mac window and scaled text', (
tester,
) async {
+ app.machineStates['m']!.agents = [
+ Agent.fromJson({
+ 'id': 'a0',
+ 'name': 'A long harness name that must leave room for the activity timestamp',
+ 'engine': 'claude',
+ 'sessionId': 'conversation',
+ 'terminal': {'available': true},
+ 'updatedAt': DateTime.now()
+ .subtract(const Duration(minutes: 8))
+ .toIso8601String(),
+ 'tokenUsage': {'totalTokens': 1234567},
+ 'outputStats': {
+ 'linesAdded': 124,
+ 'linesRemoved': 38,
+ 'pullRequestsCreated': 2,
+ },
+ }),
+ _paused,
+ ];
await open(tester);
tester.view.physicalSize = const Size(880, 560);
await tester.pumpAndSettle();
@@ -825,6 +900,9 @@ void main() {
),
),
]);
+ for (final agent in app.machineStates['m']!.agents) {
+ app.rememberOpenedHarness('m', agent.id);
+ }
final now = DateTime.now();
final ages = {
'a0': 5,
@@ -850,6 +928,23 @@ void main() {
'updatedAt': now
.subtract(Duration(minutes: ages[agent.id]!))
.toIso8601String(),
+ if (agent.id == 'a0' || agent.id == 'review')
+ 'outputStats': {
+ 'linesAdded': agent.id == 'a0' ? 124 : 832,
+ 'linesRemoved': agent.id == 'a0' ? 38 : 156,
+ 'pullRequestsCreated': agent.id == 'a0' ? 1 : 2,
+ 'updatedAt': now.toIso8601String(),
+ },
+ if (agent.id != 'docs')
+ 'tokenUsage': {
+ 'totalTokens': switch (agent.id) {
+ 'a0' => 48750,
+ 'review' => 1234567,
+ 'api' => 32410,
+ _ => 215400,
+ },
+ 'updatedAt': now.toIso8601String(),
+ },
}),
];
app.machineStates['m']!.blockedAgents['api'] = question('api');
diff --git a/desktop/test/swarm_attention_picker_test.dart b/desktop/test/swarm_attention_picker_test.dart
index d79f880ea..009bc35a7 100644
--- a/desktop/test/swarm_attention_picker_test.dart
+++ b/desktop/test/swarm_attention_picker_test.dart
@@ -138,6 +138,7 @@ void main() {
final panes = [...app.panes];
final machine = app.machineStates['m']!;
for (var i = 0; i < 25; i++) {
+ app.rememberOpenedHarness('m', 'a$i');
machine.blockedAgents['a$i'] = waitingQuestion(
'a$i',
prompt: 'Question $i?',
@@ -209,6 +210,7 @@ void main() {
(tester) async {
final app = createApp();
final machine = app.machineStates['m']!;
+ app.rememberOpenedHarness('m', 'missing');
machine.blockedAgents['missing'] = waitingQuestion('missing');
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyI, shift: true);
diff --git a/docs/images/harness-monitor-stats.png b/docs/images/harness-monitor-stats.png
new file mode 100644
index 000000000..9ec821a9c
Binary files /dev/null and b/docs/images/harness-monitor-stats.png differ