Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(mobile): feed Usages + Inbox to the companion through the agent-status mirror

enes422dddd2d6c8
diff --git a/docs/mobile-usage-inbox.md b/docs/mobile-usage-inbox.md
new file mode 100644
index 000000000..f544ca96d
--- /dev/null
+++ b/docs/mobile-usage-inbox.md
@@ -0,0 +1,143 @@
+# Mobile Usages & Inbox — protocol contract (v1)
+
+The iOS companion's Inbox sheet has two tabs — **Agents** (inbox feed) and **Usages** — that
+were designed empty states until now. This doc is the cross-repo contract that activates them.
+Everything rides in the **existing agent-status mirror file** (`agent-status.json` /
+`agent-status-<projectId>.json`) — no new files, no new transport: the phone already batch-reads
+these over SSH (and gets the same blob over the relay `projects.list` RPC).
+
+## Transport recap
+
+- Desktop/server writes `<userData>/agent-status.json` (atomic, 0600, 300 ms debounce) —
+ `src/core/agent-status-mirror.ts`.
+- For connected SSH projects, `src/main/remote-ssh/remote-status-push.ts` pushes per-project
+ slices to `~/.nodeterm/agent-status-<projectId>.json` on the host (2 s throttle, 60 s heartbeat).
+- iOS polls these every 8 s while foregrounded (`AgentStatusMonitor` → `NodetermProjects.swift`).
+
+`MirrorFile.v` stays `1` — all additions are optional fields; old readers ignore them.
+
+## MirrorFile additions
+
+```ts
+export interface MirrorFile {
+ v: 1
+ updatedAt: number
+ nodes: Record<string, MirrorEntry>
+ settings?: MirrorSettings
+ usage?: MirrorUsage // NEW — local accounts' provider rate-limit usage
+ inbox?: MirrorInbox // NEW — event feed + per-node live activity
+}
+```
+
+### Usage
+
+```ts
+export interface MirrorUsage {
+ updatedAt: number
+ accounts: MirrorUsageAccount[] // system account first, then managed local accounts
+}
+export interface MirrorUsageAccount {
+ accountId: string | null // null = system ~/.claude
+ label: string | null // account label from settings (managed accounts)
+ email: string | null
+ agentId: string // 'claude' (codex later — same shape)
+ status: string // 'ok' | 'unavailable' | 'error' | 'fetching'
+ updatedAt: number
+ limits: MirrorUsageLimit[] // pass-through of shared UsageLimit — do NOT re-derive
+}
+// Snapshot of shared UsageLimit, tolerated loose: another branch is generalizing it
+// (severity may be string|null, windowMinutes may appear). The mirror passes entries through
+// verbatim; readers must treat every field but kind/usedPercent as optional.
+export interface MirrorUsageLimit {
+ kind: string // 'session' | 'weekly_all' | 'weekly_scoped' | future
+ group?: string | null // 'session' | 'weekly'
+ usedPercent: number // 0–100 consumed
+ severity?: string | null // null ⇒ derive colour from percentage locally
+ resetsAt?: number | null // unix ms
+ windowMinutes?: number | null // real window length when the provider reports it
+ scopeLabel?: string | null // per-model scoped limit's model name
+ isActive?: boolean
+}
+```
+
+Rules:
+- Source is `src/core/usage/usage-service.ts` caches. The service now proactively polls **all
+ local accounts** (system + non-pending local managed accounts) on its existing 15-min cadence,
+ not just the system account, and notifies the mirror on every cache update.
+- **SSH slices carry no `usage`** in v1 (`filterMirrorForNodes` drops it, like `settings`):
+ a remote host's account credentials live on that host, so the desktop cannot answer for them.
+ A host that runs nodeterm itself (server edition) writes its own mirror with its own usage.
+- Remote accounts stay excluded (same rule as the desktop usage indicator).
+
+### Inbox
+
+```ts
+export interface MirrorInbox {
+ events: InboxEvent[] // oldest→newest, capped at EVENTS_CAP (50)
+ nodes: Record<string, InboxNodeNow> // per-node "what it's doing right now"
+}
+export interface InboxEvent {
+ id: string // monotonic per writer, e.g. `${ts}-${seq}`
+ ts: number // unix ms
+ nodeId: string
+ agentId?: string
+ sessionId?: string
+ kind: 'approval' | 'question' | 'done'
+ title: string // first line, ≤120 chars — "Approve write to /etc/hosts", "Finished"
+ detail?: string // ≤240 chars — lastMessage snippet
+ interrupted?: boolean // done: user hit Esc/Ctrl-C
+ resolved?: boolean // approval/question: the node has since left blocked/waiting
+}
+export interface InboxNodeNow {
+ activity?: string // ≤80 chars — "Editing foo.ts", "Running npm test", "Reading bar.ts"
+ tool?: string // raw tool name the activity came from
+ contextPercent?: number // context-window fill 0–100 (from context-tail), when known
+ updatedAt: number
+}
+```
+
+Event production (all inside/next to `agent-status-mirror.ts`, fed by the listeners the shells
+already wire):
+
+- Normalized `state:'blocked'` → `approval` event (title = first line of `lastMessage`, else
+ "Needs approval"). `state:'waiting'` → `question` event. Dedup: if the node's newest
+ unresolved approval/question has the same title, bump nothing — do not append a duplicate.
+- Normalized `state:'done'` → `done` event with `detail` = `lastMessage` snippet and
+ `interrupted` passed through. A done following an `interrupted` Esc spam should still be one
+ event per turn (the normalizer already collapses this).
+- When a node leaves blocked/waiting (any newer state event), mark its unresolved
+ approval/question events `resolved: true` (they move to the phone's archive).
+- Node removal (`dropNode`) removes its `nodes` entry; its events stay (feed history) but get
+ `resolved: true`.
+- **Activity** comes from the RAW hook listener (`setRawListener` already sees `tool_name` /
+ `tool_input`): `Edit|Write|NotebookEdit → "Editing <basename>"`, `Read → "Reading <basename>"`,
+ `Bash → "Running <command ≤60ch>"`, `Grep|Glob → "Searching <pattern>"`,
+ `Task → "Delegating: <description>"`, `WebFetch|WebSearch → "Fetching <host|query>"`, else
+ `"Using <tool>"`. Cleared on Stop/done/session-end.
+- **contextPercent** is recorded where the shells broadcast `IPC.contextUpdate` (both
+ `src/main/index.ts` and `src/server/agent-status.ts` `wireAgentStatus`).
+- SSH slices (`filterMirrorForNodes`) keep `inbox` but filter `events` and `nodes` to the
+ project's node ids.
+
+## iOS behavior (v1)
+
+- **Usages tab**: one section per paired connection that reports `usage` (header: host name +
+ relative `updatedAt`). Per account: label/email, per-limit bars — session window and weekly
+ window (scoped limits listed under). Right side: `usedPercent` + reset countdown
+ (`<24h → "16:40"` clock time, else `"3d 16h"`). Colour: severity when present, else derive
+ (≥90 red, ≥70 amber, else green). Pace line: compare `usedPercent` vs elapsed fraction of the
+ window (`windowMinutes` else 300/10080 by kind) → "5h usage pace slower/faster".
+- **Agents tab (feed)**: merged events across connections, newest first; unresolved
+ approval/question cards on top, `done`/resolved under **Archived** (collapsible). Cards show
+ the node's `contextPercent` ring when known, activity line for working nodes, agent chip +
+ relative time. Working sessions with an `activity` string render as live cards even with no
+ event yet.
+- **Quick approve (claude only, v1)**: approval cards for `agentId == 'claude'` get
+ **Approve** / **Deny** buttons: Approve sends the single key `1`, Deny sends `Escape`, to the
+ node's tmux session (`nt-<nodeId>`) over the connection's existing command channel
+ (`tmux send-keys` on the host's nodeterm socket). Before sending, re-read the status file and
+ only send when the node is still `blocked`; otherwise show "already handled". Non-claude
+ approvals fall back to **Open session**.
+- Read/unread + archive state are phone-local (as designed); `resolved` from the host only
+ moves cards out of the actionable list.
+- Live Activities / Dynamic Island / APNs: **out of scope for v1** (still "coming soon").
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.ts
index e376fa413..f7e665aa5 100644
--- a/src/core/agent-status-mirror.test.ts
+++ b/src/core/agent-status-mirror.test.ts
@@ -9,16 +9,25 @@ import {
filterMirrorForNodes,
onMirrorFlush,
recordAgentEvent,
+ recordRawToolEvent,
+ recordContextUsage,
clearNode,
flush,
initAgentStatusMirror,
setMirrorSettingsProvider,
+ setMirrorUsageProvider,
+ buildMirrorUsage,
+ toolActivity,
+ firstLine,
_resetForTest,
_snapshot,
+ _inboxSnapshot,
DONE_HOLDOFF_MS,
EXPIRE_MS,
+ INBOX_EVENTS_CAP,
type MirrorEntry,
- type MirrorFile
+ type MirrorFile,
+ type MirrorUsage
} from './agent-status-mirror'
// Minimal event factory — only the fields the reducer reads.
@@ -281,3 +290,291 @@ describe('settings block', () => {
expect('settings' in JSON.parse(fs.readFileSync(file, 'utf-8'))).toBe(false)
})
})
+
+// ---- mobile-usage-inbox ---------------------------------------------------------------------
+
+describe('inbox event production (via recordAgentEvent)', () => {
+ beforeEach(() => _resetForTest())
+ afterEach(() => _resetForTest())
+
+ it('emits an approval on blocked and dedups a same-title re-assertion', () => {
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write to /etc/hosts' }))
+ let ib = _inboxSnapshot()
+ expect(ib.events).toHaveLength(1)
+ expect(ib.events[0].kind).toBe('approval')
+ expect(ib.events[0].title).toBe('Approve write to /etc/hosts')
+ expect(ib.events[0].resolved).toBeUndefined()
+ // Same blocked ask again (still blocked) → deduped, no second event.
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write to /etc/hosts' }))
+ expect(_inboxSnapshot().events).toHaveLength(1)
+ // A genuinely different ask while still blocked DOES land.
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve rm -rf /tmp/x' }))
+ ib = _inboxSnapshot()
+ expect(ib.events).toHaveLength(2)
+ expect(ib.events[1].title).toBe('Approve rm -rf /tmp/x')
+ })
+
+ it('titles blocked/waiting from lastMessage first line, with fallbacks', () => {
+ recordAgentEvent(ev({ nodeId: 'a', state: 'blocked' }))
+ recordAgentEvent(ev({ nodeId: 'b', state: 'waiting' }))
+ recordAgentEvent(ev({ nodeId: 'c', state: 'waiting', lastMessage: 'Which file?\nsecond line' }))
+ const ev3 = _inboxSnapshot().events
+ expect(ev3.find((e) => e.nodeId === 'a')!.title).toBe('Needs approval')
+ expect(ev3.find((e) => e.nodeId === 'b')!.title).toBe('Waiting for input')
+ const q = ev3.find((e) => e.nodeId === 'c')!
+ expect(q.kind).toBe('question')
+ expect(q.title).toBe('Which file?')
+ })
+
+ it('resolves unresolved approval/question when the node leaves blocked/waiting', () => {
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve?' }))
+ expect(_inboxSnapshot().events[0].resolved).toBeUndefined()
+ recordAgentEvent(ev({ state: 'working' })) // left blocked
+ expect(_inboxSnapshot().events[0].resolved).toBe(true)
+ })
+
+ it('session reset also resolves a pending question', () => {
+ recordAgentEvent(ev({ state: 'waiting', lastMessage: 'Pick one' }))
+ recordAgentEvent(ev({ kind: 'session', sessionPhase: 'end' }))
+ expect(_inboxSnapshot().events[0].resolved).toBe(true)
+ })
+
+ it('emits one done per turn with a detail snippet and passes interrupted through', () => {
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'done', lastMessage: 'All wired up.\nplus extra' }))
+ let ib = _inboxSnapshot()
+ expect(ib.events).toHaveLength(1)
+ expect(ib.events[0]).toMatchObject({ kind: 'done', title: 'Finished', detail: 'All wired up.' })
+ expect(ib.events[0].interrupted).toBeUndefined()
+ // A duplicate done (no new turn) does not append a second event.
+ recordAgentEvent(ev({ state: 'done' }))
+ expect(_inboxSnapshot().events).toHaveLength(1)
+ // A new turn that ends interrupted titles "Stopped".
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'done', interrupted: true }))
+ ib = _inboxSnapshot()
+ expect(ib.events).toHaveLength(2)
+ expect(ib.events[1]).toMatchObject({ kind: 'done', title: 'Stopped', interrupted: true })
+ })
+
+ it('caps the feed at INBOX_EVENTS_CAP, dropping oldest', () => {
+ const total = INBOX_EVENTS_CAP + 10
+ for (let i = 0; i < total; i++) {
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'done', lastMessage: `turn ${i}` }))
+ }
+ const events = _inboxSnapshot().events
+ expect(events).toHaveLength(INBOX_EVENTS_CAP)
+ // The newest survives, the earliest fell off the front.
+ expect(events[events.length - 1].detail).toBe(`turn ${total - 1}`)
+ expect(events[0].detail).toBe(`turn ${total - INBOX_EVENTS_CAP}`)
+ })
+
+ it('clearNode drops the node activity but keeps its events, marked resolved', () => {
+ recordAgentEvent(ev({ nodeId: 'x', state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ nodeId: 'x', state: 'blocked', lastMessage: 'Q' }))
+ recordContextUsage('x', 40)
+ clearNode('x')
+ const ib = _inboxSnapshot()
+ expect(ib.nodes.x).toBeUndefined()
+ expect(ib.events).toHaveLength(1)
+ expect(ib.events[0].resolved).toBe(true)
+ })
+})
+
+describe('activity mapping (toolActivity + recordRawToolEvent)', () => {
+ beforeEach(() => _resetForTest())
+ afterEach(() => _resetForTest())
+
+ it('maps each tool to its activity line', () => {
+ expect(toolActivity('Edit', { file_path: '/a/b/foo.ts' })).toBe('Editing foo.ts')
+ expect(toolActivity('Write', { file_path: 'x/bar.py' })).toBe('Editing bar.py')
+ expect(toolActivity('NotebookEdit', { notebook_path: '/n/nb.ipynb' })).toBe('Editing nb.ipynb')
+ expect(toolActivity('Read', { file_path: '/a/baz.md' })).toBe('Reading baz.md')
+ expect(toolActivity('Bash', { command: 'npm test' })).toBe('Running npm test')
+ expect(toolActivity('Grep', { pattern: 'foo.*bar' })).toBe('Searching foo.*bar')
+ expect(toolActivity('Glob', { pattern: '**/*.ts' })).toBe('Searching **/*.ts')
+ expect(toolActivity('Task', { description: 'refactor auth' })).toBe('Delegating: refactor auth')
+ expect(toolActivity('WebFetch', { url: 'https://example.com/x?q=1' })).toBe('Fetching example.com')
+ expect(toolActivity('WebSearch', { query: 'weather today' })).toBe('Fetching weather today')
+ expect(toolActivity('CustomThing', {})).toBe('Using CustomThing')
+ })
+
+ it('truncates a long Bash command', () => {
+ const long = 'echo ' + 'a'.repeat(200)
+ const out = toolActivity('Bash', { command: long })
+ expect(out.startsWith('Running ')).toBe(true)
+ expect(out.length).toBeLessThanOrEqual('Running '.length + 60)
+ expect(out.endsWith('…')).toBe(true)
+ })
+
+ it('records activity on PreToolUse and clears it on Stop/SessionEnd', () => {
+ recordRawToolEvent('n1', { hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command: 'ls -la' } })
+ expect(_inboxSnapshot().nodes.n1).toMatchObject({ activity: 'Running ls -la', tool: 'Bash' })
+ recordRawToolEvent('n1', { hook_event_name: 'Stop' })
+ expect(_inboxSnapshot().nodes.n1.activity).toBeUndefined()
+
+ recordRawToolEvent('n2', { hook_event_name: 'PreToolUse', tool_name: 'Read', tool_input: { file_path: 'a.ts' } })
+ recordRawToolEvent('n2', { hook_event_name: 'SessionEnd' })
+ expect(_inboxSnapshot().nodes.n2.activity).toBeUndefined()
+ })
+
+ it('a done event clears live activity but keeps context %', () => {
+ recordRawToolEvent('n3', { hook_event_name: 'PreToolUse', tool_name: 'Grep', tool_input: { pattern: 'x' } })
+ recordContextUsage('n3', 30)
+ expect(_inboxSnapshot().nodes.n3).toMatchObject({ activity: 'Searching x', contextPercent: 30 })
+ recordAgentEvent(ev({ nodeId: 'n3', state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ nodeId: 'n3', state: 'done' }))
+ const n3 = _inboxSnapshot().nodes.n3
+ expect(n3.activity).toBeUndefined()
+ expect(n3.contextPercent).toBe(30)
+ })
+
+ it('recordContextUsage clamps to 0–100 and coexists with activity', () => {
+ recordContextUsage('c', 42.5)
+ expect(_inboxSnapshot().nodes.c.contextPercent).toBe(42.5)
+ recordContextUsage('c', 150)
+ expect(_inboxSnapshot().nodes.c.contextPercent).toBe(100)
+ recordRawToolEvent('c', { hook_event_name: 'PreToolUse', tool_name: 'Glob', tool_input: { pattern: '*.md' } })
+ expect(_inboxSnapshot().nodes.c).toMatchObject({ activity: 'Searching *.md', contextPercent: 100 })
+ })
+
+ it('firstLine takes the first non-empty line and clips', () => {
+ expect(firstLine(' \n\n hello there \nmore', 100)).toBe('hello there')
+ expect(firstLine('abcdefghij', 5)).toBe('abcd…')
+ expect(firstLine(undefined, 10)).toBe('')
+ })
+})
+
+describe('buildMirrorUsage', () => {
+ it('maps snapshots to accounts, system first, with defensive limit fields + labels', () => {
+ const snap = [
+ {
+ accountId: null,
+ usage: {
+ email: 'sys@x',
+ updatedAt: 100,
+ status: 'ok',
+ limits: [{ kind: 'session', usedPercent: 20, severity: 'normal', resetsAt: 999 }]
+ }
+ },
+ {
+ accountId: 'a1',
+ usage: { email: null, updatedAt: 200, status: 'ok', limits: [{ kind: 'weekly_all', usedPercent: 80 }] }
+ }
+ ]
+ const mu = buildMirrorUsage(snap, [{ id: 'a1', label: 'Work', email: 'work@x' }], 500)!
+ expect(mu.accounts[0].accountId).toBeNull()
+ expect(mu.accounts[0].label).toBeNull()
+ expect(mu.accounts[0].email).toBe('sys@x')
+ expect(mu.accounts[0].agentId).toBe('claude')
+ expect(mu.accounts[0].limits[0]).toEqual({
+ kind: 'session',
+ group: null,
+ usedPercent: 20,
+ severity: 'normal',
+ resetsAt: 999,
+ windowMinutes: null,
+ scopeLabel: null,
+ isActive: false
+ })
+ // Managed account: label from settings, email backfilled from settings when usage has none,
+ // and its limit's absent severity passes through as null (not defaulted to a colour).
+ expect(mu.accounts[1]).toMatchObject({ accountId: 'a1', label: 'Work', email: 'work@x' })
+ expect(mu.accounts[1].limits[0].severity).toBeNull()
+ // updatedAt is the freshest account's stamp.
+ expect(mu.updatedAt).toBe(200)
+ })
+
+ it('orders the system account first regardless of snapshot order', () => {
+ const snap = [
+ { accountId: 'a1', usage: { status: 'ok', limits: [] } },
+ { accountId: null, usage: { status: 'ok', limits: [] } }
+ ]
+ const mu = buildMirrorUsage(snap, [], 9)!
+ expect(mu.accounts.map((a) => a.accountId)).toEqual([null, 'a1'])
+ })
+
+ it('returns undefined for an empty snapshot', () => {
+ expect(buildMirrorUsage([], [], 5)).toBeUndefined()
+ })
+})
+
+describe('usage block on flush', () => {
+ let tmpDir: string
+ let file: string
+
+ beforeEach(() => {
+ _resetForTest()
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-status-usage-'))
+ file = path.join(tmpDir, 'status.json')
+ initAgentStatusMirror(file)
+ })
+ afterEach(() => {
+ _resetForTest()
+ fs.rmSync(tmpDir, { recursive: true, force: true })
+ })
+
+ it('writes the usage block from the provider', async () => {
+ const usage: MirrorUsage = {
+ updatedAt: 5,
+ accounts: [
+ { accountId: null, label: null, email: 'e', agentId: 'claude', status: 'ok', updatedAt: 5, limits: [] }
+ ]
+ }
+ setMirrorUsageProvider(() => usage)
+ await flush()
+ const doc = JSON.parse(fs.readFileSync(file, 'utf-8'))
+ expect(doc.usage.accounts[0].email).toBe('e')
+ })
+
+ it('omits usage when no provider is wired (old-file shape)', async () => {
+ await flush()
+ expect('usage' in JSON.parse(fs.readFileSync(file, 'utf-8'))).toBe(false)
+ })
+
+ it('a throwing usage provider fails open (no usage, file still written)', async () => {
+ setMirrorUsageProvider(() => { throw new Error('boom') })
+ recordAgentEvent(ev({ state: 'working' }))
+ await flush()
+ const doc = JSON.parse(fs.readFileSync(file, 'utf-8'))
+ expect('usage' in doc).toBe(false)
+ expect(doc.nodes.n1.state).toBe('working')
+ })
+})
+
+describe('filterMirrorForNodes (usage + inbox)', () => {
+ it('drops usage entirely and filters inbox events + nodes to the slice', () => {
+ const doc = buildFile(
+ { a: { state: 'working', updatedAt: 1 }, b: { state: 'done', updatedAt: 2 } },
+ 10,
+ undefined,
+ undefined,
+ {
+ updatedAt: 5,
+ accounts: [
+ { accountId: null, label: null, email: null, agentId: 'claude', status: 'ok', updatedAt: 5, limits: [] }
+ ]
+ },
+ {
+ events: [
+ { id: '1', ts: 1, nodeId: 'a', kind: 'approval', title: 'A' },
+ { id: '2', ts: 2, nodeId: 'b', kind: 'done', title: 'Finished' }
+ ],
+ nodes: { a: { activity: 'x', updatedAt: 1 }, b: { activity: 'y', updatedAt: 2 } }
+ }
+ )
+ expect('usage' in doc).toBe(true)
+ const slice = filterMirrorForNodes(doc, new Set(['a']))
+ expect('usage' in slice).toBe(false)
+ expect(slice.inbox!.events.map((e) => e.nodeId)).toEqual(['a'])
+ expect(Object.keys(slice.inbox!.nodes)).toEqual(['a'])
+ })
+
+ it('buildFile omits an empty inbox (old-file shape preserved)', () => {
+ const d = buildFile({}, 1, undefined, undefined, undefined, { events: [], nodes: {} })
+ expect('inbox' in d).toBe(false)
+ })
+})
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 302696adc..e59170a3e 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -65,6 +65,158 @@ export interface MirrorFile {
* on old files and whenever no settings provider is wired — the file shape is then byte-for-byte
* identical to before this block existed. */
settings?: MirrorSettings
+ /** Local accounts' provider rate-limit usage (spec: mobile-usage-inbox). Additive/optional —
+ * absent on old files, and dropped from SSH slices (a host answers only for its own creds). */
+ usage?: MirrorUsage
+ /** Agent inbox: an event feed + per-node "what it's doing right now" (spec: mobile-usage-inbox).
+ * Additive/optional. Unlike `usage`, SSH slices KEEP a filtered inbox (their own nodes only). */
+ inbox?: MirrorInbox
+}
+
+// ---- Usage block (mobile-usage-inbox) ------------------------------------------------------
+
+/** Snapshot of the shared `UsageLimit`, tolerated LOOSE on purpose: a parallel branch is
+ * generalizing that type (severity may be `string | null`, windowMinutes may appear). The mirror
+ * passes entries through verbatim — every field but `kind`/`usedPercent` is optional here, and
+ * the defensive mapper below (`?? null`) compiles against either shape of the source type. */
+export interface MirrorUsageLimit {
+ kind: string
+ group?: string | null
+ usedPercent: number
+ severity?: string | null
+ resetsAt?: number | null
+ windowMinutes?: number | null
+ scopeLabel?: string | null
+ isActive?: boolean
+}
+export interface MirrorUsageAccount {
+ /** null = the system `~/.claude` account. */
+ accountId: string | null
+ /** Account label from settings (managed accounts); null for the system account. */
+ label: string | null
+ email: string | null
+ agentId: string
+ /** 'ok' | 'unavailable' | 'error' | 'fetching' — passed through from the usage service. */
+ status: string
+ updatedAt: number
+ limits: MirrorUsageLimit[]
+}
+export interface MirrorUsage {
+ updatedAt: number
+ /** System account first, then managed local accounts. */
+ accounts: MirrorUsageAccount[]
+}
+
+/** One cached usage row from the usage service. Deliberately STRUCTURAL (not `import`ed from
+ * `@shared/types`) so this file does not couple to a `ClaudeUsage` shape a parallel branch is
+ * mid-flight editing — a real `ClaudeUsage` is assignable to this loose shape. */
+export interface UsageSnapshotEntry {
+ accountId: string | null
+ usage: {
+ email?: string | null
+ updatedAt?: number
+ status?: string
+ limits?: ReadonlyArray<{
+ kind: string
+ usedPercent: number
+ group?: string | null
+ severity?: string | null
+ resetsAt?: number | null
+ windowMinutes?: number | null
+ scopeLabel?: string | null
+ isActive?: boolean
+ }>
+ }
+}
+
+/**
+ * Assemble the `usage` block from the usage service's cached snapshots + the settings account
+ * list (for labels). Pure. Maps each `UsageLimit` through DEFENSIVELY (`?? null`) so it compiles
+ * whether the source's `severity` is `string` or `string | null`, and never re-derives severity
+ * or window from the percentage — those are the provider's call (see claude-usage-map.ts).
+ * Returns `undefined` when there is nothing to advertise, so the file keeps its old shape.
+ */
+export function buildMirrorUsage(
+ snapshot: ReadonlyArray<UsageSnapshotEntry>,
+ accounts: ReadonlyArray<{ id: string; label?: string | null; email?: string | null }>,
+ now: number
+): MirrorUsage | undefined {
+ if (snapshot.length === 0) return undefined
+ const byId = new Map(accounts.map((a) => [a.id, a]))
+ // System account (accountId null) first, then everything else in given order.
+ const ordered = [...snapshot].sort((a, b) => {
+ if (a.accountId === b.accountId) return 0
+ if (a.accountId === null) return -1
+ if (b.accountId === null) return 1
+ return 0
+ })
+ const mapped: MirrorUsageAccount[] = ordered.map((e) => {
+ const acct = e.accountId ? byId.get(e.accountId) : undefined
+ const u = e.usage
+ return {
+ accountId: e.accountId,
+ label: acct?.label ?? null,
+ email: u.email ?? acct?.email ?? null,
+ agentId: 'claude',
+ status: u.status ?? 'unavailable',
+ updatedAt: u.updatedAt ?? now,
+ limits: (u.limits ?? []).map((l) => ({
+ kind: l.kind,
+ group: l.group ?? null,
+ usedPercent: l.usedPercent,
+ // `?? null` here is the whole point: it type-checks against BOTH a `string` and a
+ // `string | null` severity (the parallel branch's in-flight generalization).
+ severity: l.severity ?? null,
+ resetsAt: l.resetsAt ?? null,
+ windowMinutes: l.windowMinutes ?? null,
+ scopeLabel: l.scopeLabel ?? null,
+ isActive: l.isActive ?? false
+ }))
+ }
+ })
+ const updatedAt = mapped.reduce((m, a) => Math.max(m, a.updatedAt), 0) || now
+ return { updatedAt, accounts: mapped }
+}
+
+// ---- Inbox block (mobile-usage-inbox) ------------------------------------------------------
+
+/** Feed cap — oldest events fall off the front once the array exceeds this. */
+export const INBOX_EVENTS_CAP = 50
+export const INBOX_TITLE_MAX = 120
+export const INBOX_DETAIL_MAX = 240
+export const INBOX_ACTIVITY_MAX = 80
+
+export interface InboxEvent {
+ /** Monotonic per writer: `${ts}-${seq}`. */
+ id: string
+ ts: number
+ nodeId: string
+ agentId?: string
+ sessionId?: string
+ kind: 'approval' | 'question' | 'done'
+ /** First line, ≤120 chars. */
+ title: string
+ /** ≤240 chars — lastMessage snippet. */
+ detail?: string
+ /** done: the user hit Esc/Ctrl-C. */
+ interrupted?: boolean
+ /** approval/question: the node has since left blocked/waiting (moves to the phone's archive). */
+ resolved?: boolean
+}
+export interface InboxNodeNow {
+ /** ≤80 chars — "Editing foo.ts", "Running npm test", "Reading bar.ts". */
+ activity?: string
+ /** Raw tool name the activity came from. */
+ tool?: string
+ /** Context-window fill 0–100 (from context-tail), when known. */
+ contextPercent?: number
+ updatedAt: number
+}
+export interface MirrorInbox {
+ /** Oldest→newest, capped at INBOX_EVENTS_CAP. */
+ events: InboxEvent[]
+ /** Per-node "what it's doing right now". */
+ nodes: Record<string, InboxNodeNow>
}
/**
@@ -112,11 +264,25 @@ export function reduceEntry(
*
* Deliberately drops the local `settings` block: a slice carries per-host settings that the SSH
* push injects itself (Task 2 of mobile-agent-launch-parity), never this host's local block.
+ *
+ * `usage` is likewise DROPPED (spec: mobile-usage-inbox): a remote host's account credentials
+ * live on that host, so the desktop cannot answer for them — a host running nodeterm itself
+ * writes its own mirror with its own usage. `inbox` is KEPT but filtered to the slice's node ids
+ * (both the `events` feed and the per-node `nodes` map).
*/
export function filterMirrorForNodes(doc: MirrorFile, nodeIds: ReadonlySet<string>): MirrorFile {
const nodes: MirrorFile['nodes'] = {}
for (const [id, e] of Object.entries(doc.nodes)) if (nodeIds.has(id)) nodes[id] = e
- return { v: doc.v, updatedAt: doc.updatedAt, nodes }
+ const out: MirrorFile = { v: doc.v, updatedAt: doc.updatedAt, nodes }
+ if (doc.inbox) {
+ const inboxNodes: Record<string, InboxNodeNow> = {}
+ for (const [id, n] of Object.entries(doc.inbox.nodes)) if (nodeIds.has(id)) inboxNodes[id] = n
+ out.inbox = {
+ events: doc.inbox.events.filter((e) => nodeIds.has(e.nodeId)),
+ nodes: inboxNodes
+ }
+ }
+ return out
}
/** Prune expired entries and shape the on-disk file. Pure; `now` injected for testability.
@@ -126,7 +292,9 @@ export function buildFile(
nodes: Record<string, MirrorEntry>,
now: number,
expireMs = EXPIRE_MS,
- settings?: MirrorSettings
+ settings?: MirrorSettings,
+ usage?: MirrorUsage,
+ inbox?: MirrorInbox
): MirrorFile {
const out: MirrorFile = { v: 1, updatedAt: now, nodes: {} }
for (const [id, e] of Object.entries(nodes)) {
@@ -136,9 +304,93 @@ export function buildFile(
out.nodes[id] = { state: e.state, agentId: e.agentId, sessionId: e.sessionId, updatedAt: e.updatedAt }
}
if (settings) out.settings = settings
+ if (usage) out.usage = usage
+ // Only attach a non-empty inbox — an empty one would gratuitously change the old-file shape.
+ if (inbox && (inbox.events.length > 0 || Object.keys(inbox.nodes).length > 0)) out.inbox = inbox
return out
}
+// ---- Inbox production (pure helpers) -------------------------------------------------------
+
+/** Clip a string to `max`, appending an ellipsis when it had to cut. */
+function clip(s: string, max: number): string {
+ return s.length > max ? s.slice(0, max - 1) + '…' : s
+}
+
+/** First non-empty line of a message, trimmed and clipped. '' when absent/blank. */
+export function firstLine(msg: string | undefined, max: number): string {
+ if (!msg) return ''
+ const line = (msg.split('\n').find((l) => l.trim()) ?? '').trim()
+ return clip(line, max)
+}
+
+/** Basename of a slash- or backslash-separated path (no `path` import: works on remote paths too). */
+function basename(p: string): string {
+ const parts = p.split(/[\\/]/)
+ return parts[parts.length - 1] || p
+}
+
+/**
+ * Map a raw hook tool invocation to a human "what it's doing now" line (spec: mobile-usage-inbox).
+ * Pure; clipped to INBOX_ACTIVITY_MAX. Unknown tools fall back to "Using <tool>".
+ */
+export function toolActivity(toolName: string, toolInput: Record<string, unknown> | undefined): string {
+ const ti = toolInput ?? {}
+ const str = (v: unknown): string => (typeof v === 'string' ? v : '')
+ let out: string
+ switch (toolName) {
+ case 'Edit':
+ case 'Write':
+ case 'MultiEdit':
+ out = `Editing ${basename(str(ti.file_path)) || 'file'}`
+ break
+ case 'NotebookEdit':
+ out = `Editing ${basename(str(ti.notebook_path) || str(ti.file_path)) || 'notebook'}`
+ break
+ case 'Read':
+ out = `Reading ${basename(str(ti.file_path) || str(ti.notebook_path)) || 'file'}`
+ break
+ case 'Bash': {
+ const cmd = str(ti.command).replace(/\s+/g, ' ').trim()
+ out = `Running ${cmd ? clip(cmd, 60) : 'command'}`
+ break
+ }
+ case 'Grep':
+ case 'Glob':
+ out = `Searching ${str(ti.pattern) || '…'}`
+ break
+ case 'Task':
+ out = `Delegating: ${str(ti.description) || str(ti.subagent_type) || '…'}`
+ break
+ case 'WebFetch': {
+ const url = str(ti.url)
+ let host = url
+ try {
+ host = new URL(url).host
+ } catch {
+ // not a parseable URL — show the raw string
+ }
+ out = `Fetching ${host || '…'}`
+ break
+ }
+ case 'WebSearch':
+ out = `Fetching ${str(ti.query) || '…'}`
+ break
+ default:
+ out = `Using ${toolName}`
+ }
+ return clip(out, INBOX_ACTIVITY_MAX)
+}
+
+/** Newest UNRESOLVED approval/question event for a node (dedup lookup), or undefined. */
+function newestUnresolved(events: ReadonlyArray<InboxEvent>, nodeId: string): InboxEvent | undefined {
+ for (let i = events.length - 1; i >= 0; i--) {
+ const e = events[i]
+ if (e.nodeId === nodeId && !e.resolved && (e.kind === 'approval' || e.kind === 'question')) return e
+ }
+ return undefined
+}
+
// ---- Stateful singleton (production side) --------------------------------------------------
const state = new Map<string, MirrorEntry>()
@@ -149,6 +401,35 @@ const flushListeners = new Set<(doc: MirrorFile) => void>()
// Supplies the host-level settings block, consulted fresh on every flush (so a mid-session
// permission-mode / account change is picked up without re-wiring). Null = no block written.
let settingsProvider: (() => MirrorSettings | undefined) | null = null
+// Supplies the local-accounts usage block, consulted fresh on every flush (so a poll landing
+// between flushes is picked up). Null = no `usage` block written (byte-identical old shape).
+let usageProvider: (() => MirrorUsage | undefined) | null = null
+
+// ---- Inbox state (feed + per-node activity) ------------------------------------------------
+// The event feed is oldest→newest and capped at INBOX_EVENTS_CAP; `inboxNodes` is the per-node
+// "what it's doing right now" (activity from raw tool events + context% from context-tail). Both
+// ride the same single write path as the main node map — there is one debounced flush.
+let inboxEvents: InboxEvent[] = []
+const inboxNodes = new Map<string, InboxNodeNow>()
+let inboxSeq = 0
+
+function pushInboxEvent(e: Omit<InboxEvent, 'id'>): void {
+ const id = `${e.ts}-${++inboxSeq}`
+ inboxEvents.push({ id, ...e })
+ // Cap the feed from the front (oldest fall off).
+ if (inboxEvents.length > INBOX_EVENTS_CAP) {
+ inboxEvents = inboxEvents.slice(inboxEvents.length - INBOX_EVENTS_CAP)
+ }
+}
+
+/** Mark a node's unresolved approval/question events resolved (it left blocked/waiting). */
+function resolveUnresolvedFor(nodeId: string): void {
+ for (const e of inboxEvents) {
+ if (e.nodeId === nodeId && !e.resolved && (e.kind === 'approval' || e.kind === 'question')) {
+ e.resolved = true
+ }
+ }
+}
/**
* Wire (or clear with `null`) the provider for the additive host-level settings block. Called
@@ -168,6 +449,24 @@ function safeSettings(): MirrorSettings | undefined {
}
}
+/**
+ * Wire (or clear with `null`) the provider for the additive `usage` block. Called once per shell
+ * on launch; absent ⇒ the mirror writes no `usage` key. The provider is consulted fresh on every
+ * flush, so a usage poll that lands between flushes is picked up without re-wiring.
+ */
+export function setMirrorUsageProvider(p: (() => MirrorUsage | undefined) | null): void {
+ usageProvider = p
+}
+
+/** Read the usage provider, failing open (a throwing/absent provider yields no block). */
+function safeUsage(): MirrorUsage | undefined {
+ try {
+ return usageProvider?.() ?? undefined
+ } catch {
+ return undefined
+ }
+}
+
/**
* Subscribe to every flush's built doc (fires even when the local disk write fails — the doc is
* the product, the file is one consumer of it). Returns an unsubscribe. Feeds the SSH-host
@@ -196,16 +495,130 @@ function resolveFile(): string | null {
}
}
-/** Fold a normalized agent event into the mirror and schedule a debounced write. */
+/** Fold a normalized agent event into the mirror (main state + inbox feed) and schedule a
+ * debounced write. Called with EVERY normalized event by both shells. */
export function recordAgentEvent(ev: NormalizedAgentEvent): void {
if (!ev?.nodeId) return
- state.set(ev.nodeId, reduceEntry(state.get(ev.nodeId), ev, Date.now()))
+ const nodeId = ev.nodeId
+ const now = Date.now()
+ const prev = state.get(nodeId)
+ const prevState = prev?.state
+ const next = reduceEntry(prev, ev, now)
+ state.set(nodeId, next)
+ produceInboxFromState(nodeId, ev, prevState, next.state, now)
scheduleWrite()
}
-/** Remove a node (call on permanent destroy). Schedules a write so the file drops it. */
+/**
+ * Inbox event production off a state transition (spec: mobile-usage-inbox). Reads the transition
+ * `prevState → nextState` that `reduceEntry` just computed (so the same done-holdoff / newTurn
+ * semantics gate the feed as gate the badge — no duplicate done inside a holdoff, no resurrection).
+ */
+function produceInboxFromState(
+ nodeId: string,
+ ev: NormalizedAgentEvent,
+ prevState: AgentState | undefined,
+ nextState: AgentState | undefined,
+ now: number
+): void {
+ // Leaving blocked/waiting (any newer, different state — incl. a session reset to idle) resolves
+ // that node's pending approval/question cards; they move to the phone's archive.
+ if ((prevState === 'blocked' || prevState === 'waiting') && nextState !== prevState) {
+ resolveUnresolvedFor(nodeId)
+ }
+ const baseEvent = { ts: now, nodeId, agentId: ev.agentId, sessionId: ev.sessionId }
+ // approval/question dedup is TITLE-based (not edge-based): a re-asserted blocked with the SAME
+ // ask is a no-op, but a genuinely different ask still lands — so the guard can't be a plain
+ // "same-state, skip". `done` alone is edge-guarded (one per turn).
+ if (nextState === 'blocked') {
+ const title = firstLine(ev.lastMessage, INBOX_TITLE_MAX) || 'Needs approval'
+ if (newestUnresolved(inboxEvents, nodeId)?.title === title) return
+ pushInboxEvent({ ...baseEvent, kind: 'approval', title })
+ } else if (nextState === 'waiting') {
+ const title = firstLine(ev.lastMessage, INBOX_TITLE_MAX) || 'Waiting for input'
+ if (newestUnresolved(inboxEvents, nodeId)?.title === title) return
+ pushInboxEvent({ ...baseEvent, kind: 'question', title })
+ } else if (nextState === 'done' && prevState !== 'done') {
+ // The turn ended: emit one `done` on the edge into done (reduceEntry's holdoff keeps a late
+ // working from re-entering, and the normalizer collapses an Esc-spam into one done).
+ const detail = firstLine(ev.lastMessage, INBOX_DETAIL_MAX) || undefined
+ pushInboxEvent({
+ ...baseEvent,
+ kind: 'done',
+ title: ev.interrupted ? 'Stopped' : 'Finished',
+ ...(detail ? { detail } : {}),
+ ...(ev.interrupted ? { interrupted: true } : {})
+ })
+ // A finished turn is no longer "doing" anything — clear its live activity line.
+ clearActivity(nodeId, now)
+ }
+}
+
+/** Clear a node's live activity (keep any contextPercent). Idempotent; no-op if nothing set. */
+function clearActivity(nodeId: string, now: number): void {
+ const n = inboxNodes.get(nodeId)
+ if (!n || n.activity === undefined) return
+ inboxNodes.set(nodeId, { contextPercent: n.contextPercent, updatedAt: now })
+}
+
+/**
+ * Fold a RAW hook tool event into the per-node "what it's doing now" line (spec:
+ * mobile-usage-inbox). Called from the shells' `setRawListener` for claude events. PreToolUse sets
+ * the activity; Stop / SessionEnd clear it. Other events are ignored. Schedules a write only when
+ * the line actually changes (raw POSTs are bursty).
+ */
+export function recordRawToolEvent(nodeId: string, payload: Record<string, unknown>): void {
+ if (!nodeId) return
+ const hook = typeof payload.hook_event_name === 'string' ? payload.hook_event_name : ''
+ const now = Date.now()
+ if (hook === 'PreToolUse') {
+ const toolName = typeof payload.tool_name === 'string' ? payload.tool_name : ''
+ if (!toolName) return
+ const toolInput =
+ payload.tool_input && typeof payload.tool_input === 'object'
+ ? (payload.tool_input as Record<string, unknown>)
+ : undefined
+ const activity = toolActivity(toolName, toolInput)
+ const cur = inboxNodes.get(nodeId)
+ if (cur?.activity === activity && cur?.tool === toolName) return // no change
+ inboxNodes.set(nodeId, { activity, tool: toolName, contextPercent: cur?.contextPercent, updatedAt: now })
+ scheduleWrite()
+ } else if (hook === 'Stop' || hook === 'SessionEnd') {
+ const before = inboxNodes.get(nodeId)?.activity
+ clearActivity(nodeId, now)
+ if (before !== undefined) scheduleWrite()
+ }
+}
+
+/**
+ * Record a node's context-window fill (0–100) from the context-tail (spec: mobile-usage-inbox).
+ * Called where the shells broadcast IPC.contextUpdate. Schedules a write only on change.
+ */
+export function recordContextUsage(nodeId: string, percent: number): void {
+ if (!nodeId || typeof percent !== 'number' || !Number.isFinite(percent)) return
+ const clamped = Math.min(100, Math.max(0, percent))
+ const cur = inboxNodes.get(nodeId)
+ if (cur?.contextPercent === clamped) return
+ inboxNodes.set(nodeId, { activity: cur?.activity, tool: cur?.tool, contextPercent: clamped, updatedAt: Date.now() })
+ scheduleWrite()
+}
+
+/**
+ * Remove a node (call on permanent destroy). Its `nodes` entries (main + inbox activity) drop,
+ * but its inbox EVENTS stay as feed history — marked resolved so the phone archives them.
+ * Schedules a write so the file reflects the removal.
+ */
export function clearNode(nodeId: string): void {
- if (state.delete(nodeId)) scheduleWrite()
+ let changed = state.delete(nodeId)
+ if (inboxNodes.delete(nodeId)) changed = true
+ // History stays; unresolved cards for a gone node can never be answered → archive them.
+ for (const e of inboxEvents) {
+ if (e.nodeId === nodeId && !e.resolved && (e.kind === 'approval' || e.kind === 'question')) {
+ e.resolved = true
+ changed = true
+ }
+ }
+ if (changed) scheduleWrite()
}
function scheduleWrite(): void {
@@ -223,9 +636,12 @@ export async function flush(): Promise<void> {
const file = resolveFile()
if (!file) return
const now = Date.now()
- const doc = buildFile(Object.fromEntries(state), now, undefined, safeSettings())
+ const inbox: MirrorInbox = { events: inboxEvents, nodes: Object.fromEntries(inboxNodes) }
+ const doc = buildFile(Object.fromEntries(state), now, undefined, safeSettings(), safeUsage(), inbox)
// Also drop expired entries from memory so the map itself can't grow without bound.
for (const [id, e] of state) if (now - e.updatedAt > EXPIRE_MS) state.delete(id)
+ // Prune stale per-node activity the same way (events stay — they are capped feed history).
+ for (const [id, n] of inboxNodes) if (now - n.updatedAt > EXPIRE_MS) inboxNodes.delete(id)
for (const cb of flushListeners) {
try {
cb(doc)
@@ -244,7 +660,7 @@ export async function flush(): Promise<void> {
// ---- Test helpers --------------------------------------------------------------------------
-/** Reset all module state (in-memory map + config + listeners). Test-only. */
+/** Reset all module state (in-memory map + config + listeners + inbox). Test-only. */
export function _resetForTest(): void {
state.clear()
targetFile = null
@@ -252,9 +668,18 @@ export function _resetForTest(): void {
writeTimer = null
flushListeners.clear()
settingsProvider = null
+ usageProvider = null
+ inboxEvents = []
+ inboxNodes.clear()
+ inboxSeq = 0
}
/** Snapshot the in-memory map. Test-only. */
export function _snapshot(): Record<string, MirrorEntry> {
return Object.fromEntries(state)
}
+
+/** Snapshot the in-memory inbox. Test-only. */
+export function _inboxSnapshot(): MirrorInbox {
+ return { events: inboxEvents.map((e) => ({ ...e })), nodes: Object.fromEntries(inboxNodes) }
+}
diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.ts
index 6f4b5d49e..7f4d510db 100644
--- a/src/core/usage/usage-service.ts
+++ b/src/core/usage/usage-service.ts
@@ -183,6 +183,17 @@ export interface UsageServiceOptions {
* informational, so a stale snapshot beats polling an idle app into 429s.
*/
shouldPoll?: () => boolean
+ /**
+ * Local managed accounts to poll ALONGSIDE the system account on the background cadence (spec:
+ * mobile-usage-inbox). Returns their account ids (settings' non-`host`, non-`pending` claude
+ * accounts). The shell owns this because settings live in the shell. Absent ⇒ system only.
+ */
+ localAccounts?: () => string[]
+ /**
+ * Fired after any account's cache is (re)populated — the mirror wires this to a flush so the
+ * phone-facing `usage` block refreshes when a poll lands. Best-effort; must never throw.
+ */
+ onCacheUpdate?: () => void
}
export interface UsageService {
@@ -192,6 +203,8 @@ export interface UsageService {
refresh(accountId?: string): Promise<ClaudeUsage>
/** Refresh the system account if the debounce has elapsed — for shell focus/attach events. */
refreshIfStale(): void
+ /** Every cached usage row (system account first). Feeds the agent-status mirror's `usage` block. */
+ snapshot(): { accountId: string | null; usage: ClaudeUsage }[]
/** Stop the poll timer. */
dispose(): void
}
@@ -213,6 +226,12 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService
lastFetchAt.set(key, u.updatedAt)
// Only the system account feeds the push channel — the collapsed chip tracks it.
if (key === '') platform().broadcast(IPC.usageUpdate, u)
+ // Notify the mirror (fail-open) so its phone-facing `usage` block re-assembles from the cache.
+ try {
+ opts.onCacheUpdate?.()
+ } catch {
+ // a mirror flush must never break the usage cache update
+ }
}
const run = async (accountId?: string): Promise<ClaudeUsage> => {
@@ -278,14 +297,28 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService
return runProviders()
})
+ // Poll the system account AND every local managed account (spec: mobile-usage-inbox), so the
+ // agent-status mirror can advertise per-account usage to the phone — not just the collapsed chip's
+ // system row. Each account is one request per cadence; the request-budget gate (`shouldPoll`)
+ // still fronts the whole sweep.
+ const pollAll = (): void => {
+ if (!shouldPoll()) return
+ void run()
+ let ids: string[] = []
+ try {
+ ids = opts.localAccounts?.() ?? []
+ } catch {
+ ids = [] // a throwing provider must never break the poll
+ }
+ for (const id of ids) if (id) void run(id)
+ }
+
// The warm-up fetch goes through the same gate as the poll: it IS a poll, just the first one.
// On desktop a focused window warms the cache before the pill mounts; on the server, boot
// happens with no browser attached, so this correctly does nothing until someone connects
// (and UsageIndicator fetches on mount regardless, so nothing is lost either way).
- if (shouldPoll()) void run()
- const interval = setInterval(() => {
- if (shouldPoll()) void run()
- }, POLL_MS)
+ pollAll()
+ const interval = setInterval(pollAll, POLL_MS)
// Node keeps the process alive for pending timers; the server shell should exit on its own terms.
interval.unref?.()
@@ -295,6 +328,11 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService
refreshIfStale: () => {
if (Date.now() - (lastFetchAt.get('') ?? 0) >= REFETCH_DEBOUNCE_MS) void run()
},
+ snapshot: () =>
+ // System account (key '') first, then managed accounts in insertion order.
+ [...last.entries()]
+ .sort((a, b) => (a[0] === '' ? -1 : b[0] === '' ? 1 : 0))
+ .map(([key, usage]) => ({ accountId: key === '' ? null : key, usage })),
dispose: () => clearInterval(interval)
}
}
diff --git a/src/main/claude-usage.ts b/src/main/claude-usage.ts
index f8e634153..9bed18b67 100644
--- a/src/main/claude-usage.ts
+++ b/src/main/claude-usage.ts
@@ -3,14 +3,27 @@
// the Server Edition boots the same code. All that is left here is the one thing core cannot
// know: whether a desktop window is focused.
import type { BrowserWindow } from 'electron'
-import { startUsageService } from '../core/usage/usage-service'
+import { startUsageService, type UsageService } from '../core/usage/usage-service'
export { resolveClaudeAccessToken } from '../core/usage/usage-service'
-export function initClaudeUsage(win: BrowserWindow): void {
+/** Extra usage-service wiring the shell owns: the local managed accounts to poll for the mobile
+ * `usage` mirror block, and the mirror-flush callback fired on every cache update. */
+export interface InitClaudeUsageOpts {
+ localAccounts?: () => string[]
+ onCacheUpdate?: () => void
+}
+
+/** Start the usage service on the focused-window poll gate and return it, so the caller can wire
+ * the agent-status mirror's `usage` provider off its `snapshot()`. */
+export function initClaudeUsage(win: BrowserWindow, opts: InitClaudeUsageOpts = {}): UsageService {
// Poll only while the window is focused, and re-check on focus — the usage endpoint has a
// tight request budget and this data is informational, so an unattended app should not spend it.
- const service = startUsageService({ shouldPoll: () => win.isFocused() })
+ const service = startUsageService({
+ shouldPoll: () => win.isFocused(),
+ localAccounts: opts.localAccounts,
+ onCacheUpdate: opts.onCacheUpdate
+ })
const onFocus = (): void => service.refreshIfStale()
win.on('focus', onFocus)
@@ -20,4 +33,5 @@ export function initClaudeUsage(win: BrowserWindow): void {
win.off('focus', onFocus)
service.dispose()
})
+ return service
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 187609576..2f2515e13 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -22,7 +22,11 @@ import {
onMirrorFlush,
flush as flushAgentStatusMirror,
recordAgentEvent,
+ recordRawToolEvent,
+ recordContextUsage,
setMirrorSettingsProvider,
+ setMirrorUsageProvider,
+ buildMirrorUsage,
type MirrorSettings
} from '../core/agent-status-mirror'
import { initRemoteStatusPush } from './remote-ssh/remote-status-push'
@@ -754,6 +758,15 @@ app.whenReady().then(async () => {
}
const contextTail = createContextTail((payload) => {
if (!win.isDestroyed()) win.webContents.send(IPC.contextUpdate, payload)
+ // Feed the mirror's per-node context ring (mobile-usage-inbox). The context tail keys by
+ // sessionId; map it back to the node via the raw-listener's nodeId↔sessionId association.
+ const cw = payload as { sessionId?: string; usedPercent?: number }
+ for (const [nid, sid] of nodeContextSession) {
+ if (sid === cw.sessionId && typeof cw.usedPercent === 'number') {
+ recordContextUsage(nid, cw.usedPercent)
+ break
+ }
+ }
}, { onTaskNotification })
// Remote (SSH-project) counterparts: a node whose pty runs on a remote host has its Claude
// transcript on that host, so its meter / subagent transcript / search must read over the
@@ -950,6 +963,10 @@ app.whenReady().then(async () => {
const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])
hookServer.setRawListener((agentId, nodeId, payload) => {
if (agentId !== 'claude') return
+ // Mirror the per-node "what it's doing now" activity line for the phone (mobile-usage-inbox).
+ // Runs BEFORE the local/remote split so it covers remote (SSH) nodes too — it needs only
+ // tool_name/tool_input, never the transcript path the split routes on.
+ recordRawToolEvent(nodeId, payload)
const p = payload as {
hook_event_name?: string
session_id?: string
@@ -1118,7 +1135,21 @@ app.whenReady().then(async () => {
initContextLink(ptyManager)
initCanvasControl()
- initClaudeUsage(win)
+ // Usage service + the mobile `usage` mirror block (mobile-usage-inbox): poll all local managed
+ // accounts alongside the system account, and re-flush the mirror on every cache update. The
+ // provider pairs the service's cache with the settings account labels at flush time; SSH slices
+ // drop it (filterMirrorForNodes) — a host answers only for its own local credentials.
+ const localClaudeAccountIds = (): string[] =>
+ (settingsStore.get().claudeAccounts ?? []).filter((a) => !a.host && !a.pending).map((a) => a.id)
+ const usageService = initClaudeUsage(win, {
+ localAccounts: localClaudeAccountIds,
+ onCacheUpdate: () => {
+ void flushAgentStatusMirror()
+ }
+ })
+ setMirrorUsageProvider(() =>
+ buildMirrorUsage(usageService.snapshot(), settingsStore.get().claudeAccounts ?? [], Date.now())
+ )
initTelemetry(() => settingsStore.get())
// Declared before initLicense so its onChange hook can re-reconcile the standing host once the
// async launch-time entitlement refresh settles (fixes the boot race where Pro isn't yet valid
diff --git a/src/server/agent-status.ts b/src/server/agent-status.ts
index 4857ae2d3..3b4f15c8f 100644
--- a/src/server/agent-status.ts
+++ b/src/server/agent-status.ts
@@ -10,7 +10,7 @@
import { resolve } from 'path'
import { homedir } from 'os'
import { hookServer } from '../core/agents/hook-server'
-import { recordAgentEvent } from '../core/agent-status-mirror'
+import { recordAgentEvent, recordRawToolEvent, recordContextUsage } from '../core/agent-status-mirror'
import { createSubagentTail, type SubagentTail } from '../core/subagent-tail'
import { createContextTail, type ContextTail, type TaskNotification } from '../core/context-tail'
import { setNodeTranscript } from '../core/context-link'
@@ -79,6 +79,15 @@ export function wireAgentStatus(platform: ServerPlatform, opts: WireAgentStatusO
createContextTail(
(payload) => {
platform.broadcast(IPC.contextUpdate, payload)
+ // Feed the mirror's per-node context ring (mobile-usage-inbox). The context tail keys by
+ // sessionId; map it back to the node via the same association the raw listener records.
+ const cw = payload as { sessionId?: string; usedPercent?: number }
+ for (const [nid, sid] of nodeContextSession) {
+ if (sid === cw.sessionId && typeof cw.usedPercent === 'number') {
+ recordContextUsage(nid, cw.usedPercent)
+ break
+ }
+ }
},
{ onTaskNotification }
)
@@ -103,6 +112,9 @@ export function wireAgentStatus(platform: ServerPlatform, opts: WireAgentStatusO
const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])
hooks.setRawListener((agentId, nodeId, payload) => {
if (agentId !== 'claude') return
+ // Mirror the per-node "what it's doing now" activity line for the phone (mobile-usage-inbox).
+ // Independent of the transcript-tailing below (no path needed), so it runs first.
+ recordRawToolEvent(nodeId, payload)
const p = payload as {
hook_event_name?: string
session_id?: string
diff --git a/src/server/handlers/index.ts b/src/server/handlers/index.ts
index aaff8030e..c17c62dfa 100644
--- a/src/server/handlers/index.ts
+++ b/src/server/handlers/index.ts
@@ -5,6 +5,11 @@ import { generateCommitMessage } from '../../core/commit-message'
import { registerFsHandlers } from '../../core/fs-handlers'
import { claudeCliCaps, registerClaudeCliIpc } from '../../core/claude-cli'
import { startUsageService } from '../../core/usage/usage-service'
+import {
+ setMirrorUsageProvider,
+ buildMirrorUsage,
+ flush as flushAgentStatusMirror
+} from '../../core/agent-status-mirror'
import { IPC } from '../../shared/ipc'
/** Register the Phase-3a handler surface (fs + git + commit) on the server platform.
@@ -40,7 +45,23 @@ export function registerCoreHandlers(
// Claude subscription usage. Previously desktop-only — the browser bridge answered `null`, so
// the pill never rendered in the Server Edition. Poll only while a browser is attached: with
// no client there is nobody to show it to, and the usage endpoint's request budget is tight.
- startUsageService({ shouldPoll: () => platform.clientIds().length > 0 })
+ // Also feeds the agent-status mirror's per-account `usage` block for the phone (mobile-usage-inbox):
+ // poll all local managed accounts, and re-flush the mirror on every cache update.
+ const localClaudeAccountIds = (): string[] =>
+ (deps.getSettings().claudeAccounts ?? []).filter((a) => !a.host && !a.pending).map((a) => a.id)
+ const usageService = startUsageService({
+ shouldPoll: () => platform.clientIds().length > 0,
+ localAccounts: localClaudeAccountIds,
+ onCacheUpdate: () => {
+ void flushAgentStatusMirror()
+ }
+ })
+ // The provider is consulted fresh at every flush, pairing the usage service's cache with the
+ // settings account labels. Dropped from SSH slices by filterMirrorForNodes (no SSH server-side
+ // anyway). Wired here (not index.ts) since the usage service is created here.
+ setMirrorUsageProvider(() =>
+ buildMirrorUsage(usageService.snapshot(), deps.getSettings().claudeAccounts ?? [], Date.now())
+ )
return { gitService }
}