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.

fix(context-meter): rehydrate at mount on remote and non-claude nodes

enesc9a0046af18a
diff --git a/CLAUDE.md b/CLAUDE.md
index b686a7f07..6dbd15e6d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1577,9 +1577,13 @@ else, and its context links must keep classifying across restarts).
- **`hasUsage` gated THREE features, not one.** Joining `USAGE_CAPABLE` also switched on
`context.ensure` and the find bar's transcript index, both of which go through claude's
`resolveTranscript` — whose **cwd fallback** then handed a codex node *the newest claude transcript
- for that cwd*: a stranger's session as its meter and its search hits. Now gated by the pure
- `readsClaudeTranscript` (`renderer/lib/transcriptGates.ts`), which reuses `CHAT_CAPABLE` rather than
- adding a fourth list. Non-claude agents lose only the mount-time head start.
+ for that cwd*: a stranger's session as its meter and its search hits. Gated by the pure
+ `readsClaudeTranscript` (`renderer/lib/transcriptGates.ts`) rather than by a fourth list.
+ `context.ensure` LEFT that gate in 2026-09 (issue #813) once its handler stopped *being* claude's
+ resolver — see **Context-meter rehydration** below; the find bar's index still has no routing and
+ so has not moved. The lasting rule is the one the episode taught: **grep every consumer of a
+ helper before adding an id to its list**, and when two consumers need different answers, route
+ the one that can be routed instead of widening the gate for both.
- **`TITLE_READ_CAPABLE` was created here**: gemini names its own sessions through its `update_topic`
tool (the title is in that call's `args.title`, NOT a top-level field) but has no rename command, so
the read and write legs split. Its read path is the transcript the context tail already tracks
@@ -1589,6 +1593,44 @@ else, and its context links must keep classifying across restarts).
because `/quit --delete` exits *and permanently deletes* the session history, i.e. exactly what the
restart exists to resume (pinned by its own test).
Full picture, measurements, gaps and a device checklist: **`docs/gemini-agent.md`**.
+- **Context-meter rehydration (`context:ensure`)** — the meter is fed by hook events, and a tmux
+ session outlives the app, so a continuing session that is idle after a restart emits nothing and
+ its meter stays blank until the user's next prompt. The mount-time read that exists to close that
+ is `core/context-ensure.ts` (`registerContextEnsureIpc`), **in core so BOTH shells serve it** — it
+ used to be inline in `src/main/index.ts` and the Server Edition had no handler at all, so a browser
+ node's meter filled only on its next turn too (issue #813; the identical hole
+ `core/transcript-ipc.ts` was moved to core to close). Three rules:
+ - **It routes per agent; it does not widen a gate.** `agentId` picks that agent's OWN locator and
+ tail — claude → `resolveTranscript`, codex → `locateCodex`, gemini → `locateGemini` (the last two
+ keyed STRICTLY by session id, no cwd fallback, so neither can adopt a session that is not its
+ own). A closed switch: an agent that is not in it gets **no meter**, never claude's resolver.
+ That is what let the renderer gate move from `readsClaudeTranscript` to `showUsage` — the danger
+ was never the meter, it was one resolver answering for four agents. **grok is deliberately
+ absent**: its meter reads a `signals.json` whose directory is learned from a hook event, so after
+ a restart there is nothing to rehydrate FROM (`locateGrok` resolves a different file, the
+ conversation). Structural, not pending.
+ - **A remote node is resolved on its HOST or not at all.** The desktop injects `ensureRemote`,
+ which asks the host through `remoteTranscriptRefFor` — the ⌘M path's locator, jail
+ (`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).
+ - **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
+ blank until the next turn anyway, which is the bug arriving by another route. The only
+ de-duplication is of **concurrent in-flight** calls (a canvas mounts dozens of remote nodes at
+ once and each resolve is an ssh exec on someone else's machine); it releases on settle, so it is
+ not a cache. **No timer** — one read at mount, the same rule Remote usage and session memory
+ follow.
+ Surfaces: Desktop full; **Server Edition** full and local-only (it runs ON the host whose
+ transcripts it reads — the legitimate asymmetry, stated the way the SSH skip is); kanban card +
+ card modal render the same `ContextMeter` from the same store and inherit it; mobile N/A (its own
+ context display, separate path). Tests: `core/context-ensure.test.ts` (routing, remote
+ fall-through, no negative cache) + `main/context-ensure-wiring.test.ts` (the shell's closure, at
+ source level, because it closes over `ptyManager`/`sshProjectManager`).
- **Permission mode** (agents in `PERMISSION_MODE_CAPABLE` — claude, grok, **gemini**, **codex**) —
the mode a session **starts** in (`claude --permission-mode <mode>`; Shift+Tab still cycles it at
runtime). Membership no longer implies claude's flag spelling: **the per-agent translation lives in
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f52e7a065..e856e4fbb 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -49,7 +49,12 @@ The repo is split by Electron process boundary and the split is enforced, not ad
**Put new service logic in `src/core` behind `CorePlatform`, not inline in `src/main`.** That is the
seam the Server Edition boots from; logic left in `src/main` silently does not exist there, and the
-boundary tests cannot tell you a feature is *missing*.
+boundary tests cannot tell you a feature is *missing*. This keeps happening to the same subsystem:
+the ⌘M transcript read and then the context meter's `context:ensure` both shipped desktop-only, and
+in both cases the browser cast the message into the void and the feature just looked empty. If your
+handler needs something only Electron has (an SSH ControlMaster, a native dialog), make that an
+**injected dep** whose absence is a documented degrade — see `registerTranscriptIpc` /
+`registerContextEnsureIpc` — rather than a reason to keep the whole handler in `src/main`.
## Three surfaces
diff --git a/src/core/context-ensure.test.ts b/src/core/context-ensure.test.ts
new file mode 100644
index 000000000..d3db94977
--- /dev/null
+++ b/src/core/context-ensure.test.ts
@@ -0,0 +1,241 @@
+// The context meter's mount-time rehydration (issue #813).
+//
+// Four properties, each of which was a real failure before this handler existed:
+// 1. a REMOTE node resolves on its host and never on this machine's disk;
+// 2. a remote resolve that FAILED is not remembered as an absence;
+// 3. codex and gemini rehydrate from THEIR OWN transcripts — and a codex node never, under any
+// circumstance, reaches claude's resolver (the regression `readsClaudeTranscript` exists to
+// prevent, now pinned at the layer that actually routes);
+// 4. an agent with no rehydration path (grok) gets nothing rather than somebody else's numbers.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { fakePlatform } from './platform-fake'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { registerContextEnsureIpc, type ContextEnsureQuery } from './context-ensure'
+import type { ContextTail } from './context-tail'
+import { IPC } from '../shared/ipc'
+
+const SID = '46b36ce2-dd77-4f5e-a89e-4a0e831e83df'
+const CWD = '/srv/app'
+
+/** A ContextTail that only records what it was asked to track. */
+function fakeTail(): ContextTail & { tracked: [string | undefined, string | undefined][] } {
+ const tracked: [string | undefined, string | undefined][] = []
+ return {
+ tracked,
+ track: (sessionId, transcriptPath) => void tracked.push([sessionId, transcriptPath]),
+ untrack: () => {},
+ pathFor: () => undefined
+ }
+}
+
+let home: string
+let f: ReturnType<typeof fakePlatform>
+let claude: ReturnType<typeof fakeTail>
+let codex: ReturnType<typeof fakeTail>
+let gemini: ReturnType<typeof fakeTail>
+
+// The registered listener is async; `CorePlatform.on` types its return as void (a cast is
+// fire-and-forget on the wire), so awaiting it here — which is what lets these tests assert on the
+// resolve's RESULT rather than on a timer — needs the hop through `unknown`.
+const ensure = (over: Partial<ContextEnsureQuery> = {}): Promise<void> =>
+ f.listeners[IPC.contextEnsure](
+ over.sessionId ?? SID,
+ 'cwd' in over ? over.cwd : CWD,
+ over.accountId,
+ over.nodeId,
+ over.agentId
+ ) as unknown as Promise<void>
+
+const tailFor = (agentId: string | undefined): ContextTail | undefined => {
+ switch (agentId) {
+ case undefined:
+ case 'claude':
+ return claude
+ case 'codex':
+ return codex
+ case 'gemini':
+ return gemini
+ default:
+ return undefined
+ }
+}
+
+/** Write a claude transcript for SID under `~/.claude/projects/<encoded cwd>/`. */
+function writeClaudeTranscript(sessionId = SID): string {
+ const dir = path.join(home, '.claude', 'projects', '-srv-app')
+ fs.mkdirSync(dir, { recursive: true })
+ const p = path.join(dir, `${sessionId}.jsonl`)
+ fs.writeFileSync(p, '{"type":"user","message":{"content":"hi"}}\n')
+ return p
+}
+
+beforeEach(() => {
+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-context-ensure-'))
+ vi.spyOn(os, 'homedir').mockReturnValue(home)
+ f = fakePlatform()
+ initPlatform(f)
+ claude = fakeTail()
+ codex = fakeTail()
+ gemini = fakeTail()
+})
+afterEach(() => {
+ vi.restoreAllMocks()
+ resetPlatformForTests()
+ fs.rmSync(home, { recursive: true, force: true })
+})
+
+describe('local rehydration, per agent', () => {
+ it('tracks a claude session on claude’s tail from its own transcript', async () => {
+ const p = writeClaudeTranscript()
+ registerContextEnsureIpc({ tailFor })
+ await ensure({ agentId: 'claude' })
+ expect(claude.tracked).toEqual([[SID, p]])
+ })
+
+ it('still resolves as claude when no agent id is sent (the legacy call shape)', async () => {
+ const p = writeClaudeTranscript()
+ registerContextEnsureIpc({ tailFor })
+ await ensure({})
+ expect(claude.tracked).toEqual([[SID, p]])
+ })
+
+ it('rehydrates a codex node from codex’s OWN rollout, on codex’s tail', async () => {
+ const dir = path.join(home, '.codex', 'sessions', '2026', '09', '18')
+ fs.mkdirSync(dir, { recursive: true })
+ const rollout = path.join(dir, `rollout-2026-09-18T10-00-00-${SID}.jsonl`)
+ fs.writeFileSync(rollout, '{}\n')
+ registerContextEnsureIpc({ tailFor })
+ await ensure({ agentId: 'codex' })
+ expect(codex.tracked).toEqual([[SID, rollout]])
+ expect(claude.tracked).toEqual([])
+ })
+
+ it('rehydrates a gemini node from gemini’s own chat file, on gemini’s tail', async () => {
+ const chats = path.join(home, '.gemini', 'tmp', 'proj', 'chats')
+ fs.mkdirSync(chats, { recursive: true })
+ const chat = path.join(chats, 'session-1.jsonl')
+ fs.writeFileSync(chat, `${JSON.stringify({ sessionId: SID })}\n`)
+ registerContextEnsureIpc({ tailFor })
+ await ensure({ agentId: 'gemini' })
+ expect(gemini.tracked).toEqual([[SID, chat]])
+ expect(claude.tracked).toEqual([])
+ })
+
+ /**
+ * THE regression this routing exists to prevent, and the reason the renderer gate could move.
+ *
+ * Claude's `resolveTranscript` falls back to *the newest claude transcript for the cwd* when its
+ * sessionId leg misses — and a codex session id ALWAYS misses, since no `<that id>.jsonl` exists
+ * under `~/.claude/projects`. So the scenario below (a codex node sharing a cwd with a claude
+ * session, which is the normal case: they are two nodes on one project) is exactly where a
+ * gate-widening without routing hands the codex node a stranger's conversation — wrong numerator,
+ * wrong denominator, then flapping against the correct codex tail.
+ *
+ * Pinned on BOTH tails: nothing claude-shaped may be tracked anywhere for a codex node.
+ */
+ it('NEVER resolves a codex node through claude’s transcript, even sharing its cwd', async () => {
+ writeClaudeTranscript('11111111-2222-3333-4444-555555555555') // a stranger's session, same cwd
+ registerContextEnsureIpc({ tailFor })
+ await ensure({ agentId: 'codex' })
+ expect(codex.tracked).toEqual([])
+ expect(claude.tracked).toEqual([])
+ })
+
+ it('gives an agent with no rehydration path (grok) nothing at all', async () => {
+ writeClaudeTranscript()
+ registerContextEnsureIpc({ tailFor })
+ await ensure({ agentId: 'grok' })
+ expect([...claude.tracked, ...codex.tracked, ...gemini.tracked]).toEqual([])
+ })
+
+ it('ignores a malformed session id without touching any resolver', async () => {
+ writeClaudeTranscript()
+ registerContextEnsureIpc({ tailFor })
+ await ensure({ sessionId: '../../etc/passwd', agentId: 'claude' })
+ expect(claude.tracked).toEqual([])
+ })
+})
+
+describe('remote (SSH-project) rehydration', () => {
+ it('fills a remote node’s meter at mount, with no hook event — issue #813', async () => {
+ const seen: ContextEnsureQuery[] = []
+ registerContextEnsureIpc({
+ tailFor,
+ ensureRemote: async (q) => {
+ seen.push(q)
+ return 'tracked'
+ }
+ })
+ await ensure({ agentId: 'claude', nodeId: 'n1' })
+ // The remote leg owns it end to end: it received everything it needs to ask the HOST, and the
+ // local tail was never involved.
+ expect(seen).toEqual([
+ { sessionId: SID, cwd: CWD, accountId: undefined, nodeId: 'n1', agentId: 'claude' }
+ ])
+ expect(claude.tracked).toEqual([])
+ })
+
+ /**
+ * The load-bearing half. A remote session's transcript is on the other machine, so an unresolved
+ * remote answer must END the ensure — falling through would run claude's cwd fallback against
+ * THIS machine's disk and meter whatever local session happens to share the cwd, under the remote
+ * node's session id.
+ */
+ it('does not fall through to the local resolver when the host could not answer', async () => {
+ writeClaudeTranscript('99999999-2222-3333-4444-555555555555') // a local session, same cwd
+ registerContextEnsureIpc({ tailFor, ensureRemote: async () => 'unresolved' })
+ await ensure({ agentId: 'claude', nodeId: 'n1' })
+ expect(claude.tracked).toEqual([])
+ })
+
+ it('takes the local path for a node the remote leg says is not remote', async () => {
+ const p = writeClaudeTranscript()
+ registerContextEnsureIpc({ tailFor, ensureRemote: async () => null })
+ await ensure({ agentId: 'claude', nodeId: 'n1' })
+ expect(claude.tracked).toEqual([[SID, p]])
+ })
+
+ /**
+ * A failed read is never evidence of absence. The handler holds no negative memory of its own, so
+ * a resolve that failed because the ControlMaster was momentarily down is retried in full by the
+ * next ensure — which is what makes the meter heal on the next mount instead of staying blank
+ * until the session's next turn (i.e. the bug, re-arrived by another route).
+ */
+ it('remembers nothing after an unresolved remote attempt, and retries in full', async () => {
+ let attempt = 0
+ registerContextEnsureIpc({
+ tailFor,
+ ensureRemote: async () => (++attempt === 1 ? 'unresolved' : 'tracked')
+ })
+ await ensure({ agentId: 'claude', nodeId: 'n1' })
+ await ensure({ agentId: 'claude', nodeId: 'n1' })
+ expect(attempt).toBe(2)
+ })
+
+ /**
+ * De-duplicating CONCURRENT calls is not caching: a canvas of dozens of remote nodes mounts at
+ * once, and each resolve is an ssh exec on someone else's machine. The previous test pins that
+ * the guard releases, so this one can only be about overlap.
+ */
+ it('coalesces a second ensure that arrives while the first is still in flight', async () => {
+ let calls = 0
+ let release: () => void = () => {}
+ const gate = new Promise<void>((r) => (release = r))
+ registerContextEnsureIpc({
+ tailFor,
+ ensureRemote: async () => {
+ calls++
+ await gate
+ return 'tracked'
+ }
+ })
+ const a = ensure({ agentId: 'claude', nodeId: 'n1' })
+ const b = ensure({ agentId: 'claude', nodeId: 'n1' })
+ release()
+ await Promise.all([a, b])
+ expect(calls).toBe(1)
+ })
+})
diff --git a/src/core/context-ensure.ts b/src/core/context-ensure.ts
new file mode 100644
index 000000000..78e4243f1
--- /dev/null
+++ b/src/core/context-ensure.ts
@@ -0,0 +1,153 @@
+// The context meter's mount-time rehydration (`context:ensure`), registered through the
+// CorePlatform seam so BOTH shells serve it.
+//
+// This lived inline in `src/main/index.ts`, and the Server Edition had no handler at all — the
+// browser cast into the void, so a Server-Edition claude node's meter also filled only on its next
+// turn. Exactly the gap `core/transcript-ipc.ts` was moved here to close for the READ channels.
+//
+// What it is for: a tmux session outlives the app, so after a restart a continuing agent session is
+// idle and emits no hook event — and a hook event is the only other thing that ever feeds the
+// meter. Without a mount-time read the meter stays blank until the user sends a prompt.
+//
+// TWO rules shape everything below.
+//
+// 1. **Per agent, never one resolver for all of them.** Claude's `resolveTranscript` has a cwd
+// fallback that answers *the newest claude transcript for that cwd*, and a codex/gemini session
+// id always misses its sessionId leg — so pointing it at a non-claude node hands that node a
+// STRANGER's session as its meter (wrong numerator and wrong denominator), then flaps against
+// the correct tail. That is why `readsClaudeTranscript` gates the renderer today and why this
+// routes instead of widening it: each agent resolves through its OWN locator and tracks on its
+// OWN tail (whose own `parse` keeps the per-agent token formulas separate, as they must be).
+// 2. **A remote session is resolved on the HOST or not at all.** For an SSH-project node the
+// transcript is on the other machine; falling through to any local resolver searches this
+// machine's disk for a file that only ever existed there. So the remote leg's "could not
+// resolve" is TERMINAL, never a fall-through — and it is never remembered as an absence either
+// (see `ContextEnsureDeps.ensureRemote`).
+import { IPC } from '../shared/ipc'
+import { platform } from './platform'
+import type { ContextTail } from './context-tail'
+import { locateCodex, locateGemini } from './handoff/locate'
+import { resolveTranscript } from './transcript-ipc'
+import { SESSION_ID_RE } from './transcript-reader'
+
+/** What an ensure is asked for. `nodeId` is only meaningful to the remote leg. */
+export interface ContextEnsureQuery {
+ sessionId: string
+ cwd: string | undefined
+ accountId: string | undefined
+ nodeId: string | undefined
+ agentId: string | undefined
+}
+
+/**
+ * The remote leg's answer.
+ *
+ * `'tracked'` — the host was asked, a transcript was found, the remote tail now has it.
+ * `'unresolved'` — this IS a remote session and we do not have a path for it: the host looked and
+ * found nothing, the ControlMaster was down, the home was unresolved, or this agent has no remote
+ * locator at all. Deliberately ONE value: `remoteTranscriptRefFor` cannot tell a clean miss from
+ * a failed ssh call, and inventing that distinction here would be a claim the resolver cannot
+ * support. Both mean the same two things — no meter this pass, and NOTHING cached, so the next
+ * mount (or the next hook event) tries again from scratch. A failed read must never be
+ * remembered as an absence.
+ *
+ * `null` (not this type) means "not a remote session at all" — take the local path.
+ */
+export type RemoteEnsureOutcome = 'tracked' | 'unresolved'
+
+export interface ContextEnsureDeps {
+ /**
+ * 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`.
+ */
+ tailFor(agentId: string | undefined): ContextTail | undefined
+ /**
+ * Resolve + track a REMOTE (SSH-project) node's transcript on its host, or `null` when this is
+ * not a remote session — the same `null` convention `TranscriptIpcDeps.readRemote` uses, and the
+ * signal to take the local path below. Electron-only: the server has no SSH-project manager, and
+ * needs none (it runs ON the host whose transcripts it reads).
+ */
+ ensureRemote?(q: ContextEnsureQuery): Promise<RemoteEnsureOutcome | null>
+}
+
+/**
+ * Locate this agent's transcript on the LOCAL disk, or `undefined` when it has no local locator.
+ *
+ * A closed switch, not a default-to-claude: an agent that reaches here unrecognized gets NO meter,
+ * which is the pre-existing behaviour for every non-claude agent and can never be wrong. Adding one
+ * means adding its locator here, next to the tail that parses its numbers.
+ *
+ * - **claude** — `resolveTranscript`, including its `accountId`-scoped cwd fallback (correct here:
+ * the file genuinely is claude's, and the account scoping is what keeps a managed-account node
+ * off the system root).
+ * - **codex / gemini** — `locateCodex` / `locateGemini`, keyed STRICTLY by session id with no cwd
+ * fallback, so neither can adopt a session that is not its own.
+ * - **grok** — none, and that is by construction rather than an omission. Grok's meter reads
+ * `signals.json` out of a session directory learned from a hook event (`grokSessionDirFor`),
+ * which is empty after a restart; `locateGrok` resolves a different file entirely
+ * (`chat_history.jsonl`, the conversation). There is nothing to rehydrate from.
+ */
+function localTranscriptFor(
+ q: ContextEnsureQuery,
+ pathFor?: (s: string) => string | undefined
+): Promise<string | undefined> {
+ switch (q.agentId) {
+ // `undefined` is the legacy call shape (the channel carried no agent id, and its one caller was
+ // claude-gated), so it keeps resolving as claude — byte-identical to the pre-split handler.
+ case undefined:
+ case 'claude':
+ return resolveTranscript(
+ { sessionId: q.sessionId, cwd: q.cwd, accountId: q.accountId },
+ pathFor
+ )
+ case 'codex':
+ return locateCodex(q.sessionId)
+ case 'gemini':
+ return locateGemini(q.sessionId)
+ default:
+ return Promise.resolve(undefined)
+ }
+}
+
+export function registerContextEnsureIpc(deps: ContextEnsureDeps): void {
+ // Ensure calls arrive on mount, and the renderer's effect re-runs when the session id, cwd or
+ // observed account changes — so the same session can be asked for twice while the first answer
+ // (an ssh round-trip, on a canvas that can hold dozens of remote nodes) is still in flight.
+ // De-duplicating the IN-FLIGHT call is not a cache: nothing is remembered once it settles, so a
+ // resolve that failed is retried by the next ensure exactly as if this guard were not here.
+ const inFlight = new Set<string>()
+
+ platform().on(
+ IPC.contextEnsure,
+ async (
+ sessionId?: string,
+ cwd?: string,
+ accountId?: string,
+ nodeId?: string,
+ agentId?: string
+ ): 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}`
+ if (inFlight.has(key)) return
+ inFlight.add(key)
+ try {
+ // Remote first, and its answer is TERMINAL either way. A remote session that could not be
+ // resolved must not fall through to the local resolver: that reads the wrong machine's
+ // disk, which for claude means metering an unrelated local session under this node's id.
+ if (deps.ensureRemote && (await deps.ensureRemote(q)) !== null) return
+ const tail = deps.tailFor(agentId)
+ if (!tail) return
+ // The tail's own path is the authoritative hint for claude's resolver (hook-fed when
+ // present) AND the early-out for everyone: a session already tracked needs no scan.
+ if (tail.pathFor(sessionId)) return
+ const p = await localTranscriptFor(q, (s) => tail.pathFor(s))
+ if (p) tail.track(sessionId, p)
+ } finally {
+ inFlight.delete(key)
+ }
+ }
+ )
+}
diff --git a/src/main/context-ensure-wiring.test.ts b/src/main/context-ensure-wiring.test.ts
new file mode 100644
index 000000000..75c29f91b
--- /dev/null
+++ b/src/main/context-ensure-wiring.test.ts
@@ -0,0 +1,95 @@
+// 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)
+}
+
+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('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')
+ })
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index 4a01bc7de..05d422eed 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -188,6 +188,7 @@ import { retainUntilDismissed } from './notifications'
import { installManagedAgentHooks } from '../core/agents/hooks'
import { createSubagentTail } from '../core/subagent-tail'
import { createContextTail, type TaskNotification } from '../core/context-tail'
+import { registerContextEnsureIpc } from '../core/context-ensure'
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'
@@ -2593,17 +2594,53 @@ app.whenReady().then(async () => {
initTranscriptIndex(() => settingsStore.get().claudeAccounts ?? [])
corePlatform.handle(IPC.transcriptSearch, (query: string) => searchTranscripts(query))
- // Populate the context meter without a live hook event: the renderer calls this on mount
- // (the continuing session may be idle after a restart). Track under the sessionId (the key
- // the meter looks up); cwd is only a path fallback. contextTail.track reads immediately and
- // the 1s interval keeps it fresh while tracked.
- // Shares core's `resolveTranscript` with the read channels — including its `accountId`-scoped
- // cwd fallback. This copy dropped the account, so a managed-account node could track (and then
- // meter, and then SERVE as the chat's first-choice path) an unrelated session's transcript.
- corePlatform.on(IPC.contextEnsure, async (sessionId?: string, cwd?: string, accountId?: string) => {
- if (!sessionId || !SESSION_ID_RE.test(sessionId)) return
- const p = await resolveTranscript({ sessionId, cwd, accountId }, (s) => contextTail.pathFor(s))
- if (p) contextTail.track(sessionId, p)
+ // Populate the context meter without a live hook event: the renderer calls this on mount (the
+ // continuing session may be idle after a restart). The routing — which agent's locator, which
+ // 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({
+ // 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
+ // nothing to rehydrate from and gets no meter rather than somebody else's numbers.
+ tailFor: (agentId) => {
+ switch (agentId) {
+ case undefined:
+ case 'claude':
+ return contextTail
+ case 'codex':
+ return codexContextTail
+ case 'gemini':
+ return geminiContextTail
+ default:
+ 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)) 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'
+ }
})
// 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
diff --git a/src/preload/index.ts b/src/preload/index.ts
index f06380b32..3b7207706 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -496,8 +496,8 @@ const api: NodeTerminalApi = {
ipcRenderer.on(IPC.contextUpdate, handler)
return () => ipcRenderer.removeListener(IPC.contextUpdate, handler)
},
- ensure: (sessionId, cwd, accountId) =>
- ipcRenderer.send(IPC.contextEnsure, sessionId, cwd, accountId)
+ ensure: (sessionId, cwd, accountId, nodeId, agentId) =>
+ ipcRenderer.send(IPC.contextEnsure, sessionId, cwd, accountId, nodeId, agentId)
},
// Canvas sync: one channel in both directions. The cast goes to the reflector (src/core/canvas-sync),
// which stamps it with the total order (`seq`) and fans it to every attached client — INCLUDING us.
diff --git a/src/renderer/bridge/ws-bridge.namespaces.test.ts b/src/renderer/bridge/ws-bridge.namespaces.test.ts
index 91e0012c6..991169238 100644
--- a/src/renderer/bridge/ws-bridge.namespaces.test.ts
+++ b/src/renderer/bridge/ws-bridge.namespaces.test.ts
@@ -45,10 +45,12 @@ describe('buildFilesApi', () => {
it('context.ensure is a cast; context.onUpdate/git.onCloneProgress subscribe', () => {
const c = fakeClient()
const api = buildFilesApi(c as never)
- api.context.ensure('sid', '/cwd', undefined)
+ // nodeId + agentId ride the same cast: the Server Edition resolves per agent, and the desktop
+ // additionally needs the node id to tell an SSH-project session from a local one (issue #813).
+ api.context.ensure('sid', '/cwd', undefined, 'n1', 'codex')
const un = api.context.onUpdate(() => {})
const un2 = api.git.onCloneProgress(() => {})
- expect(c.calls[0]).toEqual({ kind: 'cast', method: IPC.contextEnsure, args: ['sid', '/cwd', undefined] })
+ expect(c.calls[0]).toEqual({ kind: 'cast', method: IPC.contextEnsure, args: ['sid', '/cwd', undefined, 'n1', 'codex'] })
expect(c.calls[1]).toEqual({ kind: 'subscribe', method: IPC.contextUpdate, args: [] })
expect(c.calls[2]).toEqual({ kind: 'subscribe', method: IPC.gitCloneProgress, args: [] })
expect(typeof un).toBe('function')
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 0b279a02e..c00685c80 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -596,8 +596,8 @@ export function buildFilesApi(
const context: ContextApi = {
onUpdate: (listener) => client.subscribe(IPC.contextUpdate, listener as Listener),
- ensure: (sessionId, cwd, accountId) =>
- client.cast(IPC.contextEnsure, sessionId, cwd, accountId)
+ ensure: (sessionId, cwd, accountId, nodeId, agentId) =>
+ client.cast(IPC.contextEnsure, sessionId, cwd, accountId, nodeId, agentId)
}
// Board-log: REAL over the bridge for local projects (the server routes local; SSH projects on the
diff --git a/src/renderer/lib/transcriptGates.ts b/src/renderer/lib/transcriptGates.ts
index c31db1922..d66085cf9 100644
--- a/src/renderer/lib/transcriptGates.ts
+++ b/src/renderer/lib/transcriptGates.ts
@@ -4,11 +4,11 @@ import { readsClaudeShapedTranscript, type AgentId } from '@shared/agents/config
* Does this node's conversation live in a file **claude's** transcript readers can locate and parse?
*
* This is the gate for every feature that goes through `core/transcript-ipc.ts`'s
- * `resolveTranscript` — today `context.ensure` (the context meter's mount-time rehydration) and the
- * find bar's transcript index (`claude.readTranscript`). It is deliberately NOT `hasUsage`.
+ * `resolveTranscript` — today the find bar's transcript index (`claude.readTranscript`). It is
+ * deliberately NOT `hasUsage`.
*
- * Those two used to share `hasUsage` with the context METER, back when all three were claude-only
- * and the distinction cost nothing. Then codex and gemini joined `USAGE_CAPABLE` (their own
+ * That reader, and the meter's mount-time rehydration beside it, used to share `hasUsage` with the
+ * context METER, back when all three were claude-only and the distinction cost nothing. Then codex and gemini joined `USAGE_CAPABLE` (their own
* transcripts state the numbers a meter needs) and the shared gate turned into a bug in both
* features at once, because `resolveTranscript` has a **cwd fallback**: when the sessionId leg
* misses — which it always does for a codex/gemini id, since no `<that id>.jsonl` exists under
@@ -18,6 +18,14 @@ import { readsClaudeShapedTranscript, type AgentId } from '@shared/agents/config
* session's messages as its own hits. Even wired to the right file the reader would be wrong: it
* parses claude's JSONL shape, which a codex rollout is not.
*
+ * `context.ensure` LEFT this gate in 2026-09 (issue #813) and is now gated on `hasUsage` at its call
+ * site. Nothing about the danger above changed — what changed is that its handler stopped BEING
+ * claude's resolver. `core/context-ensure.ts` routes on the agent id to that agent's OWN locator
+ * (`locateCodex` / `locateGemini`, both keyed strictly by session id, with no cwd fallback) and its
+ * own tail, so the resolver this function names is now reached only by an agent whose transcript it
+ * can actually read. The find bar's index has no such routing and therefore has not moved. If you
+ * are about to widen a THIRD consumer: route it, do not widen this.
+ *
* This used to read `CHAT_CAPABLE`, on the reasoning that it "already states exactly the fact being
* asked for" and a separate list "would mean the same thing". That was true only while claude was
* CHAT_CAPABLE's only member. Grok joined it in 2026-09 — we render grok's conversation ourselves
@@ -26,15 +34,15 @@ import { readsClaudeShapedTranscript, type AgentId } from '@shared/agents/config
* new agent. The gate now reads `CLAUDE_TRANSCRIPT_READABLE`, which asks the narrower question this
* function's name has always asked.
*
- * The meter itself stays on `hasUsage` and spans three agents: it is fed by the per-agent context
- * tails in the shells (`geminiContextParse` / `codexContextParse`), which need no resolver because
- * the hook envelope hands them the path. The only thing a non-claude agent gives up here is the
- * mount-time HEAD START: its meter fills on the first hook event after mount instead of instantly.
- * Correct-but-later beats instant-but-borrowed-from-another-session.
+ * The meter itself stays on `hasUsage`: it is fed by the per-agent context tails in the shells
+ * (`geminiContextParse` / `codexContextParse` / `grokContextParse`), which need no resolver because
+ * the hook envelope hands them the path.
*
- * FOLLOW-UP (own task): per-agent rehydration. Making `context.ensure` work for codex/gemini means
- * teaching it to resolve THEIR transcripts (`handoff/locate.ts` already has `locateCodex` /
- * `locateGemini` by sessionId) and to route to the matching tail — a real feature, not a gate.
+ * The follow-up this note used to carry — per-agent rehydration, so a codex/gemini meter fills at
+ * MOUNT instead of only on its next turn — is DONE (`core/context-ensure.ts`). Grok is the one agent
+ * still without it, and that is structural rather than pending: its meter reads a `signals.json`
+ * whose directory is learned from a hook event, so after a restart there is no path to rehydrate
+ * from at all.
*/
export function readsClaudeTranscript(agentId: AgentId | undefined): boolean {
return !!agentId && readsClaudeShapedTranscript(agentId)
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 346436035..27b271eed 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -1839,24 +1839,35 @@ export function TerminalNode({
// 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 main-process tailer is never
- // re-fed. Re-runs if the sessionId changes (track is idempotent). cwd is a path fallback.
+ // 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.
//
- // CLAUDE ONLY (`claudeTranscript`, not `showUsage`). The handler resolves this sessionId through
- // claude's `resolveTranscript`, whose cwd fallback answers *the newest claude transcript for that
- // cwd* — for a codex/gemini node that is a stranger's session, tracked on the CLAUDE tail under
- // this node's session id, so its meter would show another agent's fill and then flap against the
- // correct tail. The cost of the gate: a codex/gemini meter fills on the first hook event after
- // mount instead of instantly. Their tails need no resolver (the hook envelope carries the path),
- // so nothing else is lost. Per-agent rehydration is a follow-up task — see transcriptGates.ts.
+ // 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 (claudeTranscript && sid)
- window.nodeTerminal.context.ensure(sid, (data.cwd as string) || undefined, accountForReads)
+ 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.
- }, [claudeTranscript, status?.sessionId, data.cwd, accountForReads])
+ }, [showUsage, status?.sessionId, data.cwd, accountForReads, id, agentId])
const updateNodeInternals = useUpdateNodeInternals()
const [searchOpen, setSearchOpen] = useState(false)
diff --git a/src/renderer/nodes/title-gate.test.ts b/src/renderer/nodes/title-gate.test.ts
index c397f8f78..5054bea99 100644
--- a/src/renderer/nodes/title-gate.test.ts
+++ b/src/renderer/nodes/title-gate.test.ts
@@ -114,16 +114,20 @@ describe('session-name title gates', () => {
})
/**
- * The claude-transcript gates: `claudeTranscript` (`readsClaudeTranscript(agentId)`), NOT `showUsage`
+ * The claude-transcript gate: `claudeTranscript` (`readsClaudeTranscript(agentId)`), NOT `showUsage`
* (`hasUsage(agentId)`).
*
- * `USAGE_CAPABLE` grew to claude + codex + gemini, so `showUsage` is now true for three agents while
- * only ONE of them has a claude transcript. Both readers behind these gates resolve a session id
+ * `USAGE_CAPABLE` grew to claude + codex + gemini + grok, so `showUsage` is now true for four agents
+ * while only ONE of them has a claude transcript. The reader behind this gate resolves a session id
* through claude's `resolveTranscript`, whose cwd fallback answers *the newest claude transcript for
- * that cwd* — so on a codex or gemini node they resolve an UNRELATED claude session and then meter
- * it, and search it, under this node's session id. That was this branch's own Critical fix, and
- * reverting either gate to `showUsage` left the full suite green: nothing in this repo renders
- * `TerminalNode`, so this file is the only thing standing between the bug and a re-landing.
+ * that cwd* — so on a codex or gemini node it resolves an UNRELATED claude session and searches it
+ * under this node's session id. That was this branch's own Critical fix, and reverting the gate to
+ * `showUsage` left the full suite green: nothing in this repo renders `TerminalNode`, so this file
+ * is the only thing standing between the bug and a re-landing.
+ *
+ * `context.ensure` USED to be gated here too and deliberately is not any more — see its own test
+ * below. Its handler stopped resolving every agent through claude's resolver, which is the only
+ * thing that ever made the shared gate necessary; the find bar's index still does, so it stays.
*
* Asserted per LINE rather than with `toContain` over a 6000-line file: a whole-file `toContain`
* failure dumps the file as its diff, and a per-line assertion names the site instead.
@@ -140,14 +144,32 @@ describe('claude-transcript gates', () => {
expect(terminalNode).toContain('const showUsage = !!agentId && hasUsage(agentId)')
})
- it('gates the mount-time meter rehydration (`context.ensure`)', () => {
+ /**
+ * `context.ensure` is the ONE site that legitimately left this gate, and what makes that safe is
+ * the argument it now passes instead.
+ *
+ * The gate never protected the meter; it protected against a HANDLER that resolved every agent
+ * through claude's `resolveTranscript`. That handler is now `core/context-ensure.ts`, which
+ * routes on `agentId` to each agent's own locator and tail — so the renderer can gate on the
+ * meter's own capability (`showUsage`), and a codex node reaches codex's locator rather than
+ * nothing at all.
+ *
+ * The pin therefore moves with the mechanism rather than being deleted: `agentId` MUST reach the
+ * call, because a widened gate that does not pass it is precisely the original bug (every agent
+ * resolving as claude, on claude's cwd fallback, adopting a stranger's session). `id` is pinned
+ * for the same reason on the remote leg: without it the handler cannot tell an SSH-project node
+ * 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.
- const guard = lines.slice(Math.max(0, lineNo - 3), lineNo).join('\n')
- expect(guard, `${lineNo}: context.ensure guard`).toContain('claudeTranscript')
- expect(guard, `${lineNo}: context.ensure guard`).not.toContain('showUsage')
+ // 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`)', () => {
diff --git a/src/server/agent-status.ts b/src/server/agent-status.ts
index 0fdf1b211..7f99e2647 100644
--- a/src/server/agent-status.ts
+++ b/src/server/agent-status.ts
@@ -68,7 +68,7 @@ export interface WireAgentStatusOptions {
export function wireAgentStatus(
platform: ServerPlatform,
opts: WireAgentStatusOptions = {}
-): { contextTail: ContextTail; geminiContextTail: ContextTail } {
+): { contextTail: ContextTail; geminiContextTail: ContextTail; codexContextTail: ContextTail } {
const hooks = opts.hooks ?? hookServer
// nodeId → the agent session id of whichever hook-capable CLI runs in that node (claude's, and
// since the grok branch below, grok's)
@@ -425,5 +425,8 @@ export function wireAgentStatus(
platform.on(IPC.ptyDestroy, (nodeId: string) => releaseNodeTails(nodeId))
platform.on(IPC.ptyRecycle, (nodeId: string) => releaseNodeTails(nodeId))
- return { contextTail, geminiContextTail }
+ // `codexContextTail` joins the two already returned so `src/server/index.ts` can register the
+ // context-meter rehydration over all three. Keeping a tail private here would mean a second
+ // instance somewhere else metering the same sessions twice.
+ return { contextTail, geminiContextTail, codexContextTail }
}
diff --git a/src/server/index.ts b/src/server/index.ts
index 33ef8f837..f7358e583 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -93,6 +93,7 @@ import { wireAgentStatus } from './agent-status'
import { initServerContextLink } from './context-link'
import { createServerWorkspaceWatcher } from './workspace-external-watch'
import { registerTranscriptIpc } from '../core/transcript-ipc'
+import { registerContextEnsureIpc } from '../core/context-ensure'
import { IPC } from '@shared/ipc'
import { WhisperModelStore } from '../core/speech/whisper-models'
import { SpeechService } from '../core/speech/speech-service'
@@ -453,7 +454,7 @@ export async function startServer(
// Set after the initial workspace load when the opt-in flag is on. The status listener is wired
// now so the runtime, once present, consumes the exact same normalized stream as the UI/mirror.
let canvasControl: ServerCanvasControl | null = null
- const { contextTail, geminiContextTail } = wireAgentStatus(platform, {
+ const { contextTail, geminiContextTail, codexContextTail } = wireAgentStatus(platform, {
onEvent: (event) => canvasControl?.onAgentEvent(event)
})
// The ⌘M chat view + the find-bar's transcript index. Registered HERE rather than with the rest
@@ -461,6 +462,27 @@ export async function startServer(
// leg: the Server Edition runs ON the host whose transcripts it reads, so local resolution is
// the complete answer (an SSH-project node is a desktop-only concept here).
registerTranscriptIpc({ pathFor: (sessionId) => contextTail.pathFor(sessionId) })
+ // The context meter's mount-time rehydration, registered beside the read channels and for the
+ // same reason: the tails it feeds are the ones created just above. Until this landed the Server
+ // Edition had NO handler for `context:ensure` at all — the browser cast it and nothing received
+ // it, so a browser agent node's meter filled only on its next turn, exactly the desktop bug
+ // issue #813 reported for SSH nodes. No remote leg here (see registerTranscriptIpc above): this
+ // process runs on the host whose transcripts it reads, so the local locators are complete.
+ registerContextEnsureIpc({
+ tailFor: (agentId) => {
+ switch (agentId) {
+ case undefined:
+ case 'claude':
+ return contextTail
+ case 'codex':
+ return codexContextTail
+ case 'gemini':
+ return geminiContextTail
+ default:
+ return undefined
+ }
+ }
+ })
// Deterministic hook-reply approvals (docs/hook-reply-approvals.md): the browser canvas answers a
// held Claude permission hook here. The Server Edition runs ON the host, so a local project's
// answer file is written right there (under os.homedir(), which the hook uses as $HOME). SSH
diff --git a/src/shared/types.ts b/src/shared/types.ts
index c4200cf98..76fabebbf 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2606,12 +2606,27 @@ export interface ContextApi {
/** Fires whenever a session's context fill changes. Returns unsubscribe. */
onUpdate(listener: (usage: ContextWindowUsage) => void): () => void
/**
- * Ask main to start (or refresh) tracking a session's transcript so the meter populates
+ * Ask the core to start (or refresh) tracking a session's transcript so the meter populates
* without waiting for a live hook event — e.g. on node mount after an app restart, when
* the continuing session is idle. `cwd` is a transcript-path fallback only.
* `accountId` scopes resolution to a managed Claude account's transcript root (default `~/.claude`).
- */
- ensure(sessionId: string, cwd?: string, accountId?: string): void
+ *
+ * `nodeId` and `agentId` are what make this work for anything but a LOCAL CLAUDE node, and both
+ * are load-bearing rather than informational (see `core/context-ensure.ts`):
+ * - `nodeId` is the only way to learn that this session runs on an SSH project's HOST, whose
+ * transcript no local resolver can see. Without it a remote node's meter stayed blank until
+ * its next turn, every app restart.
+ * - `agentId` routes the resolve to THAT agent's own locator and tail. Claude's resolver falls
+ * back to the newest claude transcript for the cwd, so resolving a codex/gemini session through
+ * it would meter a stranger's conversation. Both omitted ⇒ the legacy local-claude behaviour.
+ */
+ ensure(
+ sessionId: string,
+ cwd?: string,
+ accountId?: string,
+ nodeId?: string,
+ agentId?: string
+ ): void
}
/**