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: show Codex usage and context for SSH sessions

review0d4a32c9de8f
diff --git a/CLAUDE.md b/CLAUDE.md
index 81b4bd1be..931d0f989 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1696,9 +1696,9 @@ else, and its context links must keep classifying across restarts).
(`isSafeRemoteTranscriptPath`) and cache, reused as a second consumer rather than copied. Its
"could not resolve" is **terminal**: falling through to any local resolver would search THIS
machine for a file that only ever existed on the other one, and claude's cwd fallback would
- happily meter an unrelated local session under the remote node's id. Remote metering is
- claude-only, the same boundary the hook raw-listener already draws (`remote-context-tail.ts`
- parses claude's records; the locator searches claude's roots).
+ happily meter an unrelated local session under the remote node's id. Remote Codex uses its own account-scoped locator and parser over the same bounded SSH
+ reader. Its reported transcript window wins; Claude estimates must never supply a Codex
+ denominator. Unresolved/disconnected remote nodes cannot fall through to local readers.
- **Nothing negative is ever cached.** A clean miss and a failed ssh call are indistinguishable to
the locator, so both cache NOTHING and the next mount retries in full — a momentarily dead
ControlMaster must not be remembered as "this session has no transcript", or the meter stays
@@ -3161,7 +3161,7 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
- **The usage indicator is scoped to the ACTIVE project** (`renderer/lib/usageScope.ts`, pure +
unit-tested) — it describes **the machine that project runs on**, and nothing else. A local
project shows this machine (system + managed local accounts + the billing providers, whose
- credentials are all local); an **SSH project shows only that host's Claude accounts** — no local
+ credentials are all local); an **SSH project shows that host's Claude and Codex accounts** — no local
Claude, no local providers, no other host. Without this the panel showed every source at once:
each addition was individually reasonable and the sum was unreadable, numbers from three
machines sharing one line with nothing saying which was which. Deliberately NOT narrowed to the
@@ -3216,6 +3216,19 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
pointless), and no keychain leg exists remotely (a headless macOS host would hang on the prompt,
so a mac host reports nothing).
+- **Codex SSH usage** (`core/usage/remote-codex-usage.ts`) uses host-side Node JSON parsing
+ and curl, reusing the local Codex quota mapper. Read only `tokens.access_token` and
+ `tokens.account_id`; pass headers through stdin, disable curl config/redirects, and return
+ only sanitized quota fields. Never download credentials, refresh tokens, or launch a remote
+ app-server just to refresh usage. The host needs Node and curl; missing tools/transport or
+ malformed responses are errors, not proof of a logged-out account. System reads use the
+ host login environment's `CODEX_HOME`; managed reads use the validated account's remote
+ home. Cache identity includes provider, host, account and connection/home identity.
+ Remote Codex rows obey the Codex visibility setting and carry no Claude default-account
+ or bulk-move actions. Desktop supports SSH reads; Server Edition keeps its local core
+ readers and absent SSH dependency. The private mobile reader is separate. Device checks:
+ `docs/codex-ssh-metrics.md`.
+
### Adding a new agent (or a new model) — what to watch out for
Every rule below is a mistake the grok branch or the codex/gemini-parity branch **actually made**, and
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 30a0f9faf..5af144a05 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -877,3 +877,9 @@ Held approval attention must not replace subagent, recurring or background-task
state evidence from those lifecycle hooks. A parent may ask several questions while a child ticket
is outstanding: track each new picker and preserve child approval cards independently, including
when their display titles match. Answering either resolves only that question or ticket.
+
+SSH Codex metrics must stay scoped to the host and account being read. Credentials and quota
+HTTP requests remain on that host; only sanitized usage returns over SSH. Never route a failed
+remote context lookup into a local transcript reader, or reuse Claude's token formula/window
+estimate for Codex. The system account follows the host login environment; managed accounts
+use their validated private home. Usage refresh must not start or repair a shared Codex daemon.
diff --git a/docs/codex-ssh-metrics.md b/docs/codex-ssh-metrics.md
new file mode 100644
index 000000000..06211da49
--- /dev/null
+++ b/docs/codex-ssh-metrics.md
@@ -0,0 +1,54 @@
+# Codex metrics on SSH projects
+
+The usage popover and the context meter answer different questions. Usage reports the
+remote account's subscription limits; context reports the current conversation's input
+tokens against the window recorded by Codex itself. Neither should read the desktop's
+credentials or substitute another local conversation when the host cannot be reached.
+
+Claude's existing SSH readers provide the transport pattern. Codex keeps its own account
+layout, authentication format and token parser. In particular, cached input is already
+included in Codex input tokens, and cumulative session usage is not context occupancy.
+
+## Reading and identity
+
+Quota requests execute in the host login environment and require Node and curl. The
+system account uses that environment's `CODEX_HOME` (otherwise `$HOME/.codex`); managed
+accounts use the validated private remote account home. The reader does not refresh auth
+or start a Codex daemon. Missing tools and failed reads produce an error state rather than
+invented zero usage. The existing Codex visibility switch covers both local and SSH rows.
+
+Context observations carry the requesting node ID as well as the conversation ID. They
+are kept separately from local session snapshots and are not restored from browser storage.
+A changed account, connection or transcript replaces the tracking generation. An explicit
+mount-time lookup rechecks the host's configured home, while ordinary hook events do not
+replay unchanged data. No transcript-reported window means no fabricated Codex denominator.
+
+## Surfaces
+
+- Desktop: SSH usage belongs to the active project's host. The context meter is shared by
+ terminal nodes and the kanban terminal modal.
+- Server Edition: the server reads its own local Codex accounts and transcripts. It has no
+ desktop SSH project manager; the remote usage dependency remains absent.
+- Mobile companion: its independent SSH reader is outside this repository. These desktop
+ changes do not implement an iOS usage panel or context reader.
+
+## Device verification
+
+Automated shell fixtures exercise generated commands with fake homes and transports.
+They do not establish compatibility with a live subscription endpoint or every SSH shell.
+Before claiming device verification, record the host OS, shell and Codex version, then:
+
+1. Connect a Desktop SSH project whose system Codex account is signed in. Open usage and
+ compare the session and weekly buckets with that account's own usage readout.
+2. Add a managed Codex account on that host. Verify each row remains attributed to its own
+ account, including after refresh, project switches and a temporary disconnection.
+3. Use a system installation with a relocated `CODEX_HOME`; verify the metrics follow the
+ host's configured home rather than the desktop environment.
+4. Start a Codex turn. Compare the context popover with the last input-token record and
+ `model_context_window` in that conversation's rollout. Repeat in the kanban modal.
+5. Restart Desktop with an idle, continuing SSH session. The mount-time read should restore
+ its meter without requiring a new prompt. A disconnected session must not read locally.
+6. Repeat with Linux and macOS SSH hosts. Windows Desktop should preserve POSIX remote
+ paths; a native Windows OpenSSH target is not implied by the existing POSIX SSH transport.
+
+Do not include credentials or raw authenticated responses in verification reports.
diff --git a/src/core/codex-session.ts b/src/core/codex-session.ts
index c97930e53..598b4e77a 100644
--- a/src/core/codex-session.ts
+++ b/src/core/codex-session.ts
@@ -71,7 +71,7 @@ export function pickCodexUsage(rollout: string | string[]): AgentUsage | null {
* INITIAL_READ_CAP of the file, so in practice the model is settled on the very first tick and
* sticks. Claiming a model we did not read would be worse than reporting none.
*/
-function codexModel(text: string | string[]): string | null {
+export function codexContextModel(text: string | string[]): string | null {
return latestJsonLineWhere(text, '"turn_context"', (o) => {
if (o.type !== 'turn_context') return null
const model = (o.payload as { model?: unknown } | undefined)?.model
@@ -85,5 +85,5 @@ export function codexContextParse(
): { used: number; window: number | null; model: string | null } | null {
const u = pickCodexUsage(text)
if (!u) return null
- return { used: u.usedTokens, window: u.windowTokens, model: codexModel(text) }
+ return { used: u.usedTokens, window: u.windowTokens, model: codexContextModel(text) }
}
diff --git a/src/core/context-ensure.ts b/src/core/context-ensure.ts
index cbcbdc3ae..01c16394b 100644
--- a/src/core/context-ensure.ts
+++ b/src/core/context-ensure.ts
@@ -56,6 +56,8 @@ export interface ContextEnsureQuery {
export type RemoteEnsureOutcome = 'tracked' | 'unresolved'
export interface ContextEnsureDeps {
+ /** Transport/account generation for remote requests; a reconnect must not join an older read. */
+ scopeKey?(q: ContextEnsureQuery): string | undefined
/**
* The tail that meters this agent locally, or `undefined` when the agent has no local
* rehydration path. One tail per agent, each with its own `parse` — see `createContextTail`.
@@ -128,9 +130,7 @@ export function registerContextEnsureIpc(deps: ContextEnsureDeps): void {
): Promise<void> => {
if (!sessionId || !SESSION_ID_RE.test(sessionId)) return
const q: ContextEnsureQuery = { sessionId, cwd, accountId, nodeId, agentId }
- // `SESSION_ID_RE` admits no separator character, so no pair of distinct (agent, session)
- // inputs can collide on this key.
- const key = `${agentId ?? ''}/${sessionId}`
+ const key = JSON.stringify([agentId, sessionId, nodeId, accountId, cwd, deps.scopeKey?.(q)])
if (inFlight.has(key)) return
inFlight.add(key)
try {
diff --git a/src/core/remote-context-ensure.ts b/src/core/remote-context-ensure.ts
new file mode 100644
index 000000000..8b444bdad
--- /dev/null
+++ b/src/core/remote-context-ensure.ts
@@ -0,0 +1,24 @@
+import type { ContextEnsureQuery, RemoteEnsureOutcome } from './context-ensure'
+
+/** The shell supplies transports; agent selection and the no-local-fallback boundary are shared
+ * executable code. Codex and Claude must never share their locator or token parser. */
+export function createRemoteContextEnsure<Ref>(deps: {
+ isRemoteNode(nodeId: string): boolean
+ codex(q: ContextEnsureQuery): Promise<RemoteEnsureOutcome | null>
+ claude: { pathFor(sessionId: string): string | undefined; replay(sessionId: string): void; track(sessionId: string, ref: Ref): void }
+ locateClaude(q: ContextEnsureQuery): Promise<Ref | undefined>
+}): (q: ContextEnsureQuery) => Promise<RemoteEnsureOutcome | null> {
+ return async q => {
+ if (!q.nodeId || !deps.isRemoteNode(q.nodeId)) return null
+ if (q.agentId === 'codex') return await deps.codex(q) ?? 'unresolved'
+ if (q.agentId && q.agentId !== 'claude') return 'unresolved'
+ if (deps.claude.pathFor(q.sessionId)) {
+ deps.claude.replay(q.sessionId)
+ return 'tracked'
+ }
+ const ref = await deps.locateClaude(q)
+ if (!ref) return 'unresolved'
+ deps.claude.track(q.sessionId, ref)
+ return 'tracked'
+ }
+}
diff --git a/src/core/remote-ssh/codex-context.test.ts b/src/core/remote-ssh/codex-context.test.ts
new file mode 100644
index 000000000..2bce6fc0a
--- /dev/null
+++ b/src/core/remote-ssh/codex-context.test.ts
@@ -0,0 +1,177 @@
+import { isKnownRemoteCodexAccount } from './codex-home'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { execFileSync } from 'child_process'
+import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import path from 'path'
+import { createRemoteCodexContext, remoteCodexTranscriptCommand, parseRemoteCodexTranscript, type RemoteCodexContextTarget } from './codex-context'
+import { remoteCodexHome } from '../codex-accounts-core'
+import { registerContextEnsureIpc } from '../context-ensure'
+import { fakePlatform } from '../platform-fake'
+import { initPlatform, resetPlatformForTests } from '../platform'
+import { IPC } from '../../shared/ipc'
+
+const sid = '46b36ce2-dd77-4f5e-a89e-4a0e831e83df'
+const target: RemoteCodexContextTarget = { conn: { host: 'fixture', user: 'u' }, controlPath: '/socket', remoteHome: '/home/u', accountId: 'a' }
+const file = `/remote-codex/sessions/2026/09/23/rollout-date-${sid}.jsonl`
+const reply = { code: 0, stdout: `/remote-codex/sessions\n${file}\n` }
+const query = { nodeId: 'node', sessionId: sid, agentId: 'codex', cwd: '/repo', accountId: 'a' }
+const payload = { session_id: sid, transcript_path: file, hook_event_name: 'Stop' }
+function harness() {
+ let current: RemoteCodexContextTarget | null | undefined = target
+ const tail = { track: vi.fn(), replay: vi.fn(), untrack: vi.fn() }
+ const run = vi.fn(async () => reply)
+ const onClear = vi.fn()
+ const knownAccount = vi.fn(() => true)
+ const controller = createRemoteCodexContext({ targetFor: () => current, knownAccount, run, tail, onClear })
+ return { controller, tail, run, onClear, knownAccount, set: (t: typeof current) => { current = t } }
+}
+afterEach(resetPlatformForTests)
+
+describe('remote Codex context routing', () => {
+ it.each(['miss', 'throw'])('an older ensure %s cannot clear a newer hook success', async outcome => {
+ const h = harness()
+ let finish!: (v: typeof reply) => void
+ let fail!: (reason: Error) => void
+ h.run.mockImplementationOnce(() => new Promise((resolve, reject) => { finish = resolve; fail = reject }))
+ const old = h.controller.ensure(query)
+ await Promise.resolve()
+ await h.controller.hook('node', payload)
+ const clears = h.onClear.mock.calls.length
+ if (outcome === 'miss') finish({ code: 1, stdout: '' })
+ else fail(new Error('fixture lookup failed'))
+ await old
+ expect(h.tail.untrack).not.toHaveBeenCalled()
+ expect(h.onClear).toHaveBeenCalledTimes(clears)
+ expect(h.controller.publish({ sessionId: JSON.stringify(['node', sid]), usedTokens: 10,
+ windowTokens: 100, usedPercent: 10, model: null, updatedAt: 1 })).toMatchObject({ nodeId: 'node' })
+ })
+ it('requires a completed managed account on the same SSH host', () => {
+ const accounts = [{ id: 'local', label: 'local' }, { id: 'other', label: 'other', host: 'elsewhere' },
+ { id: 'pending', label: 'pending', host: 'host', pending: true }, { id: 'ready', label: 'ready', host: 'host' }]
+ for (const id of ['local', 'other', 'pending', 'missing']) expect(isKnownRemoteCodexAccount(accounts, id, 'host')).toBe(false)
+ expect(isKnownRemoteCodexAccount(accounts, 'ready', 'host')).toBe(true)
+ })
+
+ it('rehydrates, explicitly replays and retries misses; no negative discovery cache', async () => {
+ const h = harness()
+ h.run.mockResolvedValueOnce({ code: 1, stdout: '' })
+ expect(await h.controller.ensure(query)).toBe('unresolved')
+ expect(await h.controller.ensure(query)).toBe('tracked')
+ expect(h.tail.track).toHaveBeenLastCalledWith(JSON.stringify(['node', sid]), expect.objectContaining({ path: file }))
+ await h.controller.ensure(query)
+ expect(h.run).toHaveBeenCalledTimes(3) // mount observes changed login CODEX_HOME, not a stale cached path
+ expect(h.tail.replay).toHaveBeenCalledTimes(2)
+ })
+
+ it('isolates equal session UUIDs by node and rejects late disconnected/account-removed publications', async () => {
+ const h = harness()
+ await h.controller.ensure(query)
+ await h.controller.ensure({ ...query, nodeId: 'other' })
+ expect(h.tail.track.mock.calls.map(c => c[0])).toEqual([JSON.stringify(['node', sid]), JSON.stringify(['other', sid])])
+ const usage = { sessionId: JSON.stringify(['other', sid]), usedTokens: 5, windowTokens: 10, usedPercent: 50, model: null, updatedAt: 1 }
+ expect(h.controller.publish(usage)).toMatchObject({ nodeId: 'other', sessionId: sid })
+ h.knownAccount.mockReturnValue(false)
+ expect(h.controller.publish(usage)).toBeUndefined()
+ expect(h.onClear).toHaveBeenCalledWith('other', sid)
+ })
+
+ it('does not read local files for known-but-disconnected remote nodes or unsupported remote roots', async () => {
+ const h = harness()
+ h.set(null)
+ const p = fakePlatform(); initPlatform(p)
+ const tailFor = vi.fn()
+ registerContextEnsureIpc({ tailFor, ensureRemote: h.controller.ensure })
+ await p.listeners[IPC.contextEnsure](sid, '/repo', 'a', 'node', 'codex')
+ expect(tailFor).not.toHaveBeenCalled()
+ expect(h.run).not.toHaveBeenCalled()
+ h.set({ ...target, accountId: '../escape' })
+ expect(await h.controller.ensure(query)).toBe('unresolved')
+ expect(h.run).not.toHaveBeenCalled()
+ h.set(target); h.knownAccount.mockReturnValue(false)
+ expect(await h.controller.ensure(query)).toBe('unresolved')
+ expect(h.run).not.toHaveBeenCalled()
+ })
+
+ it('ignores child rollouts, rejects stale in-flight generations and clears SessionEnd', async () => {
+ const h = harness()
+ await h.controller.hook('node', { ...payload, agent_id: 'child' })
+ expect(h.run).not.toHaveBeenCalled()
+ let finish!: (v: typeof reply) => void
+ h.run.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
+ const old = h.controller.hook('node', payload)
+ await Promise.resolve()
+ h.set({ ...target, controlPath: '/replacement', accountId: 'b' })
+ await h.controller.ensure(query)
+ finish(reply); await old
+ expect(h.tail.track).toHaveBeenCalledTimes(1)
+ expect(h.tail.track.mock.calls[0][1].controlPath).toBe('/replacement')
+ await h.controller.hook('node', { ...payload, hook_event_name: 'SessionEnd' })
+ expect(h.tail.untrack).toHaveBeenCalledWith(JSON.stringify(['node', sid]))
+ expect(h.onClear).toHaveBeenCalledWith('node', sid)
+ })
+
+ it('looks up system CODEX_HOME again on remount and replaces changed transcript roots', async () => {
+ const h = harness(); h.set({ ...target, accountId: undefined })
+ await h.controller.ensure(query)
+ const relocated = file.replace('/remote-codex/', '/relocated/')
+ h.run.mockResolvedValue({ code: 0, stdout: `/relocated/sessions\n${relocated}\n` })
+ await h.controller.ensure(query)
+ expect(h.tail.track).toHaveBeenLastCalledWith(JSON.stringify(['node', sid]), expect.objectContaining({ path: relocated }))
+ expect(h.onClear).toHaveBeenCalledWith('node', sid)
+ })
+
+ it('a released node can rehydrate immediately without joining its detached in-flight lookup', async () => {
+ const h = harness()
+ let finish!: (v: typeof reply) => void
+ h.run.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
+ const old = h.controller.ensure(query)
+ await Promise.resolve()
+ h.controller.release('node')
+ expect(await h.controller.ensure(query)).toBe('tracked')
+ finish(reply); await old
+ expect(h.run).toHaveBeenCalledTimes(2)
+ expect(h.tail.track).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe.skipIf(process.platform === 'win32')('real shell remote Codex transcript jail (fixture only)', () => {
+ let dir: string | undefined
+ afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }) })
+ function rollout(home: string): string {
+ const folder = path.join(home, 'sessions', '2026', '09', '23')
+ mkdirSync(folder, { recursive: true })
+ const result = path.join(folder, `rollout-date-${sid}.jsonl`)
+ writeFileSync(result, '{}\n')
+ return result
+ }
+ function run(t: RemoteCodexContextTarget, customHome: string, hookPath?: string): string | undefined {
+ const command = remoteCodexTranscriptCommand(t, sid, hookPath)!
+ // /bin/sh avoids the developer's shell profiles; environment is this disposable fixture's.
+ const stdout = execFileSync('/bin/sh', ['-c', command], { encoding: 'utf8', env: { PATH: process.env.PATH, SHELL: '/bin/sh', CODEX_HOME: customHome } })
+ return parseRemoteCodexTranscript(stdout, sid)
+ }
+ it('honors host CODEX_HOME; managed reads never fall back to system or another account', () => {
+ dir = mkdtempSync(path.join(tmpdir(), 'codex-remote-context-'))
+ const system = path.join(dir, 'custom home'), t = { ...target, remoteHome: dir }
+ const own = rollout(remoteCodexHome(dir, 'a')), other = rollout(remoteCodexHome(dir, 'b')), sys = rollout(system)
+ expect(run(t, system)).toBe(own)
+ expect(run(t, system, other)).toBeUndefined()
+ expect(run(t, system, sys)).toBeUndefined()
+ expect(run({ ...t, accountId: undefined }, system)).toBe(sys)
+ rmSync(own)
+ expect(run(t, system)).toBeUndefined()
+ })
+ it('rejects symlinked files/date directories and unsafe ids without reading outside the account', () => {
+ dir = mkdtempSync(path.join(tmpdir(), 'codex-remote-context-'))
+ const root = path.join(dir, 'custom'), outside = path.join(dir, 'outside')
+ const external = rollout(outside)
+ const own = rollout(root)
+ rmSync(own); symlinkSync(external, own)
+ expect(run({ ...target, accountId: undefined }, root)).toBeUndefined()
+ rmSync(path.dirname(own), { recursive: true }); symlinkSync(path.dirname(external), path.dirname(own))
+ expect(run({ ...target, accountId: undefined }, root)).toBeUndefined()
+ expect(remoteCodexTranscriptCommand(target, '../bad')).toBeUndefined()
+ expect(parseRemoteCodexTranscript(`/scope\n/scope/../secret-${sid}.jsonl`, sid)).toBeUndefined()
+ })
+})
diff --git a/src/core/remote-ssh/codex-context.ts b/src/core/remote-ssh/codex-context.ts
new file mode 100644
index 000000000..1ab0cdf3d
--- /dev/null
+++ b/src/core/remote-ssh/codex-context.ts
@@ -0,0 +1,161 @@
+import path from 'path'
+import type { ContextWindowUsage } from '../../shared/types'
+import type { SshConnection } from '../../shared/ssh'
+import { posixQuote } from '../../shared/ssh'
+import { SESSION_ID_RE } from '../transcript-reader'
+import { isSafeRemoteHome } from '../remote-safety'
+import type { ContextEnsureQuery, RemoteEnsureOutcome } from '../context-ensure'
+import { remoteCodexHomeExpression, remoteCodexLoginCommand } from './codex-home'
+
+export interface RemoteCodexContextTarget {
+ conn: SshConnection
+ controlPath: string
+ connectionKey?: string
+ remoteHome?: string
+ accountId?: string
+}
+export interface CodexContextRef {
+ conn: SshConnection
+ controlPath: string
+ path: string
+}
+
+/** Locate only this thread in this account. Canonicalize directories on the owning host before
+ * reading; a symlinked date directory must not redirect a forged hook outside sessions. */
+export function remoteCodexTranscriptCommand(
+ target: RemoteCodexContextTarget, sessionId: string, hookPath?: string
+): string | undefined {
+ if (!SESSION_ID_RE.test(sessionId) || (hookPath !== undefined &&
+ (!isSafeRemoteHome(hookPath) || path.posix.normalize(hookPath) !== hookPath))) return
+ const home = remoteCodexHomeExpression(target.remoteHome, target.accountId)
+ const candidate = hookPath ? posixQuote(hookPath) : `"$root"/*/*/*/rollout-*-${sessionId}.jsonl`
+ return remoteCodexLoginCommand(`codex_home=${home}
+root=$(cd "$codex_home/sessions" 2>/dev/null && pwd -P) || exit 1
+for f in ${candidate}; do
+ [ -f "$f" ] && [ ! -L "$f" ] || continue
+ leaf=${'${f##*/}'}
+ case "$leaf" in rollout-*-${sessionId}.jsonl) ;; *) continue ;; esac
+ dir=$(cd "${'${f%/*}'}" 2>/dev/null && pwd -P) || continue
+ case "$dir/" in "$root/"*) printf '%s\\n%s\\n' "$root" "$dir/$leaf"; break ;; esac
+done`)
+}
+
+export function parseRemoteCodexTranscript(stdout: string, sessionId: string): string | undefined {
+ const lines = stdout.trimEnd().split('\n')
+ if (lines.length !== 2) return
+ const [root, file] = lines
+ if (!isSafeRemoteHome(root) || !isSafeRemoteHome(file) ||
+ path.posix.normalize(root) !== root || path.posix.normalize(file) !== file ||
+ !file.startsWith(`${root}/`) || !SESSION_ID_RE.test(sessionId) ||
+ !path.posix.basename(file).startsWith('rollout-') || !file.endsWith(`-${sessionId}.jsonl`)) return
+ return file
+}
+
+interface RemoteCodexContextDeps {
+ /** undefined = local; null = known SSH node whose connection/home is unavailable. */
+ targetFor(nodeId: string): RemoteCodexContextTarget | null | undefined
+ knownAccount(accountId: string, target: RemoteCodexContextTarget): boolean
+ run(target: RemoteCodexContextTarget, command: string): Promise<{ code: number; stdout: string }>
+ tail: {
+ track(sessionId: string, ref: CodexContextRef): void
+ replay(sessionId: string): void
+ untrack(sessionId: string): void
+ }
+ onTrack?(nodeId: string, sessionId: string, ref: CodexContextRef): void
+ onClear?(nodeId: string, sessionId: string): void
+}
+interface Binding { key: string; sessionId: string; tailId: string; ref?: CodexContextRef; revision: number; generation: number }
+
+/** Shared, dependency-injected SSH routing. No local reader is reachable from a remote miss.
+ * Private tail keys and published node ids keep equal thread UUIDs on different hosts separate. */
+export function createRemoteCodexContext(deps: RemoteCodexContextDeps) {
+ const bindings = new Map<string, Binding>()
+ const pending = new Map<string, Promise<RemoteEnsureOutcome>>()
+ let generation = 0
+ const keyFor = (target: RemoteCodexContextTarget): string => JSON.stringify(target)
+ function release(nodeId: string): void {
+ const old = bindings.get(nodeId)
+ if (!old) return
+ deps.tail.untrack(old.tailId)
+ deps.onClear?.(nodeId, old.sessionId)
+ bindings.delete(nodeId)
+ }
+ async function track(nodeId: string, sessionId: string, hookPath?: string): Promise<RemoteEnsureOutcome | null> {
+ const target = deps.targetFor(nodeId)
+ if (target === undefined) return null
+ if (!target || !SESSION_ID_RE.test(sessionId) ||
+ (target.accountId && !deps.knownAccount(target.accountId, target))) {
+ release(nodeId)
+ return 'unresolved'
+ }
+ const key = keyFor(target)
+ let binding = bindings.get(nodeId)
+ if (binding && (binding.key !== key || binding.sessionId !== sessionId)) {
+ release(nodeId)
+ binding = undefined
+ }
+ if (!binding) {
+ binding = { key, sessionId, tailId: JSON.stringify([nodeId, sessionId]), revision: 0, generation: ++generation }
+ bindings.set(nodeId, binding)
+ deps.onClear?.(nodeId, sessionId)
+ }
+ if (hookPath && binding.ref?.path === hookPath) return 'tracked'
+ const current = binding
+ const pendingKey = JSON.stringify([nodeId, key, sessionId, hookPath, current.generation])
+ const existing = pending.get(pendingKey)
+ if (existing) return existing
+ const revision = ++current.revision
+ const request = Promise.resolve().then(async (): Promise<RemoteEnsureOutcome> => {
+ try {
+ const command = remoteCodexTranscriptCommand(target, sessionId, hookPath)
+ if (!command) return 'unresolved'
+ const result = await deps.run(target, command)
+ const file = result.code === 0 ? parseRemoteCodexTranscript(result.stdout, sessionId) : undefined
+ if (!file && !hookPath && bindings.get(nodeId) === current && current.revision === revision) release(nodeId)
+ const liveTarget = deps.targetFor(nodeId)
+ if (!file || bindings.get(nodeId) !== current || current.revision !== revision || !liveTarget ||
+ keyFor(liveTarget) !== key || (target.accountId && !deps.knownAccount(target.accountId, target))) return 'unresolved'
+ const ref = { conn: target.conn, controlPath: target.controlPath, path: file }
+ if (current.ref && current.ref.path !== file) {
+ deps.tail.untrack(current.tailId)
+ deps.onClear?.(nodeId, sessionId)
+ }
+ current.ref = ref
+ deps.tail.track(current.tailId, ref)
+ if (!hookPath) deps.tail.replay(current.tailId)
+ deps.onTrack?.(nodeId, sessionId, ref)
+ return 'tracked'
+ } catch {
+ if (!hookPath && bindings.get(nodeId) === current && current.revision === revision) release(nodeId)
+ return 'unresolved'
+ } finally {
+ pending.delete(pendingKey)
+ }
+ })
+ pending.set(pendingKey, request)
+ return request
+ }
+ return {
+ publish(usage: ContextWindowUsage): ContextWindowUsage | undefined {
+ for (const [nodeId, binding] of bindings) {
+ if (binding.tailId !== usage.sessionId) continue
+ const target = deps.targetFor(nodeId)
+ if (!target || keyFor(target) !== binding.key ||
+ (target.accountId && !deps.knownAccount(target.accountId, target))) { release(nodeId); return }
+ return { ...usage, sessionId: binding.sessionId, nodeId }
+ }
+ return undefined
+ },
+ scopeKey(nodeId: string): string { return JSON.stringify([nodeId, deps.targetFor(nodeId)]) },
+ ensure(q: ContextEnsureQuery): Promise<RemoteEnsureOutcome | null> {
+ return q.nodeId ? track(q.nodeId, q.sessionId) : Promise.resolve(null)
+ },
+ async hook(nodeId: string, p: { session_id?: string; transcript_path?: string; agent_id?: string; hook_event_name?: string }): Promise<void> {
+ // Child rollout paths belong to the child, despite carrying the parent's session id.
+ if (p.agent_id) return
+ if (p.hook_event_name === 'SessionEnd') { release(nodeId); return }
+ if (p.session_id && p.transcript_path) await track(nodeId, p.session_id, p.transcript_path)
+ },
+ release
+ }
+}
diff --git a/src/core/remote-ssh/codex-home.ts b/src/core/remote-ssh/codex-home.ts
new file mode 100644
index 000000000..a427ad31f
--- /dev/null
+++ b/src/core/remote-ssh/codex-home.ts
@@ -0,0 +1,21 @@
+import { remoteCodexHome } from '../codex-accounts-core'
+import { isSafeRemoteHome } from '../remote-safety'
+import { posixQuote } from '../../shared/ssh'
+import type { CodexAccount } from '../../shared/codex-account'
+
+export function isKnownRemoteCodexAccount(accounts: readonly CodexAccount[], id: string, hostKey: string): boolean {
+ return accounts.some(a => a.id === id && a.host === hostKey && !a.pending)
+}
+
+/** Evaluated on the host, never against the desktop environment. A managed account has exactly
+ * one root; system sessions retain the host's CODEX_HOME, including relocated installations. */
+export function remoteCodexHomeExpression(remoteHome: string | undefined, accountId?: string): string {
+ if (!accountId) return '"${CODEX_HOME:-$HOME/.codex}"'
+ if (!isSafeRemoteHome(remoteHome)) throw new Error('Invalid remote home')
+ return posixQuote(remoteCodexHome(remoteHome!, accountId))
+}
+
+/** SSH exec is not necessarily a login shell. Use the same environment as host CLI discovery. */
+export function remoteCodexLoginCommand(program: string): string {
+ return `"${'${SHELL:-/bin/sh}'}" -lc ${posixQuote(program)}`
+}
diff --git a/src/core/usage/codex-usage.ts b/src/core/usage/codex-usage.ts
index b1e3a9fac..fe67b43a4 100644
--- a/src/core/usage/codex-usage.ts
+++ b/src/core/usage/codex-usage.ts
@@ -18,7 +18,7 @@ import type { ProviderUsage, UsageLimit } from '../../shared/types'
import { parseResetTimestamp } from './claude-usage-map'
import { directExecutableInvocation, findInLoginPath } from '../exec-path'
-const BACKEND_USAGE_URL = 'https://chatgpt.com/backend-api/wham/usage'
+export const CODEX_BACKEND_USAGE_URL = 'https://chatgpt.com/backend-api/wham/usage'
const FETCH_TIMEOUT_MS = 8000
const APP_SERVER_TIMEOUT_MS = 10_000
@@ -132,7 +132,7 @@ async function fetchViaBackend(home: string): Promise<ProviderUsage | null> {
const ctrl = new AbortController()
const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)
- const res = await fetch(BACKEND_USAGE_URL, { signal: ctrl.signal, headers }).finally(() =>
+ const res = await fetch(CODEX_BACKEND_USAGE_URL, { signal: ctrl.signal, headers }).finally(() =>
clearTimeout(t)
)
if (!res.ok) return null
diff --git a/src/core/usage/remote-claude-usage.ts b/src/core/usage/remote-claude-usage.ts
index adfcda2f2..e404d594d 100644
--- a/src/core/usage/remote-claude-usage.ts
+++ b/src/core/usage/remote-claude-usage.ts
@@ -32,6 +32,11 @@ const REMOTE_CURL_TIMEOUT_S = 10
/** One remote Claude identity the usage popover can show a row for. */
export interface RemoteUsageTarget {
+ /** Omitted on legacy Claude targets. */
+ provider?: 'claude' | 'codex'
+ remoteHome?: string
+ /** Changes when the reader connection is replaced; prevents reusing a former host session. */
+ connectionKey?: string
/** Stable row identity: `<hostKey>#<accountId ?? ''>`. Also the service's cache key. */
key: string
/** `user@host` of the connection — matches `ClaudeAccount.host`. */
diff --git a/src/core/usage/remote-codex-usage.test.ts b/src/core/usage/remote-codex-usage.test.ts
new file mode 100644
index 000000000..f4ea42a7e
--- /dev/null
+++ b/src/core/usage/remote-codex-usage.test.ts
@@ -0,0 +1,99 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { remoteCodexHome } from '../codex-accounts-core'
+import { fetchRemoteCodexUsage, remoteCodexUsageCommand, remoteCodexUsageTargets } from './remote-codex-usage'
+import type { RemoteUsageTarget } from './remote-claude-usage'
+const exec = promisify(execFile)
+let dir: string, home: string, bin: string
+const payload = { plan_type: 'plus', rate_limit: { primary_window: { used_percent: 42, limit_window_seconds: 18000, reset_at: 1900000000 } } }
+let extra: Record<string, string>
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "nt-codex-usage-'"))
+ home = path.join(dir, 'home with spaces'); bin = path.join(dir, 'bin')
+ fs.mkdirSync(home, { recursive: true }); fs.mkdirSync(bin)
+ fs.writeFileSync(path.join(bin, 'login-shell'), '#!/bin/sh\n[ -z "$FIXTURE_CODEX_HOME" ] || export CODEX_HOME="$FIXTURE_CODEX_HOME"\nprintf "profile noise\\n"\nexec /bin/sh -c "$2"\n', { mode: 0o755 })
+ fs.symlinkSync(process.execPath, path.join(bin, 'node'))
+ fs.writeFileSync(path.join(bin, 'curl'), `#!${process.execPath}\nconst fs=require('fs');fs.writeFileSync(process.env.RECORD,JSON.stringify({args:process.argv.slice(2),input:fs.readFileSync(0,'utf8')}));process.stdout.write(process.env.BODY+'\\n'+(process.env.CODE||'200'));process.exit(Number(process.env.EXIT||0));`, { mode: 0o755 })
+ extra = { BODY: JSON.stringify(payload) }
+})
+afterEach(() => fs.rmSync(dir, { recursive: true, force: true }))
+const target = (accountId: string | null = null): RemoteUsageTarget => ({
+ provider: 'codex', key: 'codex:host', hostKey: 'u@host', projectId: 'p', accountId, label: accountId ?? 'u@host', remoteHome: home
+})
+function auth(root: string, value: unknown = { tokens: { access_token: 'secret-token', account_id: 'chatgpt-id' } }) {
+ fs.mkdirSync(root, { recursive: true }); fs.writeFileSync(path.join(root, 'auth.json'), JSON.stringify(value))
+}
+async function run(_: RemoteUsageTarget, command: string) {
+ return (await exec('/bin/sh', ['-c', command], { env: { ...process.env, HOME: home, CODEX_HOME: '',
+ PATH: `${bin}:/usr/bin:/bin`, SHELL: path.join(bin, 'login-shell'), RECORD: path.join(dir, 'record'), ...extra } })).stdout
+}
+const record = () => JSON.parse(fs.readFileSync(path.join(dir, 'record'), 'utf8')) as {args: string[]; input: string}
+
+describe('remote Codex quota transport (actual generated shell)', () => {
+ it('reads tokens only from the system login environment home and keeps secrets off argv and stdout', async () => {
+ const relocated = path.join(dir, 'custom codex'); extra.FIXTURE_CODEX_HOME = relocated
+ auth(path.join(home, '.codex'), { tokens: { access_token: 'wrong-system' } })
+ auth(relocated, { access_token: 'decoy', other: { access_token: 'decoy2' }, tokens: { access_token: 'real"token\\x', account_id: 'real"account\\x' } })
+ extra.BODY = JSON.stringify({ ...payload, access_token: 'server-secret' })
+ const stdout = await run(target(), remoteCodexUsageCommand(target()))
+ expect(stdout).not.toContain('server-secret'); expect(stdout).not.toContain('real"token')
+ const captured = record()
+ expect(captured.args[0]).toBe('-q')
+ expect(captured.args).not.toContain('--location')
+ expect(captured.args.join(' ')).not.toContain('real"token')
+ const headers = captured.input.trim().split('\n').map(line => JSON.parse(line.slice('header = '.length)))
+ expect(headers).toContain('authorization: Bearer real"token\\x')
+ expect(headers).toContain('chatgpt-account-id: real"account\\x')
+ expect(headers.join(' ')).not.toContain('decoy')
+ expect(await fetchRemoteCodexUsage(target(), run, 123)).toMatchObject({ provider: 'codex', status: 'ok', updatedAt: 123, limits: [{ usedPercent: 42, windowMinutes: 300 }] })
+ })
+ it('isolates a managed home even when system CODEX_HOME points elsewhere', async () => {
+ const t = target('work')
+ auth(remoteCodexHome(home, 'work'), { tokens: { access_token: 'managed-only' } })
+ auth(path.join(home, '.codex'), { tokens: { access_token: 'wrong' } })
+ extra.FIXTURE_CODEX_HOME = path.join(home, '.codex')
+ expect(await fetchRemoteCodexUsage(t, run, 1)).toMatchObject({ accountId: 'work', account: 'work', status: 'ok' })
+ expect(record().input).toContain('managed-only'); expect(record().input).not.toContain('wrong')
+ })
+ it.each(['bad\nheader', 'bad\rheader', 'bad\u0000header'])('rejects header controls without launching curl: %j', token => {
+ auth(path.join(home, '.codex'), { tokens: { access_token: token } })
+ return fetchRemoteCodexUsage(target(), run, 1).then(u => {
+ expect(u.status).toBe('error'); expect(u.limits).toEqual([])
+ expect(fs.existsSync(path.join(dir, 'record'))).toBe(false)
+ })
+ })
+ it.each(['401', '403', '500', '302'])('does not fabricate limits for HTTP %s', async code => {
+ auth(path.join(home, '.codex')); extra.CODE = code
+ const u = await fetchRemoteCodexUsage(target(), run, 1)
+ expect(u.status).toBe(['401', '403'].includes(code) ? 'unavailable' : 'error'); expect(u.limits).toEqual([])
+ })
+ it('distinguishes absent credentials, malformed auth, missing runtime, network errors and empty windows', async () => {
+ expect((await fetchRemoteCodexUsage(target(), run, 1)).status).toBe('unavailable')
+ auth(path.join(home, '.codex')); fs.writeFileSync(path.join(home, '.codex/auth.json'), '{broken')
+ expect((await fetchRemoteCodexUsage(target(), run, 1)).status).toBe('error')
+ auth(path.join(home, '.codex')); extra.EXIT = '28'
+ expect((await fetchRemoteCodexUsage(target(), run, 1)).status).toBe('error')
+ delete extra.EXIT; extra.BODY = JSON.stringify({ plan_type: 'plus' })
+ expect(await fetchRemoteCodexUsage(target(), run, 1)).toMatchObject({ status: 'unavailable', limits: [] })
+ expect((await fetchRemoteCodexUsage(target(), async () => 'node missing', 1)).status).toBe('error')
+ extra.BODY = JSON.stringify({ error: 'wrong shape' })
+ expect((await fetchRemoteCodexUsage(target(), run, 1)).status).toBe('error')
+ })
+ it('refuses missing/unsafe managed scope before any remote read', async () => {
+ for (const t of [{ ...target('work'), remoteHome: undefined }, target('../bad')]) {
+ expect((await fetchRemoteCodexUsage(t, async () => { throw new Error('must not run') }, 1)).status).toBe('error')
+ expect(() => remoteCodexUsageCommand(t)).toThrow()
+ }
+ })
+ it('elects one reader per host and offers only valid nonpending accounts belonging to that host', () => {
+ const rows = remoteCodexUsageTargets([{ projectId: 'p', hostKey: 'u@h', remoteHome: '/h' }, { projectId: 'p2', hostKey: 'u@h' }], [
+ { id: 'work', label: 'Work', host: 'u@h' }, { id: 'other', label: 'Other', host: 'u@other' },
+ { id: 'local', label: 'Local' }, { id: '../bad', label: 'Bad', host: 'u@h' }, { id: 'pending', label: 'Pending', host: 'u@h', pending: true }
+ ])
+ expect(rows.map(r => [r.provider, r.projectId, r.accountId])).toEqual([['codex', 'p', null], ['codex', 'p', 'work']])
+ })
+})
diff --git a/src/core/usage/remote-codex-usage.ts b/src/core/usage/remote-codex-usage.ts
new file mode 100644
index 000000000..1f3f8a553
--- /dev/null
+++ b/src/core/usage/remote-codex-usage.ts
@@ -0,0 +1,109 @@
+// SSH usage reads credentials and performs HTTP on the host. Only sanitized quota windows return.
+// No app-server fallback: a usage refresh must not start an auth-refreshing process remotely.
+import type { ProviderUsage } from '../../shared/types'
+import type { CodexAccount } from '../../shared/codex-account'
+import { posixQuote } from '../../shared/ssh'
+import { isSafeAccountId } from '../codex-accounts-core'
+import { remoteCodexHomeExpression, remoteCodexLoginCommand } from '../remote-ssh/codex-home'
+import { isSafeRemoteHome } from '../remote-safety'
+import { CODEX_BACKEND_USAGE_URL, mapCodexLimits } from './codex-usage'
+import type { RemoteUsageRunner, RemoteUsageTarget } from './remote-claude-usage'
+
+const BEGIN = '__NT_CODEX_USAGE_BEGIN__'
+const END = '__NT_CODEX_USAGE_END__'
+
+export function remoteCodexUsageTargets(
+ connected: readonly { projectId: string; hostKey: string; remoteHome?: string; connectionKey?: string }[],
+ accounts: readonly CodexAccount[]
+): RemoteUsageTarget[] {
+ const seen = new Set<string>()
+ return connected.flatMap(connection => {
+ if (!connection.hostKey || seen.has(connection.hostKey)) return []
+ seen.add(connection.hostKey)
+ const row = (accountId: string | null, label: string): RemoteUsageTarget => ({
+ ...connection, provider: 'codex', accountId, label,
+ key: `codex:${JSON.stringify([connection.hostKey, accountId, connection.remoteHome, connection.connectionKey])}`
+ })
+ return [row(null, connection.hostKey), ...accounts.filter(a =>
+ a.host === connection.hostKey && !a.pending && isSafeAccountId(a.id)
+ ).map(a => row(a.id, a.label || a.id))]
+ })
+}
+
+/** Real JSON parsing (tokens.access_token/account_id only); no regex extraction or credential argv. */
+export function remoteCodexUsageCommand(target: Pick<RemoteUsageTarget, 'accountId' | 'remoteHome'>): string {
+ if (target.accountId !== null && (!isSafeAccountId(target.accountId) || !isSafeRemoteHome(target.remoteHome))) {
+ throw new Error('Remote Codex account scope unavailable')
+ }
+ const home = remoteCodexHomeExpression(target.remoteHome, target.accountId ?? undefined)
+ // JSON.stringify supplies curl-config quoting for quotes/backslashes. Header control bytes are
+ // rejected before config construction; curl's own config, redirects and stderr are disabled.
+ const program = String.raw`
+const fs = require('fs'), path = require('path'), cp = require('child_process');
+const emit = value => process.stdout.write('${BEGIN}' + JSON.stringify(value) + '${END}');
+const fail = status => emit({status});
+try {
+ const home = process.argv[1];
+ if (!home || !path.isAbsolute(home) || /[\x00-\x1f\x7f]/.test(home)) { fail('error'); process.exit(0); }
+ let auth;
+ try {
+ const file = path.join(home, 'auth.json');
+ if (fs.statSync(file).size > 1048576) throw new Error();
+ auth = JSON.parse(fs.readFileSync(file, 'utf8'));
+ } catch (e) { fail(e.code === 'ENOENT' ? 'unavailable' : 'error'); process.exit(0); }
+ const token = auth && auth.tokens && auth.tokens.access_token;
+ const account = auth && auth.tokens && auth.tokens.account_id;
+ if (typeof token !== 'string' || !token) { fail('unavailable'); process.exit(0); }
+ if (/[\x00-\x1f\x7f]/.test(token) || (account != null && (typeof account !== 'string' || /[\x00-\x1f\x7f]/.test(account)))) {
+ fail('error'); process.exit(0);
+ }
+ const headers = ['authorization: Bearer ' + token, 'user-agent: codex-cli', 'openai-beta: codex-1', 'originator: Codex Desktop'];
+ if (account) headers.push('chatgpt-account-id: ' + account);
+ const config = headers.map(h => 'header = ' + JSON.stringify(h)).join('\n') + '\n';
+ const result = cp.spawnSync('curl', ['-q', '-sS', '--max-time', '10', '--max-filesize', '262144',
+ '--proto', '=https', '--max-redirs', '0', '--config', '-', '-w', '\n%{http_code}',
+ '${CODEX_BACKEND_USAGE_URL}'], { input: config, encoding: 'utf8',
+ timeout: 12000, maxBuffer: 262144, stdio: ['pipe', 'pipe', 'ignore'] });
+ if (result.error || result.status !== 0) { fail('error'); process.exit(0); }
+ const raw = result.stdout || '', split = raw.lastIndexOf('\n'), code = Number(raw.slice(split + 1));
+ if (code === 401 || code === 403) { fail('unavailable'); process.exit(0); }
+ if (code !== 200) { fail('error'); process.exit(0); }
+ const payload = JSON.parse(raw.slice(0, split));
+ if (!payload || typeof payload.plan_type !== 'string') { fail('error'); process.exit(0); }
+ // Never forward raw error bodies, identity strings or unexpected server fields to the desktop.
+ const clean = w => {
+ if (!w || typeof w !== 'object') return undefined;
+ const out = {};
+ for (const k of ['used_percent', 'limit_window_seconds', 'reset_at']) {
+ if (typeof w[k] === 'number' && Number.isFinite(w[k])) out[k] = w[k];
+ }
+ return out;
+ };
+ emit({status: 'ok', rate_limit: {
+ primary_window: clean(payload.rate_limit && payload.rate_limit.primary_window),
+ secondary_window: clean(payload.rate_limit && payload.rate_limit.secondary_window)
+ }});
+} catch (_) { fail('error'); }
+`
+ // A single login-shell attempt matches Codex's host environment. Failure is unknown, never a
+ // retry under another home (which might read a different account).
+ return `${remoteCodexLoginCommand(`node -e ${posixQuote(program)} ${home}`)} 2>/dev/null`
+}
+
+export async function fetchRemoteCodexUsage(target: RemoteUsageTarget, run: RemoteUsageRunner, now: number): Promise<ProviderUsage> {
+ const result = (status: ProviderUsage['status'], limits: ProviderUsage['limits'] = []): ProviderUsage => ({
+ provider: 'codex', accountId: target.accountId ?? undefined, account: target.accountId ? target.label : null,
+ limits, status, updatedAt: now
+ })
+ try {
+ const stdout = await run(target, remoteCodexUsageCommand(target))
+ const start = stdout?.indexOf(BEGIN) ?? -1
+ const end = stdout?.indexOf(END, start + BEGIN.length) ?? -1
+ if (!stdout || start < 0 || end < 0) return result('error')
+ const payload = JSON.parse(stdout.slice(start + BEGIN.length, end))
+ if (payload.status !== 'ok') return result(payload.status === 'unavailable' ? 'unavailable' : 'error')
+ const limits = mapCodexLimits(payload.rate_limit)
+ // An absent quota window is unknown, never a manufactured 0% reading.
+ return result(limits.length ? 'ok' : 'unavailable', limits)
+ } catch { return result('error') }
+}
diff --git a/src/core/usage/usage-service.remote.test.ts b/src/core/usage/usage-service.remote.test.ts
index 94e671165..1002e82d4 100644
--- a/src/core/usage/usage-service.remote.test.ts
+++ b/src/core/usage/usage-service.remote.test.ts
@@ -144,3 +144,53 @@ describe('usage:remote', () => {
await expect(callRemote()).resolves.toEqual([])
})
})
+
+
+const CODEX_REPLY = '__NT_CODEX_USAGE_BEGIN__' + JSON.stringify({ status: 'ok',
+ rate_limit: { primary_window: { used_percent: 42 } } }) + '__NT_CODEX_USAGE_END__'
+
+describe('usage:remote Codex identity and connection cache', () => {
+ it('separates Claude/Codex rows with the same host and account id, caching each provider independently', async () => {
+ const run = vi.fn(async (t: RemoteUsageTarget) => t.provider === 'codex' ? CODEX_REPLY : OK_REPLY)
+ start({ targets: () => [target('u@h', 'same'), { ...target('u@h', 'same'), provider: 'codex', remoteHome: '/home/u' }], run })
+ const rows = await callRemote()
+ expect(rows.map(r => [r.provider ?? 'claude', r.usage.limits[0].usedPercent])).toEqual([['claude', 60], ['codex', 42]])
+ await callRemote(); expect(run).toHaveBeenCalledTimes(2)
+ })
+
+ it('invalidates a replaced connection/home and cannot cache its late old reply', async () => {
+ const codex = { ...target('u@h'), provider: 'codex' as const, remoteHome: '/old', connectionKey: 'generation1' }
+ let connected: RemoteUsageTarget[] = [codex]
+ let finish: ((s: string) => void) | undefined
+ const run = vi.fn((t: RemoteUsageTarget) => t.connectionKey === 'generation1'
+ ? new Promise<string>(r => { finish = r }) : Promise.resolve(CODEX_REPLY))
+ start({ targets: () => connected, run })
+ const old = callRemote()
+ connected = [{ ...codex, remoteHome: '/new', connectionKey: 'generation2' }]
+ expect((await callRemote())[0].usage.limits[0].usedPercent).toBe(42)
+ finish?.(CODEX_REPLY.replace('42', '99')); await old
+ expect((await callRemote())[0].usage.limits[0].usedPercent).toBe(42)
+ expect(run).toHaveBeenCalledTimes(2)
+ connected = []; expect(await callRemote()).toEqual([])
+ connected = [{ ...codex, connectionKey: 'generation3' }]
+ await callRemote(); expect(run).toHaveBeenCalledTimes(3)
+ })
+
+ it('limits remote Codex to the requested host and keeps errors as errors rather than zero', async () => {
+ const run = vi.fn(async () => null)
+ start({ targets: () => ['u@a', 'u@b'].map(h => ({ ...target(h), provider: 'codex' })), run })
+ const rows = await callRemote({ hostKey: 'u@b' })
+ expect(rows).toHaveLength(1); expect(rows[0]).toMatchObject({ provider: 'codex', hostKey: 'u@b', usage: { status: 'error', limits: [] } })
+ expect(run).toHaveBeenCalledTimes(1)
+ })
+})
+
+
+it('retains Codex discrimination when the target registry fails during late cache validation', async () => {
+ let calls = 0
+ start({ targets: () => {
+ if (++calls > 1) throw new Error('registry replaced')
+ return [{ ...target('u@h'), provider: 'codex' }]
+ }, run: async () => CODEX_REPLY })
+ expect(await callRemote()).toEqual([expect.objectContaining({ provider: 'codex', usage: expect.objectContaining({ provider: 'codex', status: 'error', limits: [] }) })])
+})
diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.ts
index b42266c18..78baa4492 100644
--- a/src/core/usage/usage-service.ts
+++ b/src/core/usage/usage-service.ts
@@ -24,6 +24,7 @@ import {
type RemoteUsageTarget
} from './remote-claude-usage'
import { fetchCodexUsage } from './codex-usage'
+import { fetchRemoteCodexUsage } from './remote-codex-usage'
import { fetchGeminiUsage } from './gemini-usage'
import { fetchGrokUsage } from './grok-usage'
import { fetchKimiUsage } from './kimi-usage'
@@ -440,23 +441,32 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService
// providers above, fetched ON DEMAND rather than polled: each row costs an ssh exec plus an
// HTTPS request made on someone else's machine, and the pill is informational. The renderer
// asks on mount, when the popover opens, and whenever the set of connected projects changes.
- const remoteCache = new Map<string, { at: number; usage: ClaudeUsage }>()
- const remoteInFlight = new Map<string, Promise<ClaudeUsage>>()
+ const remoteCache = new Map<string, { at: number; usage: ClaudeUsage | ProviderUsage }>()
+ const remoteInFlight = new Map<string, Promise<ClaudeUsage | ProviderUsage>>()
+ const remoteKey = (t: RemoteUsageTarget): string => JSON.stringify([
+ t.provider ?? 'claude', t.hostKey, t.accountId, t.projectId, t.remoteHome, t.connectionKey, t.key
+ ])
const runRemote = async (
deps: RemoteUsageDeps,
target: RemoteUsageTarget
- ): Promise<ClaudeUsage> => {
- const pending = remoteInFlight.get(target.key)
+ ): Promise<ClaudeUsage | ProviderUsage> => {
+ const key = remoteKey(target)
+ const pending = remoteInFlight.get(key)
if (pending) return pending
- const p = fetchRemoteUsage(target, deps.run, Date.now())
- remoteInFlight.set(target.key, p)
+ const p = target.provider === 'codex'
+ ? fetchRemoteCodexUsage(target, deps.run, Date.now())
+ : fetchRemoteUsage(target, deps.run, Date.now())
+ remoteInFlight.set(key, p)
try {
const u = await p
- remoteCache.set(target.key, { at: Date.now(), usage: u })
+ // A replaced connection/account cannot repopulate the cache with a late old reply.
+ if (remoteInFlight.get(key) === p && deps.targets().some(t => remoteKey(t) === key)) {
+ remoteCache.set(key, { at: Date.now(), usage: u })
+ }
return u
} finally {
- remoteInFlight.delete(target.key)
+ if (remoteInFlight.get(key) === p) remoteInFlight.delete(key)
}
}
@@ -473,8 +483,9 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService
// reporting numbers from a connection that no longer exists. Evicted against the FULL target
// list rather than the caller's filtered one: switching between two SSH projects would
// otherwise throw away each host's cache on the way to the other.
- const live = new Set(all.map((t) => t.key))
+ const live = new Set(all.map(remoteKey))
for (const key of [...remoteCache.keys()]) if (!live.has(key)) remoteCache.delete(key)
+ for (const key of [...remoteInFlight.keys()]) if (!live.has(key)) remoteInFlight.delete(key)
// The scoped indicator asks for ONE host — the machine the active project runs on — so the
// other connections cost nothing while you are not looking at them.
const targets = query?.hostKey ? all.filter((t) => t.hostKey === query.hostKey) : all
@@ -482,13 +493,19 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService
// One slow / unreachable host must not withhold the others.
const rows = await Promise.all(
targets.map(async (t): Promise<RemoteAccountUsage> => {
- const cached = remoteCache.get(t.key)
+ const cached = remoteCache.get(remoteKey(t))
const fresh = cached && Date.now() - cached.at < REFETCH_DEBOUNCE_MS
const usage =
!force && fresh
? cached.usage
- : await runRemote(deps, t).catch(() => emptyUsage(null, Date.now(), 'error'))
- return { hostKey: t.hostKey, accountId: t.accountId, label: t.label, usage }
+ : await runRemote(deps, t).catch((): ClaudeUsage | ProviderUsage => t.provider === 'codex'
+ ? { provider: 'codex', accountId: t.accountId ?? undefined, account: t.accountId ? t.label : null,
+ status: 'error', limits: [], updatedAt: Date.now() }
+ : emptyUsage(null, Date.now(), 'error'))
+ const identity = { hostKey: t.hostKey, accountId: t.accountId, label: t.label }
+ return 'provider' in usage
+ ? { ...identity, provider: 'codex', usage }
+ : { ...identity, usage }
})
)
return rows
diff --git a/src/main/context-ensure-wiring.test.ts b/src/main/context-ensure-wiring.test.ts
index d8cd88082..ba40a2139 100644
--- a/src/main/context-ensure-wiring.test.ts
+++ b/src/main/context-ensure-wiring.test.ts
@@ -1,99 +1,48 @@
-// The desktop shell's half of the context meter's mount-time rehydration (issue #813).
-//
-// `core/context-ensure.test.ts` pins the ROUTING with injected deps. What it cannot reach is this
-// shell's `ensureRemote` closure, which is inline in `index.ts` over `ptyManager`,
-// `sshProjectManager` and `remoteContextTail` — so its three load-bearing properties are pinned at
-// source level, the same way `remote-end-wiring.test.ts` and `codex-identity-record-wiring.test.ts`
-// pin theirs. Each of them fails SILENTLY if it regresses: a missing jail reads a file the host
-// named, a fall-through meters the wrong machine, and a handler nobody registers simply leaves the
-// meter blank exactly as before.
-import { describe, expect, it } from 'vitest'
-import { readFileSync } from 'fs'
-import path from 'path'
-
-const SERVER_INDEX = path.join(__dirname, '..', 'server', 'index.ts')
-const SRC = readFileSync(path.join(__dirname, 'index.ts'), 'utf8').replace(/\r\n/g, '\n')
-const SERVER = readFileSync(SERVER_INDEX, 'utf8').replace(/\r\n/g, '\n')
-
-/** The `ensureRemote: async (…) => { … }` body inside the `registerContextEnsureIpc({ … })` call. */
-const ensureRemoteBody = (): string => {
- const start = SRC.indexOf('ensureRemote: async ({ sessionId, cwd, accountId, nodeId, agentId })')
- expect(start, 'ensureRemote closure not found in src/main/index.ts').toBeGreaterThan(-1)
- const end = SRC.indexOf('\n })', start)
- expect(end, 'end of the registerContextEnsureIpc call not found').toBeGreaterThan(start)
- return SRC.slice(start, end)
+// Exercise the router main actually injects into the core registrar; no source-text assertions.
+import { describe, expect, it, vi } from 'vitest'
+import { createRemoteContextEnsure } from '../core/remote-context-ensure'
+import type { ContextEnsureQuery } from '../core/context-ensure'
+
+const q: ContextEnsureQuery = { sessionId: 'session-1', nodeId: 'n', agentId: 'claude', accountId: 'a', cwd: '/r' }
+function harness() {
+ const claude = { pathFor: vi.fn<(sid: string) => string | undefined>(() => undefined), replay: vi.fn(), track: vi.fn() }
+ const codex = vi.fn(async () => 'unresolved' as const)
+ const isRemoteNode = vi.fn(() => true)
+ const locateClaude = vi.fn<() => Promise<{ path: string } | undefined>>(async () => undefined)
+ return { claude, codex, isRemoteNode, locateClaude,
+ ensure: createRemoteContextEnsure({ claude, codex, isRemoteNode, locateClaude }) }
}
-
-describe('main wires the context-meter rehydration', () => {
- it('registers the core handler at all', () => {
- // A handler nobody registers is the whole bug: the renderer casts and nothing receives it.
- expect(SRC).toContain('registerContextEnsureIpc({')
- })
-
- it('routes each agent to its own tail, and gives grok none', () => {
- const body = SRC.slice(SRC.indexOf('registerContextEnsureIpc({'))
- expect(body).toContain('return codexContextTail')
- expect(body).toContain('return geminiContextTail')
- // grok's meter reads a hook-derived signals.json path; there is nothing to rehydrate from, so
- // the switch must fall through to `undefined` rather than adopt claude's tail.
- expect(body.slice(0, body.indexOf('ensureRemote'))).not.toContain('grok')
- })
-})
-
-describe('the remote leg keeps the jail and never falls through', () => {
- it('replays the live remote snapshot when a tracked session remounts', () => {
- expect(ensureRemoteBody()).toContain('remoteContextTail.replay(sessionId)')
- })
-
- it('resolves through `remoteTranscriptRefFor`, the one jailed locator', () => {
- const body = ensureRemoteBody()
- expect(body).toContain('await remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId)')
- // Calling the locator directly would skip `isSafeRemoteTranscriptPath` — a located path is
- // attacker-influenced input (it crosses a machine boundary before we read it). Matched as a
- // CALL, since the closure's comments name the locator to explain the boundary.
- expect(body).not.toContain('locateRemoteTranscriptCommand(')
- })
-
- it('`remoteTranscriptRefFor` still jails what the host answered', () => {
- // The property the test above delegates to. Pinned here so removing the jail cannot leave this
- // file green while the ensure path quietly starts reading whatever the host named.
- const fn = SRC.slice(SRC.indexOf('const remoteTranscriptRefFor = async ('))
- const body = fn.slice(0, fn.indexOf('\n }\n'))
- expect(body).toContain('isSafeRemoteTranscriptPath(located, remoteHome)')
- })
-
- it('answers `null` only for a node that is not an SSH remote', () => {
- const body = ensureRemoteBody()
- // `null` is core's signal to take the LOCAL path. Returning it for anything else — a failed
- // ssh call, an unresolved home — sends a remote session to this machine's disk, where claude's
- // cwd fallback happily meters an unrelated local session under the remote node's id.
- const nulls = body.split('\n').filter((l) => /return null/.test(l))
- expect(nulls.length).toBe(1)
- expect(body).toContain("if (!nodeId || !ptyManager.sshRemoteForNode(nodeId)) return null")
- })
-
- it('refuses a remote codex/gemini node instead of reading this machine', () => {
- // Same boundary the hook raw-listener draws: remote-context-tail.ts parses claude's usage
- // records and the locator searches claude's roots, so there is no remote meter for the others.
- expect(ensureRemoteBody()).toContain("if (agentId && agentId !== 'claude') return 'unresolved'")
- })
-
- it('caches nothing on an unresolved attempt', () => {
- const body = ensureRemoteBody()
- // Only a HIT is remembered, and `remoteTranscriptRefFor` is what remembers it. Nothing here may
- // record an absence: a momentarily dead ControlMaster must not look like a deleted transcript,
- // or the meter stays blank until the session's next turn — the bug, by another route.
- expect(body).not.toMatch(/\.(add|set)\(/)
- })
-})
-
-describe('both shells serve it', () => {
- // The repo has shipped a one-shell hook/transcript change three times; the Server Edition had no
- // `context:ensure` handler AT ALL before this, which is why its meters filled only on the next
- // turn too. The asymmetry that IS legitimate: only the desktop passes `ensureRemote`, because
- // only it has an SSH-project manager — the server runs ON the host whose transcripts it reads.
- it('the server registers the same handler, local-only', () => {
- expect(SERVER).toContain('registerContextEnsureIpc({')
- expect(SERVER).not.toContain('ensureRemote')
+describe('desktop remote context routing', () => {
+ it('only returns local fallback for a node not owned by an SSH project', async () => {
+ const h = harness()
+ expect(await h.ensure(q)).toBe('unresolved')
+ h.isRemoteNode.mockReturnValue(false)
+ expect(await h.ensure(q)).toBeNull()
+ h.isRemoteNode.mockReturnValue(true)
+ expect(await h.ensure({ ...q, nodeId: undefined })).toBeNull()
+ })
+ it('Codex goes only to its own host/account resolver, including failures; Gemini remains unsupported', async () => {
+ const h = harness()
+ expect(await h.ensure({ ...q, agentId: 'codex' })).toBe('unresolved')
+ expect(h.codex).toHaveBeenCalledWith({ ...q, agentId: 'codex' })
+ expect(await h.ensure({ ...q, agentId: 'gemini' })).toBe('unresolved')
+ expect(h.locateClaude).not.toHaveBeenCalled()
+ expect(h.claude.pathFor).not.toHaveBeenCalled()
+ })
+ it('Claude retries unresolved discovery and tracks only the jailed resolver result', async () => {
+ const h = harness(), ref = { path: '/remote/.claude/projects/r/session-1.jsonl' }
+ expect(await h.ensure(q)).toBe('unresolved')
+ expect(h.claude.track).not.toHaveBeenCalled()
+ h.locateClaude.mockResolvedValue(ref)
+ expect(await h.ensure(q)).toBe('tracked')
+ expect(h.locateClaude).toHaveBeenLastCalledWith(q)
+ expect(h.claude.track).toHaveBeenCalledWith(q.sessionId, ref)
+ })
+ it('replays a tracked Claude session without another locator request, including the legacy agent shape', async () => {
+ const h = harness()
+ h.claude.pathFor.mockReturnValue('/tracked')
+ expect(await h.ensure({ ...q, agentId: undefined })).toBe('tracked')
+ expect(h.claude.replay).toHaveBeenCalledWith(q.sessionId)
+ expect(h.locateClaude).not.toHaveBeenCalled()
})
})
diff --git a/src/main/index.ts b/src/main/index.ts
index eca2e5588..bf9d0b908 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,3 +1,6 @@
+import { createRemoteContextEnsure } from '../core/remote-context-ensure'
+import { isKnownRemoteCodexAccount } from '../core/remote-ssh/codex-home'
+import { createRemoteCodexContext } from '../core/remote-ssh/codex-context'
import { subagentReplay } from '../core/subagent-replay'
import { grokHomeDir, grokSessionDir, grokSessionsDir } from '../core/agents/grok-paths'
import { join, resolve, posix } from 'path'
@@ -204,7 +207,7 @@ import { grokContextParse, GROK_SIGNALS_FILE } from '../core/grok-signals'
import { GROK_CHAT_HISTORY_FILE } from '../core/agents/grok-paths'
import { createGrokSubagentFormatter } from '../core/grok-subagent-format'
import { geminiContextParse } from '../core/gemini-session'
-import { codexContextParse } from '../core/codex-session'
+import { codexContextParse, codexContextModel } from '../core/codex-session'
import { createCodexSubagentFormatter } from '../core/codex-subagent-format'
import { codexHome } from '../core/usage/codex-usage'
import { isAsyncSubagentLaunch, grokRawFields, type NormalizedAgentEvent } from '../shared/agents/normalize'
@@ -251,6 +254,7 @@ import {
trackWindowState,
writeWindowState
} from './window-state'
+import { remoteCodexUsageTargets } from '../core/usage/remote-codex-usage'
import { remoteUsageTargets } from '../core/usage/remote-claude-usage'
import { initLicense, isPremium, getStoredEntitlement } from '../core/license'
import { WhisperModelStore } from '../core/speech/whisper-models'
@@ -2366,12 +2370,12 @@ app.whenReady().then(async () => {
const pushContextUpdate = (payload: unknown): void => {
if (!win.isDestroyed()) win.webContents.send(IPC.contextUpdate, payload)
// Feed the macOS Notch HUD the model name (keyed by sessionId; no-op off/non-darwin).
- notchHudOnContextUpdate(payload as { sessionId?: string; model?: string; usedPercent?: number })
+ notchHudOnContextUpdate(payload as Parameters<typeof notchHudOnContextUpdate>[0])
// 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 }
+ const cw = payload as { nodeId?: string; sessionId?: string; usedPercent?: number }
for (const [nid, sid] of nodeContextSession) {
- if (sid === cw.sessionId && typeof cw.usedPercent === 'number') {
+ if ((cw.nodeId ? nid === cw.nodeId : sid === cw.sessionId) && typeof cw.usedPercent === 'number') {
recordContextUsage(nid, cw.usedPercent)
break
}
@@ -2409,6 +2413,36 @@ app.whenReady().then(async () => {
sshProjectManager ? sshProjectManager.sshRun(args) : Promise.resolve({ code: 1, stdout: '' })
)
const remoteContextTail = createRemoteContextTail(win, remoteFile, { onTaskNotification, onToolResult })
+ const remoteCodexContextTail = createRemoteContextTail((usage) => {
+ const scoped = remoteCodexContext.publish(usage)
+ if (scoped) pushContextUpdate(scoped)
+ }, remoteFile, { parse: codexContextParse, parseModel: codexContextModel })
+ // Persisted SSH ownership remains remote while the master is down or before PTY co-attach.
+ const remoteCodexContext = createRemoteCodexContext({
+ targetFor: (nodeId) => {
+ const projectId = workspaceStore.sshProjectIdForNode(nodeId)
+ const live = ptyManager.sshRemoteForNode(nodeId)
+ if (!projectId && !live) return undefined
+ const rt = live ?? (projectId ? sshProjectManager?.refForProject(projectId) : undefined)
+ const node = workspaceStore.getNode(nodeId)
+ if (!rt || !node) return null
+ return { conn: rt.conn, controlPath: rt.controlPath,
+ remoteHome: sshProjectManager?.remoteHomeForControlPath(rt.controlPath), accountId: node.accountId,
+ connectionKey: sshProjectManager?.connectionKeyForControlPath(rt.controlPath) }
+ },
+ knownAccount: (id, target) => isKnownRemoteCodexAccount(
+ settingsStore.get().codexAccounts ?? [], id, sshHostKey(target.conn)),
+ run: (target, command) => sshProjectManager
+ ? sshProjectManager.sshRun(childArgs(target.conn, target.controlPath, command))
+ : Promise.resolve({ code: 1, stdout: '' }),
+ tail: remoteCodexContextTail,
+ onTrack: (nodeId, sessionId) => { nodeContextSession.set(nodeId, sessionId) },
+ onClear: (nodeId, sessionId) => {
+ notchHudOnContextUpdate({ nodeId, sessionId, cleared: true })
+ if (!win.isDestroyed()) win.webContents.send(IPC.contextUpdate, { nodeId, sessionId, cleared: true,
+ usedTokens: 0, windowTokens: 0, usedPercent: 0, model: null, updatedAt: Date.now() })
+ }
+ })
const remoteSubagentTail = createRemoteSubagentTail(win, remoteFile)
// Remote transcript ref learned from the hook raw-listener, keyed by sessionId — lets the
// search/chat read handlers (which receive only sessionId + cwd) read remotely without a
@@ -2633,6 +2667,7 @@ app.whenReady().then(async () => {
// agent's tail, local or remote — lives in core so the Server Edition serves it too; this shell
// supplies the one thing core cannot have, the remote leg (it needs a ControlMaster).
registerContextEnsureIpc({
+ scopeKey: ({ nodeId }) => nodeId ? remoteCodexContext.scopeKey(nodeId) : undefined,
// One tail per agent, matching the hook raw-listener's routing exactly. `undefined` is the
// legacy call shape and stays on claude's tail. Grok is absent on purpose: its meter reads a
// hook-derived `signals.json` path that no locator can reconstruct after a restart, so it has
@@ -2650,34 +2685,13 @@ app.whenReady().then(async () => {
return undefined
}
},
- ensureRemote: async ({ sessionId, cwd, accountId, nodeId, agentId }) => {
- // Not an SSH-project node ⇒ `null`, and core takes its local path — the pre-existing
- // behaviour for every local node, byte for byte.
- if (!nodeId || !ptyManager.sshRemoteForNode(nodeId)) return null
- // From here the session IS remote, so every answer below is terminal: core must never fall
- // through to a local resolver for it.
- //
- // Remote metering is CLAUDE-only, the same boundary the hook raw-listener draws two hundred
- // lines below ("Remote meters for these agents are out of scope"): `remote-context-tail.ts`
- // parses claude's usage records, and `locateRemoteTranscriptCommand` searches claude's
- // transcript roots. A remote codex/gemini node therefore gets no meter here — not a
- // wrong-machine read, which is what falling through would produce.
- if (agentId && agentId !== 'claude') return 'unresolved'
- // Already tracked (a hook event landed, or an earlier mount resolved it) — nothing to ask.
- if (remoteContextTail.pathFor(sessionId)) {
- remoteContextTail.replay(sessionId)
- return 'tracked'
- }
- // Asks the HOST where the transcript is, jails the answer, and caches a HIT under the session
- // id (shared with the ⌘M read path, which is the locator's first consumer). A clean miss and
- // a failed ssh call both come back `undefined` and cache NOTHING — so a momentarily dead
- // ControlMaster is never remembered as "this session has no transcript", and the next mount
- // or hook event resolves it for real.
- const ref = await remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId)
- if (!ref) return 'unresolved'
- remoteContextTail.track(sessionId, ref)
- return 'tracked'
- }
+ ensureRemote: createRemoteContextEnsure({
+ isRemoteNode: (nodeId) => !!ptyManager.sshRemoteForNode(nodeId) || !!workspaceStore.sshProjectIdForNode(nodeId),
+ codex: remoteCodexContext.ensure,
+ claude: remoteContextTail,
+ locateClaude: ({ sessionId, cwd, accountId, nodeId }) =>
+ remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId)
+ })
})
// The remote half of a handoff. Same three-line shape as the context-link deps above and for
// the same reason: reading (and here also WRITING) on an SSH project's host is the one thing
@@ -3087,15 +3101,11 @@ app.whenReady().then(async () => {
hook_event_name?: string
agent_id?: string
}
- // A REMOTE (SSH) node's transcript lives on the HOST, and these tails read the LOCAL disk —
- // a host path like `~/.gemini/tmp/…` clears the local jail, so without this we would meter
- // whatever same-named file happens to exist on THIS machine. Remote meters for these agents
- // are out of scope (remote-context-tail.ts is that path), so skip rather than report the
- // wrong machine's numbers. The Server Edition needs no counterpart: it has no SSH projects,
- // which is why its copy of this branch is otherwise identical but lacks these two lines.
- // (A remote codex node's subagent CARDS still work — normalize is machine-agnostic — it is
- // only the live-activity tail that has no remote leg yet.)
- if (nodeId && ptyManager.sshRemoteForNode(nodeId)) return
+ // Resolve on the owning host. Child rollouts cannot replace the parent's context.
+ if (nodeId && (ptyManager.sshRemoteForNode(nodeId) || workspaceStore.sshProjectIdForNode(nodeId))) {
+ if (agentId === 'codex') void remoteCodexContext.hook(nodeId, p)
+ return
+ }
// Codex subagent events (spawn_agent), BEFORE the meter track: every agent_id-tagged event
// carries the PARENT's session_id with the CHILD's rollout as transcript_path (measured,
// codex-cli 0.146.0 — SubagentStart and the child's own tool events alike), so falling
@@ -3246,6 +3256,7 @@ app.whenReady().then(async () => {
// tails of the OLD session's transcript are just as dead; the respawned agent re-registers
// them under its new session id via the hook events).
const releaseNodeTails = (nodeId: string): void => {
+ remoteCodexContext.release(nodeId)
const sessionId = nodeContextSession.get(nodeId)
if (sessionId) {
// Untrack both tails — untracking a non-tracked session is a no-op, so this is safe
@@ -3831,15 +3842,22 @@ app.whenReady().then(async () => {
// command and the parsing, main owns the ControlMaster. `sshProjectManager` is assigned just
// below, so both closures read it lazily — they only ever run after a project has connected.
remote: {
- targets: () =>
- remoteUsageTargets(
- sshProjectManager?.connectedHosts() ?? [],
- settingsStore.get().claudeAccounts ?? []
- ),
+ targets: () => {
+ const connected = sshProjectManager?.connectedHosts() ?? []
+ return [...remoteUsageTargets(connected, settingsStore.get().claudeAccounts ?? []),
+ ...remoteCodexUsageTargets(connected.map(c => ({ ...c,
+ remoteHome: sshProjectManager?.remoteHomeFor(c.projectId),
+ connectionKey: sshProjectManager?.connectionKeyFor(c.projectId)
+ })), settingsStore.get().codexAccounts ?? [])]
+ },
run: async (target, command) => {
const mgr = sshProjectManager
const ref = mgr?.refForProject(target.projectId)
if (!mgr || !ref) return null
+ if (mgr.hostKeyFor(target.projectId) !== target.hostKey) return null
+ if (target.provider === 'codex' &&
+ (mgr.connectionKeyFor(target.projectId) !== target.connectionKey ||
+ mgr.remoteHomeFor(target.projectId) !== target.remoteHome)) return null
try {
const { stdout } = await mgr.sshRun(childArgs(ref.conn, ref.controlPath, command))
// Deliberately not gated on the exit code: the remote script exits 0 on its own
diff --git a/src/main/notch-hud-model.test.ts b/src/main/notch-hud-model.test.ts
index 3441a599b..24082b7bd 100644
--- a/src/main/notch-hud-model.test.ts
+++ b/src/main/notch-hud-model.test.ts
@@ -168,6 +168,30 @@ describe('subagent grouping', () => {
})
describe('prompt / model / context join', () => {
+ it('keeps copied SSH thread ids isolated from each other and legacy local observations', () => {
+ const m = createHudModel()
+ for (const nodeId of ['local', 'a', 'b']) {
+ m.applyStateChange(stateChange({ nodeId, state: 'working', agentId: 'codex', sessionId: 'copied' }))
+ }
+ m.applyContextUpdate({ nodeId: 'a', sessionId: 'copied', cleared: true })
+ m.applyContextUpdate({ nodeId: 'b', sessionId: 'copied', model: 'remote-b', usedPercent: 75 })
+ m.applyContextUpdate({ sessionId: 'copied', model: 'local-model', usedPercent: 10 })
+ let rows = m.buildRows(T0, titleOf)
+ expect(rowFor(rows, 'local')).toMatchObject({ model: 'local-model', contextPercent: 10 })
+ expect(rowFor(rows, 'a')?.model).toBeUndefined()
+ expect(rowFor(rows, 'a')?.contextPercent).toBeUndefined()
+ expect(rowFor(rows, 'b')).toMatchObject({ model: 'remote-b', contextPercent: 75 })
+ m.applyContextUpdate({ nodeId: 'b', sessionId: 'copied', cleared: true })
+ rows = m.buildRows(T0, titleOf)
+ expect(rowFor(rows, 'b')?.model).toBeUndefined()
+ expect(rowFor(rows, 'b')?.contextPercent).toBeUndefined()
+ m.applyContextUpdate({ nodeId: 'b', sessionId: 'new', model: 'next-model', usedPercent: 25 })
+ m.applyStateChange(stateChange({ nodeId: 'b', state: 'working', sessionId: 'new' }))
+ m.applyContextUpdate({ nodeId: 'b', sessionId: 'copied', cleared: true })
+ expect(rowFor(m.buildRows(T0, titleOf), 'b')).toMatchObject({ model: 'next-model', contextPercent: 25 })
+ m.applyStateChange(stateChange({ nodeId: 'b', state: 'working', sessionId: 'another' }))
+ expect(rowFor(m.buildRows(T0, titleOf), 'b')?.model).toBeUndefined()
+ })
it('joins model by sessionId and context% by now-change', () => {
const m = createHudModel()
m.applyStateChange(stateChange({ nodeId: 'a', state: 'working', agentId: 'claude', sessionId: 's1' }))
diff --git a/src/main/notch-hud-model.ts b/src/main/notch-hud-model.ts
index ea029f0ea..bada300df 100644
--- a/src/main/notch-hud-model.ts
+++ b/src/main/notch-hud-model.ts
@@ -139,6 +139,14 @@ export function firstPromptLine(text: string | undefined, max = PROMPT_MAX): str
return line.length > max ? line.slice(0, max - 1) + '…' : line
}
+export interface HudContextUpdate {
+ sessionId?: string
+ nodeId?: string
+ model?: string | null
+ usedPercent?: number
+ cleared?: true
+}
+
export interface HudModel {
/** A main-state edge (working start / needsYou / done). Drives the row's live state + latch. */
applyStateChange(c: NodeStateChange): void
@@ -149,7 +157,7 @@ export interface HudModel {
/** The normalized agent-event stream — the ONLY source of the user prompt + subagent grouping. */
applyAgentEvent(ev: NormalizedAgentEvent): void
/** A context-update {sessionId, model, usedPercent} — the ONLY source of the model name. */
- applyContextUpdate(p: { sessionId?: string; model?: string; usedPercent?: number }): void
+ applyContextUpdate(p: HudContextUpdate): void
/** Clear ONE node's done highlight (the user opened that row). Read is per row on purpose:
* a blanket "the panel was opened, so everything is read" loses sessions the user never saw. */
noteFocus(nodeId: string): void
@@ -170,6 +178,9 @@ export function createHudModel(): HudModel {
const nodes = new Map<string, NodeAccum>()
// Model name arrives keyed by sessionId (context tail) — joined to a node via its sessionId.
const modelBySession = new Map<string, string>()
+ // A scoped entry remains present after a clear so this node cannot fall back to another
+ // host's session-id observation. Context never creates a phantom HUD row on its own.
+ const contextByNode = new Map<string, HudContextUpdate>()
function ensure(nodeId: string, ts: number): NodeAccum {
let a = nodes.get(nodeId)
@@ -277,12 +288,18 @@ export function createHudModel(): HudModel {
}
}
- function applyContextUpdate(p: { sessionId?: string; model?: string; usedPercent?: number }): void {
+ function applyContextUpdate(p: HudContextUpdate): void {
if (!p.sessionId) return
+ if (p.nodeId) {
+ const previous = contextByNode.get(p.nodeId)
+ if (p.cleared && previous && previous.sessionId !== p.sessionId) return
+ contextByNode.set(p.nodeId, p.cleared ? { nodeId: p.nodeId, sessionId: p.sessionId, cleared: true } : { ...p })
+ return
+ }
if (p.model) modelBySession.set(p.sessionId, p.model)
if (typeof p.usedPercent === 'number') {
- for (const a of nodes.values()) {
- if (a.sessionId === p.sessionId) {
+ for (const [nodeId, a] of nodes) {
+ if (!contextByNode.has(nodeId) && a.sessionId === p.sessionId) {
a.contextPercent = p.usedPercent
break
}
@@ -312,6 +329,7 @@ export function createHudModel(): HudModel {
if (a.presentInMirror) continue
if (now - a.updatedAt > HUD_STALE_DROP_MS) {
nodes.delete(nodeId)
+ contextByNode.delete(nodeId)
changed = true
}
}
@@ -342,7 +360,10 @@ export function createHudModel(): HudModel {
// node's display to idle and back without that counting as "it changed".
if (a.dismissedAt === a.state) continue
a.dismissedAt = undefined
- const model = a.sessionId ? modelBySession.get(a.sessionId) : undefined
+ const scoped = contextByNode.get(nodeId)
+ const current = scoped?.sessionId === a.sessionId && !scoped?.cleared ? scoped : undefined
+ const model = scoped ? current?.model : a.sessionId ? modelBySession.get(a.sessionId) : undefined
+ const contextPercent = scoped ? current?.usedPercent : a.contextPercent
rows.push({
row: {
nodeId,
@@ -352,7 +373,7 @@ export function createHudModel(): HudModel {
state,
...(a.prompt ? { prompt: a.prompt } : {}),
...(a.activity ? { activity: a.activity } : {}),
- ...(typeof a.contextPercent === 'number' ? { contextPercent: a.contextPercent } : {}),
+ ...(typeof contextPercent === 'number' ? { contextPercent } : {}),
subagents: [...a.subagents.values()],
// The latch, said out loud: a finished turn nobody has looked at. `noteFocus` / a
// read-ack from the phone clears `doneSeen`, which retires the row entirely.
diff --git a/src/main/notch-hud.ts b/src/main/notch-hud.ts
index 0196c66b2..c3ee1fe38 100644
--- a/src/main/notch-hud.ts
+++ b/src/main/notch-hud.ts
@@ -21,7 +21,7 @@ import {
type MirrorFile
} from '../core/agent-status-mirror'
import type { NormalizedAgentEvent } from '../shared/agents/normalize'
-import { createHudModel, type HudModel } from './notch-hud-model'
+import { createHudModel, type HudModel, type HudContextUpdate } from './notch-hud-model'
import { hudGeometry, hudPlacement, type HudGeometry } from './notch-hud-geometry'
import {
sanitizeNotchAlign,
@@ -201,7 +201,7 @@ class NotchHudController {
}
/** Feed a context-update {sessionId, model, usedPercent} (the model name). */
- onContextUpdate(p: { sessionId?: string; model?: string; usedPercent?: number }): void {
+ onContextUpdate(p: HudContextUpdate): void {
this.onModelChange(() => this.model.applyContextUpdate(p))
}
@@ -446,10 +446,6 @@ export function destroyNotchHud(): void {
export function notchHudOnAgentEvent(ev: NormalizedAgentEvent): void {
controller?.onAgentEvent(ev)
}
-export function notchHudOnContextUpdate(p: {
- sessionId?: string
- model?: string
- usedPercent?: number
-}): void {
+export function notchHudOnContextUpdate(p: HudContextUpdate): void {
controller?.onContextUpdate(p)
}
diff --git a/src/main/remote-context-tail.codex.test.ts b/src/main/remote-context-tail.codex.test.ts
new file mode 100644
index 000000000..80e915d7c
--- /dev/null
+++ b/src/main/remote-context-tail.codex.test.ts
@@ -0,0 +1,60 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { createRemoteContextTail } from './remote-context-tail'
+import { codexContextParse, codexContextModel } from '../core/codex-session'
+import type { RemoteFile } from './remote-ssh/remote-file'
+
+const ref = { conn: { host: 'fixture', user: 'u' }, controlPath: '/socket', path: '/rollout' }
+const model = JSON.stringify({ type: 'turn_context', payload: { model: 'codex-fixture-model' } }) + '\n'
+const usage = (input: number, window?: number) => JSON.stringify({ type: 'event_msg', payload: { type: 'token_count', info: {
+ last_token_usage: { input_tokens: input, cached_input_tokens: input - 1 },
+ total_token_usage: { input_tokens: input * 10 }, model_context_window: window
+} } }) + '\n'
+const snapshot = (text: string, initial = false) => ({ data: Buffer.from(text), newOffset: text.length, initial })
+beforeEach(() => vi.useFakeTimers())
+afterEach(() => { vi.clearAllTimers(); vi.useRealTimers() })
+function setup() {
+ const send = vi.fn(), onToolResult = vi.fn(), onTaskNotification = vi.fn()
+ const readContextWindow = vi.fn().mockResolvedValue(snapshot(''))
+ const tail = createRemoteContextTail(send, { readContextWindow } as unknown as RemoteFile,
+ { parse: codexContextParse, parseModel: codexContextModel, onToolResult, onTaskNotification })
+ return { tail, send, readContextWindow, onToolResult, onTaskNotification }
+}
+it('uses Codex last input and reported window, preserves separately read model and torn token records', async () => {
+ const h = setup()
+ const line = usage(25000, 100000)
+ h.readContextWindow.mockResolvedValueOnce(snapshot(model, true))
+ .mockResolvedValueOnce(snapshot(line.slice(0, 70))).mockResolvedValueOnce(snapshot(line.slice(70)))
+ h.tail.track('s', ref, 999999) // Claude environment metadata must never override Codex's denominator.
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.send).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.send).toHaveBeenCalledTimes(1)
+ expect(h.send).toHaveBeenLastCalledWith(expect.objectContaining({ sessionId: 's', model: 'codex-fixture-model',
+ usedTokens: 25000, windowTokens: 100000, usedPercent: 25, windowSource: 'transcript' }))
+ h.tail.replay('s')
+ expect(h.send).toHaveBeenCalledTimes(2)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.send).toHaveBeenCalledTimes(2)
+})
+it('does not fabricate a Claude window when Codex has not stated its capacity', async () => {
+ const h = setup()
+ h.readContextWindow.mockResolvedValueOnce(snapshot(model + usage(123), true))
+ h.tail.track('s', ref, 999999)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(h.send).not.toHaveBeenCalled()
+ h.readContextWindow.mockResolvedValueOnce(snapshot(usage(200, 2000)))
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.send).toHaveBeenCalledWith(expect.objectContaining({ usedPercent: 10, windowTokens: 2000 }))
+})
+it('cannot publish an old read after a remote reference is replaced', async () => {
+ const h = setup()
+ let finish!: (value: ReturnType<typeof snapshot>) => void
+ h.readContextWindow.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
+ .mockResolvedValueOnce(snapshot(usage(20, 100), true))
+ h.tail.track('s', ref)
+ h.tail.track('s', { ...ref, path: '/new-rollout' })
+ await vi.advanceTimersByTimeAsync(0)
+ finish(snapshot(usage(99, 100), true)); await vi.advanceTimersByTimeAsync(0)
+ expect(h.send).toHaveBeenCalledTimes(1)
+ expect(h.send.mock.calls[0][0].usedTokens).toBe(20)
+})
diff --git a/src/main/remote-context-tail.ts b/src/main/remote-context-tail.ts
index 8a52c5666..9b467f7f4 100644
--- a/src/main/remote-context-tail.ts
+++ b/src/main/remote-context-tail.ts
@@ -1,8 +1,8 @@
-// Remote counterpart of context-tail.ts: tails a Claude transcript .jsonl that lives on a
+// Remote counterpart of context-tail.ts: tails an agent transcript .jsonl that lives on a
// REMOTE host (read over the project's ControlMaster via an injected RemoteFile) and pushes
// the IDENTICAL ContextWindowUsage IPC the local tail does — the renderer can't tell remote
-// from local. Reuses the pure parser (parseLatestUsage) + model-window resolution from the
-// local tail; differs only in being async (the read is an ssh round-trip), so it async-polls
+// from local. Claude uses parseLatestUsage + model-window resolution; Codex injects its own
+// parser and reported denominator. The read is an ssh round-trip, so it async-polls
// with a per-session in-flight `reading` flag that skips a tick instead of overlapping reads.
import { type BrowserWindow } from 'electron'
import { IPC } from '../shared/ipc'
@@ -31,6 +31,7 @@ interface Tracked {
suppressCarry: boolean
used: number
window: number
+ parsedWindow: number | null
model: string | null
// In-flight guard: a slow ssh read must not overlap with the next tick.
reading: boolean
@@ -53,10 +54,12 @@ export interface RemoteContextTail {
}
export function createRemoteContextTail(
- win: BrowserWindow,
+ win: BrowserWindow | ((payload: ContextWindowUsage) => void),
remoteFile: RemoteFile,
- opts?: ContextTailOptions
+ opts?: ContextTailOptions & { parseModel?: (text: string | string[]) => string | null }
): RemoteContextTail {
+ const customParse = opts?.parse
+ const parse: NonNullable<ContextTailOptions['parse']> = customParse ?? parseLatestUsage
const sessions = new Map<string, Tracked>()
let timer: ReturnType<typeof setInterval> | null = null
@@ -71,10 +74,12 @@ export function createRemoteContextTail(
// torn tail past the final newline, so dropping it yields the complete lines.
const lines = combined.toString('utf-8').split('\n')
const completeLines = lines.slice(0, -1)
- const latest = parseLatestUsage(lines)
+ t.model = opts?.parseModel?.(lines) ?? t.model
+ const latest = parse(lines)
if (latest) {
t.used = latest.used
t.model = latest.model ?? t.model
+ t.parsedWindow = latest.window ?? t.parsedWindow
}
// A historical partial line may finish on a later poll; it still must not emit events.
const eventLines = historical ? [] : completeLines.slice(t.suppressCarry ? 1 : 0)
@@ -88,7 +93,7 @@ export function createRemoteContextTail(
}
const push = (sessionId: string, t: Tracked): void => {
- if (win.isDestroyed()) return
+ if (typeof win !== 'function' && win.isDestroyed()) return
const usedPercent = Math.min(100, Math.max(0, (t.used / t.window) * 100))
const payload: ContextWindowUsage = {
sessionId,
@@ -96,10 +101,11 @@ export function createRemoteContextTail(
windowTokens: t.window,
usedPercent,
model: t.model,
- windowSource: t.sessionWindow === null ? 'estimate' : 'session-env',
+ windowSource: customParse ? 'transcript' : t.sessionWindow === null ? 'estimate' : 'session-env',
updatedAt: Date.now()
}
- win.webContents.send(IPC.contextUpdate, payload)
+ if (typeof win === 'function') win(payload)
+ else win.webContents.send(IPC.contextUpdate, payload)
}
// One bounded read per tick; retain the last good meter through transport failures.
@@ -129,10 +135,10 @@ export function createRemoteContextTail(
}
// Reconcile the window every pass, same resolution as the local tail.
- const window = t.sessionWindow ?? cachedWindowFor(t.model)
+ const window = customParse ? t.parsedWindow : t.sessionWindow ?? cachedWindowFor(t.model)
if (sessions.get(sessionId) !== t) return
- if (t.used > 0 && (t.used !== t.lastUsed || t.model !== t.lastModel || window !== t.lastWindow)) {
+ if (t.used > 0 && window !== null && window > 0 && (t.used !== t.lastUsed || t.model !== t.lastModel || window !== t.lastWindow)) {
t.window = window
push(sessionId, t)
t.lastUsed = t.used
@@ -171,6 +177,7 @@ export function createRemoteContextTail(
suppressCarry: false,
used: 0,
window: 0,
+ parsedWindow: null,
model: null,
reading: false,
lastUsed: 0,
diff --git a/src/main/remote-ssh/ssh-project.codex-auth.test.ts b/src/main/remote-ssh/ssh-project.codex-auth.test.ts
index 9e576d20f..937c1718c 100644
--- a/src/main/remote-ssh/ssh-project.codex-auth.test.ts
+++ b/src/main/remote-ssh/ssh-project.codex-auth.test.ts
@@ -49,3 +49,19 @@ describe('SshProjectManager.remoteCodexAuthPresent', () => {
expect(await makeMgr({ code: 0, stdout: 'yes' }).mgr.remoteCodexAuthPresent('p1', 'acct1')).toBeNull()
})
})
+
+
+it('changes metric connection identity after reconnect even when the socket path is reused', async () => {
+ const { mgr } = makeMgr({ code: 0, stdout: '' })
+ expect(mgr.connectionKeyFor('p1')).toBeUndefined()
+ await mgr.connect('p1', conn, '/srv')
+ const key = mgr.connectionKeyFor('p1')
+ const ref = mgr.refForProject('p1')!
+ expect(key).toBeTruthy()
+ expect(mgr.connectionKeyForControlPath(ref.controlPath)).toBe(key)
+ await mgr.disconnect('p1')
+ expect(mgr.connectionKeyFor('p1')).toBeUndefined()
+ await mgr.connect('p1', conn, '/srv')
+ expect(mgr.connectionKeyFor('p1')).not.toBe(key)
+ await mgr.disconnect('p1')
+})
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index a585ed734..53580dd81 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -1443,6 +1443,26 @@ export class SshProjectManager {
* SshFs ops take). Returns `undefined` when the project isn't connected, so the `sshFs:*` IPC
* handlers can fail open (empty result) rather than throw.
*/
+ private readonly connectionKeys = new WeakMap<object, string>()
+ private nextConnectionKey = 0
+
+ /** A reused control socket path is not a connection generation. New Conn objects invalidate
+ * in-flight metrics/discovery even when reconnect uses the same host, project and socket. */
+ connectionKeyFor(projectId: string): string | undefined {
+ const connection = this.conns.get(projectId)
+ if (!connection) return undefined
+ let key = this.connectionKeys.get(connection)
+ if (!key) { key = String(++this.nextConnectionKey); this.connectionKeys.set(connection, key) }
+ return key
+ }
+
+ connectionKeyForControlPath(controlPath: string): string | undefined {
+ for (const [projectId, connection] of this.conns) {
+ if (connection.controlPath === controlPath) return this.connectionKeyFor(projectId)
+ }
+ return undefined
+ }
+
refForProject(
projectId: string
): { conn: SshConnection; controlPath: string; remoteCwd?: string } | undefined {
diff --git a/src/renderer/components/ContextMeter.test.tsx b/src/renderer/components/ContextMeter.test.tsx
index c53507d61..65a082094 100644
--- a/src/renderer/components/ContextMeter.test.tsx
+++ b/src/renderer/components/ContextMeter.test.tsx
@@ -4,6 +4,8 @@ import { act } from 'react'
import { createRoot } from 'react-dom/client'
import { ContextMeter } from './ContextMeter'
import { useContextWindow } from '../state/contextWindow'
+import { useSettings } from '../state/settings'
+import { setCustomAgentBaseResolver } from '@shared/agents/config'
it('qualifies model-name guesses but not observed session configuration', async () => {
const el = document.createElement('div')
@@ -17,3 +19,29 @@ it('qualifies model-name guesses but not observed session configuration', async
expect(el.querySelector('button')?.title).toMatch(/^Context window/)
} finally { await act(async () => root.unmount()) }
})
+
+it('shows only the requested SSH node even when local and remote rollouts share an id', async () => {
+ useSettings.setState(s => ({ settings: { ...s.settings, usagePercentMode: 'used' } }))
+ const el = document.createElement('div')
+ const root = createRoot(el)
+ const usage = { sessionId: 'copied', usedTokens: 10, windowTokens: 100, usedPercent: 10, model: 'gpt', updatedAt: Date.now(), windowSource: 'transcript' as const }
+ useContextWindow.setState({ bySessionId: {}, byNodeId: {} })
+ useContextWindow.getState().set(usage)
+ useContextWindow.getState().set({ ...usage, nodeId: 'a', usedPercent: 70 })
+ try {
+ await act(async () => root.render(<ContextMeter sessionId="copied" nodeId="b" remote agentId="codex" />))
+ expect(el.querySelector('button')).toBeNull()
+ await act(async () => root.render(<ContextMeter sessionId="copied" nodeId="a" remote agentId="codex" />))
+ expect(el.querySelector('button')?.title).toContain('70%')
+ setCustomAgentBaseResolver(id => id === 'custom:remote-codex' ? 'codex' : undefined)
+ await act(async () => root.render(<ContextMeter sessionId="copied" nodeId="b" remote agentId="custom:remote-codex" />))
+ expect(el.querySelector('button')).toBeNull()
+ await act(async () => root.render(<ContextMeter sessionId="new-thread" nodeId="a" remote agentId="codex" />))
+ expect(el.querySelector('button')).toBeNull()
+ await act(async () => root.render(<ContextMeter sessionId="copied" />))
+ expect(el.querySelector('button')?.title).toContain('10%')
+ } finally {
+ setCustomAgentBaseResolver(null)
+ await act(async () => root.unmount())
+ }
+})
diff --git a/src/renderer/components/ContextMeter.tsx b/src/renderer/components/ContextMeter.tsx
index 8ad21fedc..3f0dc5f1c 100644
--- a/src/renderer/components/ContextMeter.tsx
+++ b/src/renderer/components/ContextMeter.tsx
@@ -1,14 +1,27 @@
import { useEffect, useRef, useState } from 'react'
import { useContextWindow } from '../state/contextWindow'
import { useSettings } from '../state/settings'
+import { capabilityAgentId } from '@shared/agents/config'
import { barFillPercent, contextFillColor, contextPillText, formatModelLabel, formatTimeAgo, formatTokensShort, percentText } from '../lib/usageFormat'
/**
* Per-Claude-node context-window meter. A small header pill (mini-bar + "NN%") that toggles
* a popover with token figures and model. Renders nothing until the session has usage data.
*/
-export function ContextMeter({ sessionId }: { sessionId: string | null }): JSX.Element | null {
- const usage = useContextWindow((s) => (sessionId ? s.bySessionId[sessionId] : undefined))
+export function ContextMeter({ sessionId, nodeId, remote = false, agentId }: {
+ sessionId: string | null
+ nodeId?: string
+ remote?: boolean
+ agentId?: string
+}): JSX.Element | null {
+ const scoped = remote && !!agentId && capabilityAgentId(agentId) === 'codex'
+ // A copied rollout has the same session id on two hosts. SSH Codex observations belong
+ // to the node that requested them; never fall back to a local/session-only snapshot.
+ const usage = useContextWindow((s) => {
+ if (!sessionId) return undefined
+ const value = scoped ? (nodeId ? s.byNodeId[nodeId] : undefined) : s.bySessionId[sessionId]
+ return value?.sessionId === sessionId ? value : undefined
+ })
const percentMode = useSettings((s) => s.settings.usagePercentMode)
const [open, setOpen] = useState(false)
const ref = useRef<HTMLDivElement>(null)
diff --git a/src/renderer/components/UsageIndicator.remoteCodex.test.tsx b/src/renderer/components/UsageIndicator.remoteCodex.test.tsx
new file mode 100644
index 000000000..f8abf2258
--- /dev/null
+++ b/src/renderer/components/UsageIndicator.remoteCodex.test.tsx
@@ -0,0 +1,76 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { UsageIndicator } from './UsageIndicator'
+import { useSettings } from '../state/settings'
+import { useProjects } from '../state/projects'
+import { useSshConn } from '../state/sshConn'
+import { DEFAULT_SETTINGS, type RemoteAccountUsage, type ProviderUsage } from '@shared/types'
+let root: Root, host: HTMLDivElement
+const usage = (value: number): ProviderUsage => ({ provider: 'codex', status: 'ok', account: 'Work', updatedAt: 1,
+ limits: [{ kind: 'session', group: 'session', usedPercent: value, severity: null, resetsAt: null, windowMinutes: 300, scopeLabel: null, isActive: false }] })
+const row = (hostKey: string, value: number): Extract<RemoteAccountUsage, { provider: 'codex' }> => ({ provider: 'codex', hostKey, accountId: 'work', label: 'Work', usage: usage(value) })
+const project = (id: string, server: string) => ({ id, name: id, nodes: [], ssh: { server: { host: server, user: 'u', port: 22 }, remoteCwd: '/srv' } })
+beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
+ useSettings.setState({ hydrated: true, settings: { ...DEFAULT_SETTINGS, usagePercentMode: 'used', hiddenUsageProviders: ['claude', 'claude-remote'],
+ claudeAccounts: [{ id: 'work', label: 'Claude work', host: 'u@a', createdAt: 0 }] } })
+ useProjects.setState({ projects: [project('a', 'a'), project('b', 'b')] as never, activeProjectId: 'a' })
+ useSshConn.setState({ byProject: { a: { controlPath: '/a' }, b: { controlPath: '/b' } } })
+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
+})
+afterEach(() => { act(() => root.unmount()); host.remove(); useSettings.setState({ settings: DEFAULT_SETTINGS }); useProjects.setState({ projects: [], activeProjectId: '' }); useSshConn.setState({ byProject: {} }); vi.unstubAllGlobals() })
+async function render(remote: (q?: {hostKey?: string}) => Promise<RemoteAccountUsage[]>) {
+ Object.assign(window, { nodeTerminal: { usage: { remote, providers: async () => [usage(99)],
+ fetch: async () => null, onUpdate: () => () => {} }, settings: { save: async () => {} } } })
+ await act(async () => root.render(<UsageIndicator countAccountSessions={() => 3} onMoveSessions={vi.fn()} />))
+}
+it('shows host Codex when Claude is hidden without Claude default/move controls or local quotas', async () => {
+ await render(async () => [row('u@a', 42)])
+ expect(host.querySelector('.usage-pill')?.textContent).toContain('42% Codex')
+ expect(host.textContent).not.toContain('99%')
+ await act(async () => (host.querySelector('.usage-pill') as HTMLButtonElement).click())
+ expect(host.textContent).toContain('u@a · SSH')
+ expect(host.textContent).not.toContain('Move 3 sessions')
+ expect(host.textContent).not.toContain('Use for new sessions')
+ await act(async () => useSettings.setState({ settings: { ...useSettings.getState().settings, hiddenUsageProviders: ['codex', 'claude', 'claude-remote'] } }))
+ expect(host.querySelector('.usage-pill')).toBeNull()
+})
+it('does not let a slow previous host response replace the current host quota', async () => {
+ let finish: ((r: RemoteAccountUsage[]) => void) | undefined
+ await render(q => q?.hostKey === 'u@a' ? new Promise(r => { finish = r }) : Promise.resolve([row('u@b', 17)]))
+ await act(async () => useProjects.setState({ activeProjectId: 'b' }))
+ expect(host.textContent).toContain('17% Codex')
+ await act(async () => finish?.([row('u@a', 88)]))
+ expect(host.textContent).toContain('17% Codex'); expect(host.textContent).not.toContain('88%')
+})
+it('renders an error without a zero percent bar when the host cannot read usage', async () => {
+ await render(async () => [{ ...row('u@a', 42), usage: { ...usage(42), limits: [], status: 'error' } }])
+ expect(host.querySelector('.usage-pill')?.textContent).toContain('⚠')
+ expect(host.textContent).not.toContain('0%')
+ await act(async () => (host.querySelector('.usage-pill') as HTMLButtonElement).click())
+ expect(host.textContent).toContain('Could not read usage.')
+})
+
+it('discards an old forced refresh after switching projects and retains both Claude and Codex pill limits', async () => {
+ useSettings.setState({ settings: { ...useSettings.getState().settings, hiddenUsageProviders: [] } })
+ let finish: ((r: RemoteAccountUsage[]) => void) | undefined
+ await render((q: { hostKey?: string; force?: boolean } | undefined) => {
+ if (q?.force) return new Promise(r => { finish = r })
+ if (q?.hostKey === 'u@b') return Promise.resolve([row('u@b', 17)])
+ return Promise.resolve([row('u@a', 98), { hostKey: 'u@a', accountId: null, label: 'u@a',
+ usage: { limits: usage(5).limits, email: null, session: null, weekly: null, status: 'ok', updatedAt: 1 } }])
+ })
+ expect(host.querySelector('.usage-pill')?.textContent).toContain('98% Codex')
+ expect(host.querySelector('.usage-pill')?.textContent).toContain('5%')
+ expect((host.querySelector('.usage-pill__minibar-fill') as HTMLElement).style.width).toBe('98%')
+ await act(async () => (host.querySelector('.usage-pill') as HTMLButtonElement).click())
+ const refresh = host.querySelector('button[title="Refresh usage"]') as HTMLButtonElement
+ expect(refresh).toBeTruthy()
+ await act(async () => refresh.click())
+ await act(async () => useProjects.setState({ activeProjectId: 'b' }))
+ expect(host.querySelector('.usage-pill')?.textContent).toContain('17% Codex')
+ await act(async () => finish?.([row('u@a', 88)]))
+ expect(host.querySelector('.usage-pill')?.textContent).toContain('17% Codex')
+})
diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsx
index 5dbac3436..edc129119 100644
--- a/src/renderer/components/UsageIndicator.tsx
+++ b/src/renderer/components/UsageIndicator.tsx
@@ -220,7 +220,7 @@ function RemoteUsageBlock({
onUse,
move
}: {
- row: RemoteAccountUsage
+ row: Extract<RemoteAccountUsage, { provider?: 'claude' }>
mode: 'used' | 'remaining' | 'tokens'
isDefault?: boolean
onUse?: () => void
@@ -263,12 +263,14 @@ function labelFor(provider: string): string {
return providerLabel(provider, agentLabel)
}
-function ProviderBlock({ u, mode }: { u: ProviderUsage; mode: 'used' | 'remaining' | 'tokens' }) {
+function ProviderBlock({ u, mode, hostKey }: { u: ProviderUsage; mode: 'used' | 'remaining' | 'tokens'; hostKey?: string }) {
if (u.status === 'unavailable') return null
const label = labelFor(u.provider)
return (
<div className="usage-account">
- <div className="usage-account__label">{label}</div>
+ <div className="usage-account__label">{label}
+ {hostKey && <span className="usage-account__host" title={`Read on ${hostKey} over SSH`}>{hostKey} · SSH</span>}
+ </div>
{u.account && <div className="usage-account__email">{u.account}</div>}
{u.limits.map((l) => (
<LimitRow key={limitKey(l)} limit={l} mode={mode} />
@@ -422,7 +424,13 @@ export function UsageIndicator({
// pill stays empty until you click it). Never polled: each row is an ssh exec plus an HTTPS
// request made on the host, which is not a price to pay every 15 minutes for a pill nobody may
// be looking at.
- const sshUp = useSshConn((s) => !!s.byProject[activeProjectId])
+ const sshConnection = useSshConn((s) => s.byProject[activeProjectId])
+ const sshUp = !!sshConnection
+ const remoteScope = useRef({ activeProjectId, scopeHostKey, sshConnection })
+ if (remoteScope.current.activeProjectId !== activeProjectId || remoteScope.current.scopeHostKey !== scopeHostKey ||
+ remoteScope.current.sshConnection !== sshConnection) {
+ remoteScope.current = { activeProjectId, scopeHostKey, sshConnection }
+ }
useEffect(() => {
if (!scopeHostKey || !sshUp) {
// Leaving the rows up after a switch would attribute one machine's numbers to another.
@@ -436,7 +444,7 @@ export function UsageIndicator({
return () => {
cancelled = true
}
- }, [open, scopeHostKey, sshUp])
+ }, [open, scopeHostKey, sshUp, sshConnection])
// Fetch each account's usage on demand when the popover opens (system row uses `usage`).
// Skipped entirely on an SSH project: those identities are not what this project spends.
@@ -490,7 +498,7 @@ export function UsageIndicator({
providers: providers.filter((p) => !hidden.has(p.provider)),
// Its own switch, not Claude's: hiding the local rows must not silently take the SSH hosts
// down with them, and vice versa.
- remote: hidden.has('claude-remote') ? [] : remote
+ remote: remote.filter(r => !hidden.has(r.provider === 'codex' ? 'codex' : 'claude-remote'))
})
const claudeUsage = scoped.claude
const visibleProviders = scoped.providers
@@ -499,7 +507,8 @@ export function UsageIndicator({
// Only providers the user has actually enabled reach the pill; render whenever ANY of them
// (Claude included) has something to say. Both rules are pure and pinned by tests — gating on
// Claude alone, which is what this did, left a Codex-only user with no pill at all.
- const enabled = enabledProviders(visibleProviders)
+ const enabled = enabledProviders([...visibleProviders,
+ ...visibleRemote.flatMap(r => r.provider === 'codex' ? [r.usage] : [])])
if (!hasAnyUsage(claudeUsage, visibleProviders, visibleRemote)) return null
// On an SSH project these are the HOST's limits — same shape, same labels, read somewhere else.
@@ -507,8 +516,10 @@ export function UsageIndicator({
const status = claudeUsage?.status ?? visibleRemote[0]?.usage.status ?? 'unavailable'
const hasData = limits.length > 0 || enabled.length > 0
const fetching = refreshing
- const providerError = visibleProviders.some((p) => p.status === 'error')
- const claudeError = status === 'error'
+ const providerError = visibleProviders.some((p) => p.status === 'error') ||
+ visibleRemote.some(r => r.provider === 'codex' && r.usage.status === 'error')
+ const claudeError = claudeUsage?.status === 'error' ||
+ visibleRemote.some(r => r.provider !== 'codex' && r.usage.status === 'error')
const isError = claudeError || providerError
// The pill leads with whatever is closest to biting, so a scoped model cap that is nearly
// exhausted can't hide behind a comfortable 5h window. Considers every enabled provider, not
@@ -520,16 +531,16 @@ export function UsageIndicator({
e.stopPropagation()
if (refreshing) return
setRefreshing(true)
+ const requestedScope = remoteScope.current
try {
// ⟳ refreshes what is actually on screen. On an SSH project that is the host — forced past
// its debounce, since this is the only way to make it re-read before the cache expires —
// and the local snapshot is left alone rather than spending a request on rows nobody can see.
if (scope.kind === 'ssh') {
- setRemote(
- await window.nodeTerminal.usage
- .remote({ hostKey: scope.hostKey, force: true })
- .catch((): RemoteAccountUsage[] => [])
- )
+ const rows = await window.nodeTerminal.usage
+ .remote({ hostKey: scope.hostKey, force: true })
+ .catch((): RemoteAccountUsage[] => [])
+ if (remoteScope.current === requestedScope) setRemote(rows)
} else {
setUsage(await window.nodeTerminal.usage.refresh())
}
@@ -571,7 +582,7 @@ export function UsageIndicator({
const worst = primaryLimit(p.limits)
if (!worst) return null
return (
- <span key={p.provider} className="usage-pill__provider">
+ <span key={providerRowKey(p)} className="usage-pill__provider">
{(limits.length > 0 || i > 0) && <span className="usage-pill__sep">·</span>}
<span className="usage-pill__num">
{percentNumber(worst.usedPercent, percentMode)}% {labelFor(p.provider)}
@@ -664,7 +675,9 @@ export function UsageIndicator({
were read somewhere other than this machine. */}
{/* The same offer on an SSH project's rows — scoped as ever: only the host's system
identity and THIS host's managed accounts are actionable (accountRowAction). */}
- {visibleRemote.map((r) => (
+ {visibleRemote.map((r) => r.provider === 'codex' ? (
+ <ProviderBlock key={`codex:${r.hostKey}:${r.accountId ?? ''}`} u={r.usage} mode={percentMode} hostKey={r.hostKey} />
+ ) : (
<RemoteUsageBlock
key={`${r.hostKey}#${r.accountId ?? ''}`}
row={r}
diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsx
index 7828043b7..b6cbef528 100644
--- a/src/renderer/components/kanban/CardModal.tsx
+++ b/src/renderer/components/kanban/CardModal.tsx
@@ -16,6 +16,7 @@ import { nodeIconDialog } from '../NodeIconPicker'
import { applyIconChoice } from '../../lib/nodeIconChoice'
import type { NodeIcon } from '@shared/node-icon'
import { ContextMeter } from '../ContextMeter'
+import { isRemoteSessionNode } from '@shared/worktree'
import { AccountChip, useAccountChip } from '../AccountChip'
import { useAgentStatus } from '../../state/agentStatus'
import { useCardPanel } from '../../state/cardPanel'
@@ -78,6 +79,7 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,
// StickyNode's toggle, so the canvas and the card can't disagree about how a note reads).
const [editingNote, setEditingNote] = useState(false)
const agentSessionId = useAgentStatus((st) => st.byId[session.id]?.sessionId)
+ const observedAgentId = useAgentStatus((st) => st.byId[session.id]?.agentId)
const paused = useAgentStatus((st) => !!st.byId[session.id]?.paused)
const dropped = useAgentStatus((st) => !!st.byId[session.id]?.dropped)
// Same chip as the card and the canvas node header — the modal is where a user checks WHICH
@@ -326,7 +328,7 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,
{isTerminal && (
<>
{/* Same context-window pill + popover as the node header (null until usage data). */}
- <ContextMeter sessionId={agentSessionId ?? null} />
+ <ContextMeter sessionId={agentSessionId ?? null} nodeId={session.id} remote={isRemoteSessionNode(session.spawn)} agentId={session.agentId ?? session.spawn.agentId ?? observedAgentId} />
<button
className="kanban-modal__action"
title="Search this terminal"
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index 5f81189e9..1356b70e3 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -1,3 +1,4 @@
+import { useContextEnsure } from '../../terminal/useContextEnsure'
import { ptyRefusal } from '@shared/pty-refusal'
import { patchImeModeSwitch } from '../../terminal/ime-mode-switch'
@@ -106,12 +107,15 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda
const fitRef = useRef<FitAddon | null>(null)
const transportRef = useRef<LocalTransport | null>(null)
const agentSessionId = useAgentStatus((s) => s.byId[nodeId]?.sessionId)
+ const observedAgentId = useAgentStatus((s) => s.byId[nodeId]?.agentId)
// MIRROR TerminalNode: transcript READS go to the account the session is actually running as,
// which for a plain terminal is only ever the observed one. The spawn below keeps
// `spawn.accountId` — launch identity stays creation-time.
const observedAccount = useAgentStatus((s) => s.byId[nodeId]?.account)
// …resolved against the live account list, so linking the dir repoints the reader at once.
const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)
+ useContextEnsure(api.context, nodeId, spawn.agentId ?? observedAgentId, agentSessionId, spawn.cwd,
+ effectiveAccountId(spawn.accountId, observedAccount, claudeAccounts))
// One shallow-compared subscription for the whole appearance slice — see useXtermVisualSettings.
// MIRROR TerminalNode: scoped to the OWNING project (`owningProjectId`, the active one — a modal
// only ever opens over it), deliberately NOT this card's connection scope. `sshConnectionScope`
diff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsx
index fee8b1936..c5580503c 100644
--- a/src/renderer/components/kanban/SessionCard.tsx
+++ b/src/renderer/components/kanban/SessionCard.tsx
@@ -3,6 +3,7 @@ import type { KanbanCardMeta, KanbanLabel, KanbanPriority } from '@shared/types'
import { useAgentStatus } from '../../state/agentStatus'
import { AccountChip, useAccountChip } from '../AccountChip'
import { ContextMeter } from '../ContextMeter'
+import { isRemoteSessionNode } from '@shared/worktree'
import { NodeIconView } from '../NodeIcon'
import { LabelChips } from './LabelChips'
import type { KanbanSession } from './KanbanView'
@@ -191,7 +192,7 @@ export const SessionCard = memo(function SessionCard({
<span className="kanban-card__stickytext">{stickyPreview}</span>
) : (
<>
- <ContextMeter sessionId={status?.sessionId ?? null} />
+ <ContextMeter sessionId={status?.sessionId ?? null} nodeId={session.id} remote={isRemoteSessionNode(session.spawn)} agentId={session.agentId ?? session.spawn.agentId ?? status?.agentId} />
<AccountChip chip={accountChip} />
{status?.session && (
<span className="kanban-card__session" title={status.session}>
diff --git a/src/renderer/lib/usageScope.ts b/src/renderer/lib/usageScope.ts
index 3734af3a7..b8d54696e 100644
--- a/src/renderer/lib/usageScope.ts
+++ b/src/renderer/lib/usageScope.ts
@@ -125,11 +125,12 @@ export function scopeUsage(input: ScopeInput): ScopedUsage {
}
}
const rows = remote.filter((r) => r.hostKey === scope.hostKey)
- const system = rows.find((r) => r.accountId === null)
+ const claudeRows = rows.filter(r => r.provider !== 'codex')
+ const system = claudeRows.find((r) => r.accountId === null)
const leading =
system && system.usage.limits.length > 0
? system
- : (rows.find((r) => r.usage.limits.length > 0) ?? system)
+ : (claudeRows.find((r) => r.usage.limits.length > 0) ?? system)
return {
// The local machine's Claude, its managed accounts and the local billing providers are all
// credentials you are NOT spending while you work on the host.
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 6e925826f..572596e96 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -1,3 +1,4 @@
+import { useContextEnsure } from '../terminal/useContextEnsure'
import { ptyRefusal } from '@shared/pty-refusal'
import { patchImeModeSwitch } from '../terminal/ime-mode-switch'
@@ -1873,36 +1874,7 @@ export function TerminalNode({
// Use the chat panel only for a chat-capable agent with a known session; otherwise the
// markdown-of-output view (computed in the capture effect below) is shown as a fallback.
const useChat = mdMode && showChat && !!status?.sessionId
- // Feed the context meter without waiting for a live hook event: after an app restart the
- // continuing tmux session is idle and emits no event, so the core tailer is never re-fed.
- // Re-runs if the sessionId changes (track is idempotent). cwd is a path fallback.
- //
- // Gated on `showUsage` — the METER's own capability — and NOT on `claudeTranscript`, which still
- // gates the find bar's transcript index one line below. That is the opposite of the rule this
- // site used to carry, and the reason is that the thing the rule protected against moved: the
- // handler no longer resolves every agent through claude's `resolveTranscript` (whose cwd fallback
- // answers *the newest claude transcript for that cwd*, i.e. a stranger's session for a
- // codex/gemini id). It now routes on `agentId` to that agent's OWN locator and tail
- // (`core/context-ensure.ts`), so the gate can finally be the capability the feature actually
- // needs. Both extra arguments are load-bearing, not diagnostics: `id` is how the handler learns
- // this session runs on an SSH project's host (no local resolver can see that transcript), and
- // `agentId` is what picks the resolver. An agent with no rehydration path (grok) is refused
- // there, not here — one closed switch beside the tails, rather than a second list to keep in
- // sync. See lib/transcriptGates.ts for the gate that did NOT move.
- useEffect(() => {
- const sid = status?.sessionId
- if (showUsage && sid)
- window.nodeTerminal.context.ensure(
- sid,
- (data.cwd as string) || undefined,
- accountForReads,
- id,
- agentId
- )
- // `accountForReads`, not `data.accountId`: the transcript this meter tails lives under the
- // account the session is RUNNING as, which for a plain terminal is only ever the observed one.
- // It can arrive after mount (the first hook event), hence its place in the deps.
- }, [showUsage, status?.sessionId, data.cwd, accountForReads, id, agentId])
+ useContextEnsure(session.api.context, id, agentId, status?.sessionId, (data.cwd as string) || undefined, accountForReads)
const updateNodeInternals = useUpdateNodeInternals()
const [searchOpen, setSearchOpen] = useState(false)
@@ -5478,7 +5450,7 @@ export function TerminalNode({
SSH {(data.ssh as SshConnection).user}@{(data.ssh as SshConnection).host}
</span>
) : null}
- {showUsage && <ContextMeter sessionId={status?.sessionId ?? null} />}
+ {showUsage && <ContextMeter sessionId={status?.sessionId ?? null} nodeId={id} remote={!!remoteSession} agentId={agentId} />}
{/* Who else is in this node. Subscribes to presence itself — see PresenceChips. */}
<PresenceChips nodeId={id} />
{status?.state === 'working' && (
diff --git a/src/renderer/nodes/title-gate.test.ts b/src/renderer/nodes/title-gate.test.ts
index 5054bea99..958cbc832 100644
--- a/src/renderer/nodes/title-gate.test.ts
+++ b/src/renderer/nodes/title-gate.test.ts
@@ -161,16 +161,7 @@ describe('claude-transcript gates', () => {
* from a local one, which is what issue #813 reported. `core/context-ensure.test.ts` pins the
* routing itself.
*/
- it('passes the agent + node id to the mount-time meter rehydration (`context.ensure`)', () => {
- const found = sites('window.nodeTerminal.context.ensure(')
- expect(found.length).toBe(1)
- const [lineNo] = found[0]
- // The `if (…) ensure(…)` guard is the line above the call; the arguments follow it.
- const call = lines.slice(Math.max(0, lineNo - 3), lineNo + 7).join('\n')
- expect(call, `${lineNo}: context.ensure guard`).toContain('showUsage')
- expect(call, `${lineNo}: context.ensure routes per agent`).toContain('agentId')
- expect(call, `${lineNo}: context.ensure carries the node id`).toMatch(/^\s*id,$/m)
- })
+
it('gates the find bar’s transcript index (`searchTranscript`)', () => {
const found = sites('searchTranscript:')
diff --git a/src/renderer/state/contextWindow.test.ts b/src/renderer/state/contextWindow.test.ts
index a5555eb35..dad257ad4 100644
--- a/src/renderer/state/contextWindow.test.ts
+++ b/src/renderer/state/contextWindow.test.ts
@@ -1,6 +1,25 @@
// @vitest-environment jsdom
import { expect, it, vi } from 'vitest'
+it('keeps copied remote session ids separate and ignores stale clears for another session', async () => {
+ vi.resetModules()
+ const { useContextWindow } = await import('./contextWindow')
+ const usage = { sessionId: 'copied', usedTokens: 10, windowTokens: 100, usedPercent: 10, model: 'gpt', updatedAt: 1, windowSource: 'transcript' as const }
+ const put = useContextWindow.getState().set
+ put(usage)
+ put({ ...usage, nodeId: 'host-a', usedTokens: 20 })
+ put({ ...usage, nodeId: 'host-b', usedTokens: 70 })
+ expect(useContextWindow.getState().bySessionId.copied.usedTokens).toBe(10)
+ expect(useContextWindow.getState().byNodeId['host-a'].usedTokens).toBe(20)
+ expect(useContextWindow.getState().byNodeId['host-b'].usedTokens).toBe(70)
+ put({ ...usage, nodeId: 'host-a', sessionId: 'new' })
+ put({ ...usage, nodeId: 'host-a', cleared: true })
+ expect(useContextWindow.getState().byNodeId['host-a'].sessionId).toBe('new')
+ put({ ...usage, nodeId: 'host-a', sessionId: 'new', cleared: true })
+ expect(useContextWindow.getState().byNodeId['host-a']).toBeUndefined()
+ expect(useContextWindow.getState().byNodeId['host-b'].usedTokens).toBe(70)
+})
+
it('does not restore an old denominator from persistent browser state', async () => {
localStorage.setItem('nodeterm.contextWindow', JSON.stringify({ old: { sessionId: 'old', windowTokens: 200000 }, claude: { sessionId: 'claude', windowSource: 'session-env', windowTokens: 32000 }, own: { sessionId: 'own', windowSource: 'transcript', windowTokens: 64000 } }))
vi.resetModules()
diff --git a/src/renderer/state/contextWindow.ts b/src/renderer/state/contextWindow.ts
index 54ed4f7a1..b2c47d6cc 100644
--- a/src/renderer/state/contextWindow.ts
+++ b/src/renderer/state/contextWindow.ts
@@ -25,7 +25,8 @@ function load(): Record<string, ContextWindowUsage> {
function persistable(map: Record<string, ContextWindowUsage>): Record<string, ContextWindowUsage> {
// Older records have no provenance; invalidate them instead of guessing their agent.
- return Object.fromEntries(Object.entries(map).filter(([, usage]) => usage?.windowSource === 'transcript'))
+ return Object.fromEntries(Object.entries(map).filter(([, usage]) =>
+ usage?.windowSource === 'transcript' && !usage.nodeId && !usage.cleared))
}
/** Keep only the MAX_SESSIONS most-recently-updated entries (LRU by updatedAt). */
@@ -55,13 +56,26 @@ function scheduleSave(bySessionId: Record<string, ContextWindowUsage>): void {
interface ContextWindowState {
bySessionId: Record<string, ContextWindowUsage>
+ /** Remote observations are node-owned and never restored from browser storage. */
+ byNodeId: Record<string, ContextWindowUsage>
set(usage: ContextWindowUsage): void
}
export const useContextWindow = create<ContextWindowState>((set) => ({
bySessionId: load(),
+ byNodeId: {},
set: (usage) =>
set((s) => {
+ if (usage.nodeId) {
+ if (usage.cleared) {
+ if (s.byNodeId[usage.nodeId]?.sessionId !== usage.sessionId) return s
+ const byNodeId = { ...s.byNodeId }
+ delete byNodeId[usage.nodeId]
+ return { byNodeId }
+ }
+ return { byNodeId: prune({ ...s.byNodeId, [usage.nodeId]: usage }) }
+ }
+ if (usage.cleared) return s
const merged = { ...s.bySessionId, [usage.sessionId]: usage }
const bySessionId = prune(merged)
scheduleSave(bySessionId)
diff --git a/src/renderer/terminal/useContextEnsure.test.tsx b/src/renderer/terminal/useContextEnsure.test.tsx
new file mode 100644
index 000000000..3af15a886
--- /dev/null
+++ b/src/renderer/terminal/useContextEnsure.test.tsx
@@ -0,0 +1,45 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { expect, it, vi } from 'vitest'
+import type { ContextApi } from '@shared/types'
+import type { AgentId } from '@shared/agents/config'
+import { useContextEnsure } from './useContextEnsure'
+
+function Probe({ api, node = 'canvas', sid = 's1', account = 'a', agent = 'codex' }: {
+ api: ContextApi; node?: string; sid?: string; account?: string; agent?: AgentId
+}) {
+ useContextEnsure(api, node, agent, sid || undefined, '/remote/repo', account)
+ return null
+}
+it('rehydrates canvas/modal mounts and changed node, account, session and core identities', async () => {
+ const first = { ensure: vi.fn(), onUpdate: vi.fn() }, second = { ensure: vi.fn(), onUpdate: vi.fn() }
+ const local = vi.fn()
+ Object.defineProperty(window, 'nodeTerminal', { configurable: true, value: { context: { ensure: local } } })
+ const root = createRoot(document.createElement('div'))
+ try {
+ await act(async () => root.render(<Probe api={first} />))
+ expect(first.ensure).toHaveBeenLastCalledWith('s1', '/remote/repo', 'a', 'canvas', 'codex')
+ await act(async () => root.render(<Probe api={first} account="b" />))
+ expect(first.ensure).toHaveBeenLastCalledWith('s1', '/remote/repo', 'b', 'canvas', 'codex')
+ await act(async () => root.render(<Probe api={second} account="b" />))
+ expect(second.ensure).toHaveBeenLastCalledWith('s1', '/remote/repo', 'b', 'canvas', 'codex')
+ await act(async () => root.render(<Probe api={second} node="modal" sid="s2" />))
+ expect(second.ensure).toHaveBeenLastCalledWith('s2', '/remote/repo', 'a', 'modal', 'codex')
+ await act(async () => root.render(null))
+ await act(async () => root.render(<Probe api={second} node="modal" sid="s2" />))
+ expect(second.ensure).toHaveBeenCalledTimes(3)
+ expect(local).not.toHaveBeenCalled()
+ } finally { await act(async () => root.unmount()) }
+})
+it('does not ask for an unknown session or unsupported agent; keeps Claude routing', async () => {
+ const api = { ensure: vi.fn(), onUpdate: vi.fn() }
+ const root = createRoot(document.createElement('div'))
+ try {
+ await act(async () => root.render(<Probe api={api} sid="" />))
+ await act(async () => root.render(<Probe api={api} agent="custom:unsupported" />))
+ expect(api.ensure).not.toHaveBeenCalled()
+ await act(async () => root.render(<Probe api={api} agent="claude" account="claude-account" />))
+ expect(api.ensure).toHaveBeenCalledWith('s1', '/remote/repo', 'claude-account', 'canvas', 'claude')
+ } finally { await act(async () => root.unmount()) }
+})
diff --git a/src/renderer/terminal/useContextEnsure.ts b/src/renderer/terminal/useContextEnsure.ts
new file mode 100644
index 000000000..58f20d053
--- /dev/null
+++ b/src/renderer/terminal/useContextEnsure.ts
@@ -0,0 +1,16 @@
+import { useEffect } from 'react'
+import { capabilityAgentId, hasUsage, type AgentId } from '@shared/agents/config'
+import type { ContextApi } from '@shared/types'
+
+/** Canvas and board co-attach share the same account/agent-aware mount-time read. The backend
+ * resolves on the owning host; this capability gate must never enable Claude's search resolver. */
+export function useContextEnsure(
+ api: ContextApi, nodeId: string, agentId: AgentId | undefined, sessionId: string | null | undefined,
+ cwd: string | undefined, accountId: string | undefined
+): void {
+ useEffect(() => {
+ if (agentId && hasUsage(agentId) && sessionId) {
+ api.ensure(sessionId, cwd, accountId, nodeId, capabilityAgentId(agentId))
+ }
+ }, [api, nodeId, agentId, sessionId, cwd, accountId])
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index e23431008..e6c067180 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2595,21 +2595,25 @@ export interface ClaudeUsage {
}
/**
- * One REMOTE (SSH host) Claude identity's usage, read on that host over the project's
+ * One REMOTE (SSH host) Claude or Codex identity's usage, read on that host over the project's
* ControlMaster. Separate from the local per-account rows because the identity is only
* meaningful together with the host it lives on — the same email can be logged in on two
* machines with two different quotas in flight.
*/
-export interface RemoteAccountUsage {
+interface RemoteAccountUsageBase {
/** `user@host` of the connection the numbers came from. */
hostKey: string
- /** Managed remote account id, or null for that host's system `~/.claude`. */
+ /** Managed remote account id, or null for that provider's system identity on the host. */
accountId: string | null
/** Display label: the managed account's label, else the host key. */
label: string
- usage: ClaudeUsage
}
+export type RemoteAccountUsage = RemoteAccountUsageBase & (
+ | { provider?: 'claude'; usage: ClaudeUsage }
+ | { provider: 'codex'; usage: ProviderUsage }
+)
+
/** What the usage indicator wants from the remote hosts right now. */
export interface RemoteUsageQuery {
/** Read only this `user@host` — the machine the active project runs on. Omitted = every
@@ -2646,6 +2650,10 @@ export interface UsageApi {
/** A Claude session's context-window fill, pushed per sessionId from the transcript tailer. */
export interface ContextWindowUsage {
+ /** Remote Codex observations are node-scoped; equal thread ids on different hosts never mix. */
+ nodeId?: string
+ /** Invalidates this node/session observation after its remote scope changes or disappears. */
+ cleared?: true
/** Missing on older hosts; only session-env is an observed Claude configuration. */
windowSource?: 'session-env' | 'transcript' | 'estimate'
sessionId: string
diff --git a/src/shared/usage-limits.test.ts b/src/shared/usage-limits.test.ts
index 54f00c790..ba9d90cdc 100644
--- a/src/shared/usage-limits.test.ts
+++ b/src/shared/usage-limits.test.ts
@@ -138,7 +138,7 @@ describe('hasAnyUsage', () => {
})
})
-function remoteRow(over: Partial<RemoteAccountUsage> & { limits?: UsageLimit[] } = {}): RemoteAccountUsage {
+function remoteRow(over: Partial<Extract<RemoteAccountUsage, { provider?: 'claude' }>> & { limits?: UsageLimit[] } = {}): RemoteAccountUsage {
const { limits = [], ...rest } = over
return {
hostKey: '[email protected]',