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(mirror): seed session identity from the renderer's persisted agent status

reviewbea6eb6d5a2e
diff --git a/src/core/agent-status-mirror.seed.test.ts b/src/core/agent-status-mirror.seed.test.ts
new file mode 100644
index 000000000..522dc44e5
--- /dev/null
+++ b/src/core/agent-status-mirror.seed.test.ts
@@ -0,0 +1,173 @@
+// Seeding the mirror's IDENTITY from the renderer (device report after #993/#994): the phone's chat
+// view locates a node's transcript ONLY by the sessionId it reads off this mirror, and the mirror
+// learns a session id only from hook events. An entry dropped before #994, or never created in this
+// app run (an idle terminal-made conversation after a restart), is simply absent — while the
+// renderer's agentStatus store has kept that node's sessionId in localStorage all along. These tests
+// pin the seed that closes the gap: identity-only, add-never-overwrite, validated at the boundary,
+// existing nodes only, and carried into the pushed SSH slice.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import {
+ seedNodeIdentities,
+ recordAgentEvent,
+ setNodeHibernated,
+ setMirrorLiveNodesProvider,
+ onMirrorFlush,
+ flush,
+ initAgentStatusMirror,
+ filterMirrorForNodes,
+ mirrorEntry,
+ _resetForTest,
+ _snapshot,
+ type MirrorFile
+} from './agent-status-mirror'
+import { IDENTITY_SEED_MAX, parseIdentitySeed } from '@shared/agent-identity-seed'
+
+let dir = ''
+beforeEach(() => {
+ _resetForTest()
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-seed-'))
+ initAgentStatusMirror(path.join(dir, 'agent-status.json'))
+})
+afterEach(() => {
+ _resetForTest()
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+
+const account = { configDir: '/home/u/.claude', accountId: null, known: true }
+
+describe('seedNodeIdentities', () => {
+ it('creates an IDENTITY-ONLY entry (no state) for a node the mirror has never seen', () => {
+ expect(seedNodeIdentities([{ nodeId: 'n1', agentId: 'claude', sessionId: 'sess-1' }])).toBe(1)
+ const e = mirrorEntry('n1')!
+ expect(e.agentId).toBe('claude')
+ expect(e.sessionId).toBe('sess-1')
+ expect(e.state).toBeUndefined()
+ expect(e.stateExpired).toBe(true)
+ // Not evidence about any state: nothing that gates on proof may read it as proven or restored.
+ expect(e.stateVerified).toBeUndefined()
+ })
+
+ it('writes the identity to the flushed doc (no state key)', async () => {
+ let doc: MirrorFile | null = null
+ onMirrorFlush((d) => (doc = d))
+ seedNodeIdentities([{ nodeId: 'n1', agentId: 'claude', sessionId: 'sess-1', account }])
+ await flush()
+ const n1 = JSON.parse(JSON.stringify(doc!)).nodes.n1
+ expect(n1).toMatchObject({ agentId: 'claude', sessionId: 'sess-1', account })
+ expect('state' in n1).toBe(false)
+ })
+
+ it('NEVER overrides an existing entry or its sessionId', () => {
+ recordAgentEvent({ nodeId: 'n1', agentId: 'claude', kind: 'state', state: 'working', sessionId: 'live' })
+ expect(seedNodeIdentities([{ nodeId: 'n1', agentId: 'claude', sessionId: 'stale' }])).toBe(0)
+ expect(mirrorEntry('n1')!.sessionId).toBe('live')
+ expect(mirrorEntry('n1')!.state).toBe('working')
+ expect(mirrorEntry('n1')!.stateExpired).toBeUndefined()
+ })
+
+ it('never changes the agentId of an entry that already names one', () => {
+ recordAgentEvent({ nodeId: 'n1', agentId: 'codex', kind: 'session', sessionPhase: 'end' })
+ expect(seedNodeIdentities([{ nodeId: 'n1', agentId: 'claude', sessionId: 's' }])).toBe(0)
+ expect(mirrorEntry('n1')!.agentId).toBe('codex')
+ expect(mirrorEntry('n1')!.sessionId).toBeUndefined()
+ })
+
+ it('fills the identity of a hibernated-only entry without touching the flag', () => {
+ // The renderer's boot replay reports hibernated nodes BEFORE the seed; those are exactly the
+ // long-idle nodes the phone could not open.
+ setNodeHibernated('n1', true)
+ expect(seedNodeIdentities([{ nodeId: 'n1', agentId: 'claude', sessionId: 'sess-1' }])).toBe(1)
+ const e = mirrorEntry('n1')!
+ expect(e.hibernated).toBe(true)
+ expect(e.sessionId).toBe('sess-1')
+ expect(e.agentId).toBe('claude')
+ })
+
+ it('skips nodes the workspace does not know (a deleted node\'s stale localStorage entry)', () => {
+ setMirrorLiveNodesProvider(() => new Set(['alive']))
+ expect(
+ seedNodeIdentities([
+ { nodeId: 'alive', agentId: 'claude', sessionId: 's1' },
+ { nodeId: 'deleted', agentId: 'claude', sessionId: 's2' }
+ ])
+ ).toBe(1)
+ expect(Object.keys(_snapshot())).toEqual(['alive'])
+ })
+
+ it('rejects invalid ids at the boundary', () => {
+ const n = seedNodeIdentities([
+ { nodeId: 'a;rm -rf', agentId: 'claude', sessionId: 's' },
+ { nodeId: '..', agentId: 'claude', sessionId: 's' },
+ { nodeId: 'n2', agentId: 'claude', sessionId: '$(touch x)' },
+ { nodeId: 'n3', agentId: 'claude', sessionId: '-flag' },
+ { nodeId: 'n4', agentId: 'claude; x', sessionId: 's' },
+ { nodeId: 'n5', agentId: 'claude', sessionId: 's', account: { configDir: 1 } },
+ { nodeId: 'n6', sessionId: 's' },
+ { nodeId: 'n7', agentId: 'claude' },
+ 'n8',
+ null
+ ] as unknown)
+ expect(n).toBe(0)
+ expect(_snapshot()).toEqual({})
+ expect(seedNodeIdentities('nope' as unknown)).toBe(0)
+ expect(seedNodeIdentities({ nodeId: 'n1' } as unknown)).toBe(0)
+ })
+
+ it('accepts a custom agent id', () => {
+ expect(
+ seedNodeIdentities([{ nodeId: 'n1', agentId: 'custom:3f0e-aa', sessionId: 'sess-1' }])
+ ).toBe(1)
+ })
+
+ it('caps the number of entries per call', () => {
+ const many = Array.from({ length: IDENTITY_SEED_MAX + 50 }, (_, i) => ({
+ nodeId: `n${i}`,
+ agentId: 'claude',
+ sessionId: `s${i}`
+ }))
+ expect(seedNodeIdentities(many)).toBe(IDENTITY_SEED_MAX)
+ expect(Object.keys(_snapshot())).toHaveLength(IDENTITY_SEED_MAX)
+ })
+
+ it('a later hook event supersedes the seed normally', () => {
+ seedNodeIdentities([{ nodeId: 'n1', agentId: 'claude', sessionId: 'old' }])
+ recordAgentEvent({ nodeId: 'n1', agentId: 'claude', kind: 'state', state: 'working', sessionId: 'new' })
+ const e = mirrorEntry('n1')!
+ expect(e.sessionId).toBe('new')
+ expect(e.state).toBe('working')
+ expect(e.stateExpired).toBeUndefined()
+ })
+
+ it('the pushed per-project slice carries the seeded identity', async () => {
+ let doc: MirrorFile | null = null
+ onMirrorFlush((d) => (doc = d))
+ seedNodeIdentities([
+ { nodeId: 'ssh-node', agentId: 'claude', sessionId: 'remote-sess' },
+ { nodeId: 'other', agentId: 'claude', sessionId: 'x' }
+ ])
+ await flush()
+ const slice = filterMirrorForNodes(doc!, new Set(['ssh-node']))
+ expect(Object.keys(slice.nodes)).toEqual(['ssh-node'])
+ expect(slice.nodes['ssh-node']).toMatchObject({ agentId: 'claude', sessionId: 'remote-sess' })
+ })
+})
+
+describe('parseIdentitySeed', () => {
+ it('keeps a valid account label and drops a remote flag that is not boolean true', () => {
+ const [e] = parseIdentitySeed([
+ { nodeId: 'n1', agentId: 'claude', sessionId: 's', account: { ...account, remote: 'yes' } }
+ ])
+ expect(e.account).toEqual(account)
+ })
+
+ it('rejects an account label with control characters in its config dir', () => {
+ expect(
+ parseIdentitySeed([
+ { nodeId: 'n1', agentId: 'claude', sessionId: 's', account: { ...account, configDir: '/a\nb' } }
+ ])
+ ).toEqual([])
+ })
+})
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 7154a72bc..7fa2ae83e 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -7,6 +7,7 @@ import type { AgentId } from '@shared/agents/config'
import type { AgentState, NormalizedAgentEvent } from '@shared/agents/normalize'
import type { ObservedClaudeAccount } from '@shared/types'
import { WORKING_STALE_MS, isStaleWorking } from '@shared/agents/stale'
+import { parseIdentitySeed } from '@shared/agent-identity-seed'
/**
* Mirrors the live per-node agent status to a small JSON file so an EXTERNAL reader (the
@@ -2087,6 +2088,61 @@ export function setNodeHibernated(nodeId: string, on: boolean): void {
scheduleWrite()
}
+/**
+ * Seed IDENTITY for nodes the mirror has no session for — the `agent:seed-identity` cast's only
+ * writer. The renderer's agentStatus store keeps each node's `sessionId`/`agentId` in localStorage
+ * indefinitely, while this mirror learns them only from hook events; a node idle since before this
+ * app run (or whose entry was dropped before identity outlived the state) is therefore absent here,
+ * and the phone — which finds a transcript only by the session id it reads off this file — showed
+ * "No conversation yet" until the next prompt fired a hook.
+ *
+ * The rules, each a refusal:
+ * - validated by `parseIdentitySeed` (bounded count, safe ids — the values come from hand-editable
+ * localStorage and the ids are shell-reaching elsewhere);
+ * - a node the workspace does not know is skipped (a deleted node's stale localStorage entry must
+ * not be advertised); an unknowable workspace (`undefined`) accepts, bounded by the identity TTL
+ * and the renderer's own filter;
+ * - an entry that already carries a `sessionId` is NEVER touched — a hook-fed id is fresher than
+ * anything localStorage remembers — and neither is one whose `agentId` disagrees;
+ * - an entry with no identity at all (the boot replay's hibernated-only entry) gets its identity
+ * filled, nothing else;
+ * - a new entry is the IDENTITY-ONLY shape (`stateExpired`, no state, no proof): it says nothing
+ * about what the node is doing, so every state-gated reader sees "no current observation".
+ * Returns how many entries changed. Schedules a write (and so an SSH slice push) only then.
+ */
+export function seedNodeIdentities(input: unknown): number {
+ const entries = parseIdentitySeed(input)
+ if (entries.length === 0) return 0
+ const liveIds = safeLiveNodes()
+ const now = Date.now()
+ let changed = 0
+ for (const s of entries) {
+ if (liveIds && !liveIds.has(s.nodeId)) continue
+ const e = state.get(s.nodeId)
+ if (e) {
+ if (e.sessionId) continue
+ if (e.agentId && e.agentId !== s.agentId) continue
+ state.set(s.nodeId, {
+ ...e,
+ agentId: s.agentId,
+ sessionId: s.sessionId,
+ ...(!e.account && s.account ? { account: s.account } : {})
+ })
+ } else {
+ state.set(s.nodeId, {
+ agentId: s.agentId,
+ sessionId: s.sessionId,
+ ...(s.account ? { account: s.account } : {}),
+ updatedAt: now,
+ stateExpired: true
+ })
+ }
+ changed++
+ }
+ if (changed > 0) scheduleWrite()
+ return changed
+}
+
/** A node's published session name (see MirrorEntry.name), or undefined. */
export function nodeSessionName(nodeId: string): string | undefined {
return state.get(nodeId)?.name
diff --git a/src/main/agent-seed-identity-parity.test.ts b/src/main/agent-seed-identity-parity.test.ts
new file mode 100644
index 000000000..c91438f86
--- /dev/null
+++ b/src/main/agent-seed-identity-parity.test.ts
@@ -0,0 +1,42 @@
+// Source-level parity for the mirror identity seed (`agent:seed-identity`). Every hop is optional
+// at the type level — a preload member that is never called, a ws-bridge forward to a channel no
+// server handles, a shell that never registers the handler — and each of those compiles, passes
+// every unit test, and ships the seed INERT on one surface. Same remedy as
+// `hook-verified-parity.test.ts`: read the wiring as text.
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+const src = (p: string): string =>
+ readFileSync(resolve(__dirname, '..', p), 'utf8').replace(/\r\n/g, '\n')
+
+describe('agent:seed-identity wiring', () => {
+ it('names the channel once, in shared/ipc.ts', () => {
+ expect(src('shared/ipc.ts')).toMatch(/agentSeedIdentity:\s*'agent:seed-identity'/)
+ })
+
+ it('desktop main registers the handler and feeds the mirror seed', () => {
+ const main = src('main/index.ts')
+ expect(main).toMatch(/ipcMain\.on\(IPC\.agentSeedIdentity,[\s\S]{0,200}seedNodeIdentities\(/)
+ })
+
+ it('Server Edition registers the handler and feeds the mirror seed', () => {
+ const server = src('server/index.ts')
+ expect(server).toMatch(/platform\.handle\(IPC\.agentSeedIdentity,[\s\S]{0,200}seedNodeIdentities\(/)
+ })
+
+ it('both renderer bridges forward to the channel', () => {
+ expect(src('preload/index.ts')).toMatch(/seedAgentIdentity:[\s\S]{0,120}IPC\.agentSeedIdentity/)
+ expect(src('renderer/bridge/ws-bridge.ts')).toMatch(
+ /seedAgentIdentity:[\s\S]{0,200}IPC\.agentSeedIdentity/
+ )
+ })
+
+ it('the relay tab deliberately does not seed another core', () => {
+ expect(src('renderer/bridge/relay-api.ts')).toMatch(/seedAgentIdentity:\s*\(\)\s*=>\s*undefined/)
+ })
+
+ it('the canvas mounts the seeder', () => {
+ expect(src('renderer/canvas/Canvas.tsx')).toMatch(/useMirrorIdentitySeed\(\)/)
+ })
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index 5677e08fa..baa1cb1db 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -183,6 +183,7 @@ import {
type MirrorSettings,
setNodeSessionName,
setNodeHibernated,
+ seedNodeIdentities,
sessionNameSweepEntries,
nodeState,
nodeSessionName,
@@ -4103,6 +4104,13 @@ app.whenReady().then(async () => {
if (typeof msg?.nodeId !== 'string' || !msg.nodeId) return
setNodeHibernated(msg.nodeId, msg.on === true)
})
+ // Identity seed: the renderer's persisted agentStatus store reports the session ids it holds for
+ // nodes the mirror has none for (an idle, terminal-made conversation after a restart), so the
+ // phone's chat view can locate the transcript before the next hook fires. Add-only and
+ // validated in core; SSH projects get it through the ordinary per-project slice push.
+ ipcMain.on(IPC.agentSeedIdentity, (_e, entries: unknown) => {
+ seedNodeIdentities(entries)
+ })
initRemoteHost(win, ptyManager, listProjectsOutput, hostBridge)
// NEW interactive relay host (Stage 4): a connecting peer desktop becomes a first-class
// CorePlatform client of this desktop after mutual SAS approval. Runs BESIDE initRemoteHost (the
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 403b3345b..85d7e3f78 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -794,6 +794,7 @@ const api: NodeTerminalApi = {
return () => ipcRenderer.removeListener(IPC.agentStatus, handler)
}, () => ipcRenderer.invoke(IPC.agentSubagentSnapshot), listener),
reportHibernated: (nodeId, on) => ipcRenderer.send(IPC.agentHibernated, { nodeId, on }),
+ seedAgentIdentity: (entries) => ipcRenderer.send(IPC.agentSeedIdentity, entries),
onAgentWake: (listener) => {
const handler = (_e: unknown, nodeId: string) => listener(nodeId)
ipcRenderer.on(IPC.agentWake, handler)
diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.ts
index 45c24dcd1..3a1d02022 100644
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@ -164,7 +164,12 @@ export function buildRelayApi(connectionId: string, transport?: FrameTransport):
sendHostChatReply: stub.sendHostChatReply,
// Messaging rides the same decision: the browser client is never a sender (constraint 5 of
// the messaging plan — the phone drives canvas control over relay→IPC, not /control/*).
- agentMessage: stub.agentMessage
+ agentMessage: stub.agentMessage,
+ // The mirror identity seed is a deliberate no-op here: a relay tab's nodes belong to the HOST's
+ // core, whose mirror is seeded by the host's own renderer from its own localStorage. This
+ // machine's localStorage holds no identity for them, and `...local` would plant this machine's
+ // ids into this machine's mirror under the peer's node ids.
+ seedAgentIdentity: () => undefined
} satisfies NodeTerminalApi
return {
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index ea8f065c7..13148eed7 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -129,6 +129,7 @@ export function buildStubApi(): Omit<
| 'answerPermission'
| 'ackDone'
| 'reportHibernated'
+ | 'seedAgentIdentity'
| 'onAgentWake'
| 'onRemoteViewers'
| 'onAgentRefreshNode'
@@ -589,6 +590,7 @@ export function buildStubApi(): Omit<
| 'answerPermission'
| 'ackDone'
| 'reportHibernated'
+ | 'seedAgentIdentity'
| 'onAgentWake'
| 'onRemoteViewers'
| 'onAgentRefreshNode'
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 6b5fb11bf..a8c3fd96d 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -665,6 +665,7 @@ export function buildAgentApi(
| 'answerPermission'
| 'ackDone'
| 'reportHibernated'
+ | 'seedAgentIdentity'
| 'onAgentWake'
| 'onRemoteViewers'
| 'onAgentRefreshNode'
@@ -680,6 +681,10 @@ export function buildAgentApi(
reportHibernated: (nodeId, on) => {
void client.request(IPC.agentHibernated, { nodeId, on }).catch(() => undefined)
},
+ // REAL forward, same reason: the server's mirror is what a phone browsing that host reads.
+ seedAgentIdentity: (entries) => {
+ void client.request(IPC.agentSeedIdentity, entries).catch(() => undefined)
+ },
// Deliberate no-op subscriptions, not stubs-by-accident: both signals originate in the phone
// RELAY host, which lives only in the desktop main process — the Server Edition serves no
// relay, so there is nothing to subscribe to and nothing silently degrades.
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 19447fa0b..8552a5f2c 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -8,6 +8,7 @@ import { commitOwnedLaunchAttempt, registerLaunchCommit } from '../terminal/laun
import { launchCommand } from '../terminal/launch-command'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useContextLinkSync } from './useContextLinkSync'
+import { useMirrorIdentitySeed } from './useMirrorIdentitySeed'
import { useShallow } from 'zustand/react/shallow'
import { playSfx, primeSfx } from '@renderer/lib/sfx'
import { fanoutStillWorking } from '@renderer/lib/completionAlert'
@@ -3759,6 +3760,9 @@ export function Canvas() {
}, [nodes])
useContextLinkSync({ projectId: nodesProjectIdRef.current, nodes, edges: linkEdges })
+ // Phone chat: tell the core's agent-status mirror which session each node was last running, for
+ // nodes it learned nothing about this run (see useMirrorIdentitySeed).
+ useMirrorIdentitySeed()
// Pruning is separate from publication: node geometry changes must not postpone link writes.
useEffect(() => {
diff --git a/src/renderer/canvas/useMirrorIdentitySeed.ts b/src/renderer/canvas/useMirrorIdentitySeed.ts
new file mode 100644
index 000000000..63c80da87
--- /dev/null
+++ b/src/renderer/canvas/useMirrorIdentitySeed.ts
@@ -0,0 +1,52 @@
+import { useEffect } from 'react'
+import { useProjects } from '../state/projects'
+import { useAgentStatus } from '../state/agentStatus'
+import { sessionForProject } from '../session/session'
+import { identitySeedSignature, planIdentitySeed } from '../lib/identitySeed'
+
+/**
+ * Seed the core's agent-status mirror with the node identities this renderer's persisted
+ * agentStatus store holds (see `@shared/agent-identity-seed`): once at boot, when the projects
+ * store hydrates, and whenever the status store learns a session id. The core fills only nodes it
+ * has no session for, so this can never override a hook-fed id.
+ *
+ * Only projects whose session is THIS core (`window.nodeTerminal`): a relay tab's nodes belong to
+ * another machine, and the default status store holds nothing for them anyway. Coalesced on a
+ * fixed task boundary (never reset), like `useContextLinkSync`, so a hook burst costs one plan.
+ */
+export function useMirrorIdentitySeed(): void {
+ useEffect(() => {
+ const sent = new Set<string>()
+ let pending: ReturnType<typeof setTimeout> | undefined
+ const update = (): void => {
+ const api = window.nodeTerminal
+ if (!api?.seedAgentIdentity) return
+ const { projects } = useProjects.getState()
+ const local = projects.filter((p) => sessionForProject(p.id).api === api)
+ const chunks = planIdentitySeed(local, useAgentStatus.getState().byId, sent)
+ for (const chunk of chunks) {
+ try {
+ api.seedAgentIdentity(chunk)
+ } catch {
+ continue // a mirror side-channel; a failed cast is retried on the next change
+ }
+ for (const e of chunk) sent.add(identitySeedSignature(e))
+ }
+ }
+ const schedule = (): void => {
+ if (pending !== undefined) return
+ pending = setTimeout(() => {
+ pending = undefined
+ update()
+ }, 0)
+ }
+ const offProjects = useProjects.subscribe(schedule)
+ const offStatus = useAgentStatus.subscribe(schedule)
+ schedule()
+ return () => {
+ clearTimeout(pending)
+ offProjects()
+ offStatus()
+ }
+ }, [])
+}
diff --git a/src/renderer/lib/identitySeed.test.ts b/src/renderer/lib/identitySeed.test.ts
new file mode 100644
index 000000000..087a8efb5
--- /dev/null
+++ b/src/renderer/lib/identitySeed.test.ts
@@ -0,0 +1,55 @@
+import { describe, it, expect } from 'vitest'
+import { planIdentitySeed, identitySeedSignature } from './identitySeed'
+import { IDENTITY_SEED_MAX } from '@shared/agent-identity-seed'
+
+const project = (id: string, nodeIds: string[]) => ({
+ id,
+ nodes: nodeIds.map((n) => ({ id: n, kind: 'terminal' as const }))
+})
+
+describe('planIdentitySeed', () => {
+ it('seeds only nodes that exist in a project, with a known sessionId', () => {
+ const plan = planIdentitySeed(
+ [project('p1', ['a', 'b', 'c'])],
+ {
+ a: { sessionId: 'sa', agentId: 'claude' },
+ b: { agentId: 'claude' }, // no session id: nothing the phone could use
+ deleted: { sessionId: 'sd', agentId: 'claude' } // stale localStorage entry
+ },
+ new Set()
+ )
+ expect(plan).toEqual([[{ nodeId: 'a', agentId: 'claude', sessionId: 'sa' }]])
+ })
+
+ it('falls back to the node\'s own agentId and carries the observed account', () => {
+ const account = { configDir: '/h/.claude', accountId: null, known: true }
+ const plan = planIdentitySeed(
+ [{ nodes: [{ id: 'a', agentId: 'codex' }] }],
+ { a: { sessionId: 'sa', account } },
+ new Set()
+ )
+ expect(plan).toEqual([[{ nodeId: 'a', agentId: 'codex', sessionId: 'sa', account }]])
+ })
+
+ it('does not resend an identity it already sent, but sends a changed one', () => {
+ const statuses = { a: { sessionId: 'sa', agentId: 'claude' } }
+ const sent = new Set([identitySeedSignature({ nodeId: 'a', agentId: 'claude', sessionId: 'sa' })])
+ expect(planIdentitySeed([project('p', ['a'])], statuses, sent)).toEqual([])
+ expect(
+ planIdentitySeed([project('p', ['a'])], { a: { sessionId: 'sb', agentId: 'claude' } }, sent)
+ ).toHaveLength(1)
+ })
+
+ it('drops entries the core would refuse, so a hand-edited localStorage cannot ride along', () => {
+ expect(
+ planIdentitySeed([project('p', ['a'])], { a: { sessionId: '$(x)', agentId: 'claude' } }, new Set())
+ ).toEqual([])
+ })
+
+ it('chunks to the per-call cap', () => {
+ const ids = Array.from({ length: IDENTITY_SEED_MAX + 3 }, (_, i) => `n${i}`)
+ const statuses = Object.fromEntries(ids.map((id) => [id, { sessionId: `s-${id}`, agentId: 'claude' }]))
+ const plan = planIdentitySeed([project('p', ids)], statuses, new Set())
+ expect(plan.map((c) => c.length)).toEqual([IDENTITY_SEED_MAX, 3])
+ })
+})
diff --git a/src/renderer/lib/identitySeed.ts b/src/renderer/lib/identitySeed.ts
new file mode 100644
index 000000000..89f4ce01f
--- /dev/null
+++ b/src/renderer/lib/identitySeed.ts
@@ -0,0 +1,63 @@
+/**
+ * Which node identities the renderer seeds into the core's agent-status mirror (see
+ * `@shared/agent-identity-seed` for why). Pure, so the rules are testable without a store:
+ * - only nodes that exist in a project handed in (the caller passes this core's projects), so a
+ * deleted node's stale localStorage entry is never advertised;
+ * - only entries with a session id AND an agent id (the status store's, else the node's own);
+ * - only entries the core would accept (`parseIdentitySeedEntry` — the same rule, applied here so
+ * a hand-edited localStorage value never even crosses the boundary);
+ * - an identity already sent (by signature) is not resent; a CHANGED one is. The core only ever
+ * fills a node it has no session for, so a resend could not override anything — this only
+ * bounds the traffic;
+ * - chunked to IDENTITY_SEED_MAX per call, the most the core reads from one.
+ */
+import {
+ IDENTITY_SEED_MAX,
+ parseIdentitySeedEntry,
+ type IdentitySeedEntry
+} from '@shared/agent-identity-seed'
+import type { ObservedClaudeAccount } from '@shared/types'
+
+export interface SeedProject {
+ nodes: ReadonlyArray<{ id: string; agentId?: string }>
+}
+
+export interface SeedStatus {
+ sessionId?: string
+ agentId?: string
+ account?: ObservedClaudeAccount
+}
+
+export function identitySeedSignature(e: IdentitySeedEntry): string {
+ return `${e.nodeId}\u0000${e.agentId}\u0000${e.sessionId}`
+}
+
+export function planIdentitySeed(
+ projects: ReadonlyArray<SeedProject>,
+ statuses: Readonly<Record<string, SeedStatus | undefined>>,
+ sent: ReadonlySet<string>
+): IdentitySeedEntry[][] {
+ const out: IdentitySeedEntry[] = []
+ const seen = new Set<string>()
+ for (const p of projects) {
+ for (const n of p.nodes ?? []) {
+ if (!n || seen.has(n.id)) continue
+ seen.add(n.id)
+ const st = statuses[n.id]
+ if (!st?.sessionId) continue
+ const entry = parseIdentitySeedEntry({
+ nodeId: n.id,
+ agentId: st.agentId ?? n.agentId,
+ sessionId: st.sessionId,
+ ...(st.account ? { account: st.account } : {})
+ })
+ if (!entry || sent.has(identitySeedSignature(entry))) continue
+ out.push(entry)
+ }
+ }
+ const chunks: IdentitySeedEntry[][] = []
+ for (let i = 0; i < out.length; i += IDENTITY_SEED_MAX) {
+ chunks.push(out.slice(i, i + IDENTITY_SEED_MAX))
+ }
+ return chunks
+}
diff --git a/src/server/index.ts b/src/server/index.ts
index 35ffc3049..2b71c4896 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -79,6 +79,7 @@ import {
type MirrorServer,
setNodeSessionName,
setNodeHibernated,
+ seedNodeIdentities,
sessionNameSweepEntries,
nodeSessionName
} from '../core/agent-status-mirror'
@@ -552,6 +553,12 @@ export async function startServer(
if (typeof msg?.nodeId !== 'string' || !msg.nodeId) return
setNodeHibernated(msg.nodeId, msg.on === true)
})
+ // Identity seed (parity with desktop's ipcMain.on(IPC.agentSeedIdentity)): the browser renderer's
+ // persisted agentStatus store fills session ids this server's mirror has none for, so a phone
+ // browsing this host finds an idle node's transcript. Add-only and validated in core.
+ platform.handle(IPC.agentSeedIdentity, (entries: unknown) => {
+ seedNodeIdentities(entries)
+ })
// Phone→host read-acks: the phone drops `~/.nodeterm/acks/<nodeId>.seen` on this host when it READS
// a finished session. Sweep it (15s cadence, cheap dir-mtime gate) and for each ack: `ackDone`
// (mirror resolve + phone Live-Activity dismiss) + broadcast `agent:unread-clear` so the browser
diff --git a/src/shared/agent-identity-seed.ts b/src/shared/agent-identity-seed.ts
new file mode 100644
index 000000000..76f4376a0
--- /dev/null
+++ b/src/shared/agent-identity-seed.ts
@@ -0,0 +1,104 @@
+/**
+ * The boundary rule for `agent:seed-identity` — the renderer reporting, from its persisted
+ * `agentStatus` store (localStorage `nodeterm.agentStatus`), which agent session each node was last
+ * running, so the core's agent-status mirror can advertise it to the phone.
+ *
+ * Why it exists: the mirror learns a session id only from hook events, while the phone's chat view
+ * locates a node's transcript ONLY by the session id it reads off that mirror. A node whose mirror
+ * entry was dropped before #994 (identity used to expire with the state), or that has emitted no
+ * hook event since the app started, is absent — and its phone chat said "No conversation yet" until
+ * the next prompt, while this renderer had the id in localStorage the whole time.
+ *
+ * Every field is validated here, in `src/shared`, so both sides apply the same rule: the renderer
+ * drops what the core would refuse, and the core re-validates, because the values come from
+ * hand-editable localStorage and the ids are shell-reaching elsewhere (`--resume <sessionId>`,
+ * `nt-<nodeId>` tmux names). Anything that does not match is dropped whole — never repaired.
+ */
+import { isSafeNodeId } from './safe-id'
+import { BUILTIN_AGENT_IDS } from './agents/config'
+import type { ObservedClaudeAccount } from './types'
+
+/** At most this many entries are read from one call; the renderer chunks to it. */
+export const IDENTITY_SEED_MAX = 256
+
+export interface IdentitySeedEntry {
+ nodeId: string
+ /** Required: without it the phone cannot tell which agent's transcript reader to use. */
+ agentId: string
+ sessionId: string
+ /** The observed Claude account label, carried like the mirror carries it (a LABEL only). */
+ account?: ObservedClaudeAccount
+}
+
+/** The same session-id alphabet `resumeCommand` / `agent-launch.ts` accept, bounded. */
+const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/
+/** `custom:<uuid>` — the node-id alphabet after the prefix. */
+const CUSTOM_AGENT_ID = /^custom:[A-Za-z0-9._-]{1,128}$/
+const CONFIG_DIR_MAX = 4096
+// eslint-disable-next-line no-control-regex
+const CONTROL_CHARS = /[\u0000-\u001f\u007f]/
+
+export function isSeedSessionId(v: unknown): v is string {
+ return typeof v === 'string' && SAFE_SESSION_ID.test(v)
+}
+
+export function isSeedAgentId(v: unknown): v is string {
+ return (
+ typeof v === 'string' &&
+ ((BUILTIN_AGENT_IDS as readonly string[]).includes(v) || CUSTOM_AGENT_ID.test(v))
+ )
+}
+
+function parseAccount(v: unknown): ObservedClaudeAccount | null {
+ if (!v || typeof v !== 'object') return null
+ const o = v as Record<string, unknown>
+ if (
+ typeof o.configDir !== 'string' ||
+ !o.configDir ||
+ o.configDir.length > CONFIG_DIR_MAX ||
+ CONTROL_CHARS.test(o.configDir)
+ )
+ return null
+ if (!(o.accountId === null || (typeof o.accountId === 'string' && isSafeNodeId(o.accountId))))
+ return null
+ if (typeof o.known !== 'boolean') return null
+ return {
+ configDir: o.configDir,
+ accountId: o.accountId as string | null,
+ known: o.known,
+ ...(o.remote === true ? { remote: true } : {})
+ }
+}
+
+/** One entry, or null when any field fails. */
+export function parseIdentitySeedEntry(v: unknown): IdentitySeedEntry | null {
+ if (!v || typeof v !== 'object') return null
+ const o = v as Record<string, unknown>
+ if (typeof o.nodeId !== 'string' || !isSafeNodeId(o.nodeId)) return null
+ if (!isSeedSessionId(o.sessionId)) return null
+ if (!isSeedAgentId(o.agentId)) return null
+ let account: ObservedClaudeAccount | undefined
+ if (o.account !== undefined) {
+ const a = parseAccount(o.account)
+ if (!a) return null
+ account = a
+ }
+ return {
+ nodeId: o.nodeId,
+ agentId: o.agentId,
+ sessionId: o.sessionId,
+ ...(account ? { account } : {})
+ }
+}
+
+/** The validated entries of one call: a non-array is nothing, at most IDENTITY_SEED_MAX are read,
+ * and an invalid entry is dropped without affecting its neighbours. */
+export function parseIdentitySeed(input: unknown): IdentitySeedEntry[] {
+ if (!Array.isArray(input)) return []
+ const out: IdentitySeedEntry[] = []
+ for (const v of input.slice(0, IDENTITY_SEED_MAX)) {
+ const e = parseIdentitySeedEntry(v)
+ if (e) out.push(e)
+ }
+ return out
+}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 636c5d2be..421fda870 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -177,6 +177,12 @@ export const IPC = {
* phone can render SLEEPING, and gives main the `isHibernated` signal the delivery queue's
* hibernated leg was recorded as missing (agent-messaging.ts). */
agentHibernated: 'agent:hibernated',
+ /** Renderer → main/server: seed the agent-status mirror with the node identities (agentId +
+ * sessionId [+ observed account]) this renderer's persisted agentStatus store holds, for nodes
+ * the mirror has no session for. Arg: `IdentitySeedEntry[]` (`@shared/agent-identity-seed`,
+ * validated and capped there). Fire-and-forget; add-only — never overrides a hook-fed id. Feeds
+ * the phone's chat view, which finds a transcript only by the mirror's session id. */
+ agentSeedIdentity: 'agent:seed-identity',
/** main → renderer: ask the renderer to wake a hibernated node NOW (a phone viewer attached to
* its session over the relay). A nudge, never an assertion: the renderer re-reads the flag and
* no-ops for a non-hibernated or unmounted node — same contract as `wakeHibernatedNode`. Arg:
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f7c955e82..fcd8467f4 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,4 +1,5 @@
import type { TextDeliveryResult } from './text-delivery'
+import type { IdentitySeedEntry } from './agent-identity-seed'
// Types shared across the main, preload, and renderer processes.
import { TABBAR_HEIGHT_PX } from './window-chrome-metrics'
@@ -3803,6 +3804,11 @@ export interface NodeTerminalApi {
* mirrors it into the agent-status file so the phone can render SLEEPING). Fire-and-forget;
* called on every `setHibernated` change and replayed for the persisted set at boot. */
reportHibernated(nodeId: string, on: boolean): void
+ /** Seed the core's agent-status mirror with node identities from this renderer's persisted
+ * agentStatus store (see `@shared/agent-identity-seed`). Fire-and-forget and add-only: the core
+ * fills only nodes it has no session for, and validates every field. A relay tab's api is a
+ * deliberate no-op — its nodes belong to another core, whose own renderer seeds it. */
+ seedAgentIdentity(entries: IdentitySeedEntry[]): void
/** Fires when the core asks this renderer to WAKE a hibernated node NOW (a phone viewer just
* attached to its session over the relay). A nudge with `wakeHibernatedNode`'s exact contract:
* re-read the flag, no-op when not hibernated or not mounted. Returns unsubscribe.