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): keep a node's session identity past the 6 h state expiry

review43b824d5f663
diff --git a/src/core/agent-status-mirror.identity.test.ts b/src/core/agent-status-mirror.identity.test.ts
new file mode 100644
index 000000000..67ae1c973
--- /dev/null
+++ b/src/core/agent-status-mirror.identity.test.ts
@@ -0,0 +1,280 @@
+// Identity outlives state (device-measured bug): the phone's chat view locates a node's transcript
+// by the claude `sessionId` it reads off this mirror, and the mirror used to drop a node's WHOLE
+// entry — identity included — once its STATE was older than EXPIRE_MS. A conversation typed in the
+// terminal and left idle overnight therefore opened on the phone as "No conversation yet" until the
+// next prompt fired a hook. EXPIRE_MS is about a stale STATE ("working" from a dead session); these
+// tests pin that past it the mirror keeps an IDENTITY-ONLY entry instead, bounded by node existence
+// and a much longer identity TTL.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import type { NormalizedAgentEvent } from '@shared/agents/normalize'
+import {
+ buildFile,
+ filterMirrorForNodes,
+ recordAgentEvent,
+ flush,
+ initAgentStatusMirror,
+ setMirrorLiveNodesProvider,
+ nodeState,
+ mirrorEntry,
+ workingNodes,
+ sessionNameSweepEntries,
+ _resetForTest,
+ _snapshot,
+ EXPIRE_MS,
+ IDENTITY_EXPIRE_MS,
+ type MirrorEntry
+} from './agent-status-mirror'
+
+function ev(partial: Partial<NormalizedAgentEvent>): NormalizedAgentEvent {
+ return { nodeId: 'n1', agentId: 'claude', kind: 'state', ...partial } as NormalizedAgentEvent
+}
+
+const account = { configDir: '/home/u/.claude', accountId: null, known: true }
+
+describe('buildFile — identity-only entries past EXPIRE_MS', () => {
+ const now = IDENTITY_EXPIRE_MS + 10 * EXPIRE_MS
+
+ it('keeps agentId/sessionId/account/name of an idle node older than 6 h, with NO state', () => {
+ const doc = buildFile(
+ {
+ n1: {
+ state: 'done',
+ agentId: 'claude',
+ sessionId: 'sess-1',
+ account,
+ name: 'refactor',
+ updatedAt: now - EXPIRE_MS - 1
+ }
+ },
+ now
+ )
+ const n1 = JSON.parse(JSON.stringify(doc)).nodes.n1
+ expect(n1).toEqual({
+ agentId: 'claude',
+ sessionId: 'sess-1',
+ account,
+ name: 'refactor',
+ updatedAt: now - EXPIRE_MS - 1
+ })
+ expect('state' in n1).toBe(false)
+ })
+
+ it('strips a stale "working" to identity — the rationale of EXPIRE_MS is the state, not the id', () => {
+ const doc = buildFile(
+ { n1: { state: 'working', agentId: 'codex', sessionId: 's', updatedAt: now - EXPIRE_MS - 1 } },
+ now
+ )
+ expect(doc.nodes.n1.state).toBeUndefined()
+ expect(doc.nodes.n1.sessionId).toBe('s')
+ })
+
+ it('still drops a stale entry that carries no identity at all', () => {
+ const doc = buildFile({ n1: { state: 'working', updatedAt: now - EXPIRE_MS - 1 } }, now)
+ expect(doc.nodes).toEqual({})
+ })
+
+ it('drops the identity past IDENTITY_EXPIRE_MS (the file cannot grow forever)', () => {
+ const doc = buildFile(
+ {
+ old: { agentId: 'claude', sessionId: 'a', updatedAt: now - IDENTITY_EXPIRE_MS - 1 },
+ kept: { agentId: 'claude', sessionId: 'b', updatedAt: now - IDENTITY_EXPIRE_MS + 1 }
+ },
+ now
+ )
+ expect(Object.keys(doc.nodes)).toEqual(['kept'])
+ })
+
+ it("drops a deleted node's identity when the live node set is known", () => {
+ const doc = buildFile(
+ {
+ alive: { agentId: 'claude', sessionId: 'a', updatedAt: now - EXPIRE_MS - 1 },
+ gone: { agentId: 'claude', sessionId: 'b', updatedAt: now - EXPIRE_MS - 1 },
+ // A FRESH entry is never pruned by existence: a brand-new node may not be saved yet.
+ fresh: { state: 'working', agentId: 'claude', sessionId: 'c', updatedAt: now - 1 }
+ },
+ now,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ new Set(['alive'])
+ )
+ expect(Object.keys(doc.nodes).sort()).toEqual(['alive', 'fresh'])
+ })
+
+ it('keeps a hibernated entry whole, state included (unchanged behavior)', () => {
+ const doc = buildFile(
+ { n1: { state: 'done', agentId: 'claude', sessionId: 's', hibernated: true, updatedAt: now - EXPIRE_MS - 1 } },
+ now
+ )
+ expect(doc.nodes.n1.state).toBe('done')
+ expect(doc.nodes.n1.hibernated).toBe(true)
+ })
+
+ it('the per-project SSH slice carries the identity-only entry', () => {
+ const doc = buildFile(
+ {
+ mine: { state: 'done', agentId: 'claude', sessionId: 'sess-1', updatedAt: now - EXPIRE_MS - 1 },
+ other: { agentId: 'claude', sessionId: 'x', updatedAt: now - EXPIRE_MS - 1 }
+ },
+ now
+ )
+ const slice = filterMirrorForNodes(doc, new Set(['mine']))
+ expect(slice.nodes).toEqual({
+ mine: { agentId: 'claude', sessionId: 'sess-1', updatedAt: now - EXPIRE_MS - 1 }
+ })
+ })
+})
+
+describe('live mirror — identity survives the state expiry', () => {
+ let dir: string
+ let file: string
+ let nowSpy: ReturnType<typeof vi.spyOn>
+
+ beforeEach(() => {
+ _resetForTest()
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-mirror-identity-'))
+ file = path.join(dir, 'agent-status.json')
+ nowSpy = vi.spyOn(Date, 'now')
+ nowSpy.mockReturnValue(1_000_000)
+ initAgentStatusMirror(file)
+ })
+ afterEach(() => {
+ nowSpy.mockRestore()
+ _resetForTest()
+ fs.rmSync(dir, { recursive: true, force: true })
+ })
+
+ const read = (): { nodes: Record<string, Record<string, unknown>> } =>
+ JSON.parse(fs.readFileSync(file, 'utf-8'))
+
+ it('an idle node older than 6 h keeps sessionId/agentId on disk and in memory, with no state', async () => {
+ recordAgentEvent(ev({ state: 'working', newTurn: true, sessionId: 'sess-1' }))
+ recordAgentEvent(ev({ state: 'done', sessionId: 'sess-1' }))
+ nowSpy.mockReturnValue(1_000_000 + EXPIRE_MS + 1)
+ await flush()
+
+ expect(read().nodes.n1).toMatchObject({ agentId: 'claude', sessionId: 'sess-1' })
+ expect('state' in read().nodes.n1).toBe(false)
+ // Memory is stripped too: no reader of the live map may see the expired state.
+ expect(nodeState('n1')).toBeUndefined()
+ expect(mirrorEntry('n1')?.sessionId).toBe('sess-1')
+ expect(mirrorEntry('n1')?.stateExpired).toBe(true)
+ })
+
+ it('a stale working node is no longer reported as working once stripped', async () => {
+ recordAgentEvent(ev({ state: 'working', newTurn: true, sessionId: 'sess-1' }))
+ nowSpy.mockReturnValue(1_000_000 + EXPIRE_MS + 1)
+ await flush()
+ expect(workingNodes()).toEqual([])
+ })
+
+ it('a later event re-grows the state on the kept identity and clears the expired marker', async () => {
+ recordAgentEvent(ev({ state: 'done', sessionId: 'sess-1' }))
+ nowSpy.mockReturnValue(1_000_000 + EXPIRE_MS + 1)
+ await flush()
+ recordAgentEvent(ev({ state: 'working', newTurn: true, sessionId: 'sess-1' }))
+ const e = _snapshot().n1 as MirrorEntry
+ expect(e.state).toBe('working')
+ expect(e.stateExpired).toBeUndefined()
+ })
+
+ it("drops a deleted node's identity via the live-node provider", async () => {
+ recordAgentEvent(ev({ nodeId: 'alive', state: 'done', sessionId: 'a' }))
+ recordAgentEvent(ev({ nodeId: 'gone', state: 'done', sessionId: 'b' }))
+ setMirrorLiveNodesProvider(() => new Set(['alive']))
+ nowSpy.mockReturnValue(1_000_000 + EXPIRE_MS + 1)
+ await flush()
+ expect(Object.keys(read().nodes)).toEqual(['alive'])
+ expect(_snapshot().gone).toBeUndefined()
+ })
+
+ it('an UNKNOWABLE live set (provider answers undefined, or throws) prunes nothing by existence', async () => {
+ recordAgentEvent(ev({ nodeId: 'a', state: 'done', sessionId: 'a' }))
+ setMirrorLiveNodesProvider(() => undefined)
+ nowSpy.mockReturnValue(1_000_000 + EXPIRE_MS + 1)
+ await flush()
+ expect(Object.keys(read().nodes)).toEqual(['a'])
+ setMirrorLiveNodesProvider(() => {
+ throw new Error('index not loaded')
+ })
+ await flush()
+ expect(Object.keys(read().nodes)).toEqual(['a'])
+ })
+
+ it('the identity TTL bound drops it from disk and memory', async () => {
+ recordAgentEvent(ev({ state: 'done', sessionId: 'sess-1' }))
+ nowSpy.mockReturnValue(1_000_000 + IDENTITY_EXPIRE_MS + 1)
+ await flush()
+ expect(read().nodes).toEqual({})
+ expect(_snapshot().n1).toBeUndefined()
+ })
+
+ it('the restart restore keeps the identity-only entry (and keeps it state-less)', async () => {
+ recordAgentEvent(ev({ state: 'done', sessionId: 'sess-1', account }))
+ await flush() // written while fresh, WITH its state
+ _resetForTest()
+ nowSpy.mockReturnValue(1_000_000 + EXPIRE_MS + 1)
+ initAgentStatusMirror(file)
+
+ const e = _snapshot().n1 as MirrorEntry
+ expect(e).toBeDefined()
+ expect(e.state).toBeUndefined()
+ expect(e.sessionId).toBe('sess-1')
+ expect(e.agentId).toBe('claude')
+ expect(e.account).toEqual(account)
+ expect(e.restored).toBe(true)
+ await flush()
+ expect(read().nodes.n1).toMatchObject({ sessionId: 'sess-1' })
+ expect('state' in read().nodes.n1).toBe(false)
+ })
+
+ it('the restart restore drops an identity past IDENTITY_EXPIRE_MS', async () => {
+ recordAgentEvent(ev({ state: 'done', sessionId: 'sess-1' }))
+ await flush()
+ _resetForTest()
+ nowSpy.mockReturnValue(1_000_000 + IDENTITY_EXPIRE_MS + 1)
+ initAgentStatusMirror(file)
+ expect(_snapshot().n1).toBeUndefined()
+ })
+})
+
+describe('session-name sweep scope', () => {
+ let nowSpy: ReturnType<typeof vi.spyOn>
+ beforeEach(() => {
+ _resetForTest()
+ nowSpy = vi.spyOn(Date, 'now')
+ })
+ afterEach(() => {
+ nowSpy.mockRestore()
+ _resetForTest()
+ })
+
+ it('does not walk identity-only entries (the sweep cost stays bounded by EXPIRE_MS)', async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-mirror-sweep-'))
+ try {
+ nowSpy.mockReturnValue(1_000_000)
+ initAgentStatusMirror(path.join(dir, 'agent-status.json'))
+ recordAgentEvent(ev({ nodeId: 'old', state: 'done', sessionId: 'a' }))
+ nowSpy.mockReturnValue(1_000_000 + EXPIRE_MS + 1)
+ recordAgentEvent(ev({ nodeId: 'new', state: 'done', sessionId: 'b' }))
+ await flush()
+ expect(sessionNameSweepEntries().map((e) => e.nodeId)).toEqual(['new'])
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
+
+// Both shells must wire the live-node provider, or the Server Edition (or the desktop) keeps a
+// deleted node's identity for the whole TTL. The seam is optional, so a missing call still compiles.
+describe('live-node provider wiring (both shells)', () => {
+ it.each(['src/main/index.ts', 'src/server/index.ts'])('%s wires setMirrorLiveNodesProvider to the workspace store', (f) => {
+ const src = fs.readFileSync(path.join(__dirname, '..', '..', f), 'utf8').replace(/\r\n/g, '\n')
+ expect(src).toMatch(/setMirrorLiveNodesProvider\(\(\) => workspaceStore\.knownNodeIds\(\)\)/)
+ })
+})
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index cfd8fa21f..59b6112db 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -32,9 +32,25 @@ import { WORKING_STALE_MS, isStaleWorking } from '@shared/agents/stale'
// late PostToolUse `working` POST can arrive after the `Stop` `done`. Hold `done` against any
// non-newTurn `working` for this long.
export const DONE_HOLDOFF_MS = 3000
-// Drop entries whose state hasn't been refreshed in this long, so the file can't accumulate
-// unbounded nodes or advertise a stale "working" from a crashed/abandoned session.
+// Drop a node's STATE once it hasn't been refreshed in this long, so the file can't advertise a
+// stale "working" from a crashed/abandoned session. The node's IDENTITY (agentId/sessionId/
+// account/name) outlives it — see IDENTITY_EXPIRE_MS.
export const EXPIRE_MS = 6 * 60 * 60_000
+/**
+ * How long an entry whose state has expired is kept as an IDENTITY-ONLY entry (no `state`, nothing
+ * state-derived). EXPIRE_MS is about the state, and dropping the whole entry with it was a
+ * device-measured bug: the phone's chat view finds a node's transcript ONLY through the `sessionId`
+ * it reads here, so a conversation typed in the terminal and left idle overnight opened on the
+ * phone as "No conversation yet" until the next prompt fired a hook.
+ *
+ * Measured from `updatedAt` (the last STATE commit), deliberately not from the last time an id was
+ * seen: a node's session id only changes across a session boundary, and every boundary commits a
+ * state, so "30 days since the node last did anything" is the same clock. Identity-only entries are
+ * also dropped as soon as their node is known to be gone (`setMirrorLiveNodesProvider`); this TTL
+ * is the bound when that cannot be known (a folder project that is unavailable, an SSH project
+ * never connected).
+ */
+export const IDENTITY_EXPIRE_MS = 30 * 24 * 60 * 60_000
// Coalesce bursty hook POSTs (a single turn fires many tool events) into one disk write.
export const WRITE_DEBOUNCE_MS = 300
@@ -152,6 +168,15 @@ export interface MirrorEntry {
* Runtime-only (not in `buildFile`'s allowlist); cleared by every state commit.
*/
sessionStarted?: { sessionId: string; agentId: NormalizedAgentEvent['agentId']; at: number }
+ /**
+ * The entry's state EXPIRED (no state commit for EXPIRE_MS) and was stripped: this is an
+ * IDENTITY-ONLY entry kept so external readers can still find the node's session (see
+ * IDENTITY_EXPIRE_MS). It carries no `state` and no evidence about one; agent messaging reads it
+ * as "no current observation", exactly like a node that has never posted. Runtime-only (not in
+ * `buildFile`'s allowlist — the file says the same thing by omitting `state`); cleared by the next
+ * state commit.
+ */
+ stateExpired?: true
}
/** This host's Server-Edition install metadata (spec: server-update). Written by the installer
@@ -228,6 +253,9 @@ export interface MirrorFile {
nodes: Record<
string,
{
+ /** Absent = unknown: idle, between sessions, or an IDENTITY-ONLY entry whose state expired
+ * (older than EXPIRE_MS — see IDENTITY_EXPIRE_MS). A reader must never read absence as
+ * "working"; the identity fields stay valid either way. */
state?: AgentState
agentId?: AgentId
sessionId?: string
@@ -519,6 +547,7 @@ function reduceEffectiveEntry(
if (proof) next.verifiedAt = now
next.clientRevision = ev.clientRevision
delete next.sessionStarted
+ delete next.stateExpired
// Which KIND of `done` this is, recorded on the same edge as the state itself. `idle` is only
// ever meaningful on a `done`; assigning (not merging) is the point — a later, genuine turn-end
// `done` must clear the marker, or a node would stay tainted for the rest of its session.
@@ -639,6 +668,46 @@ function reduceEffectiveEntry(
return next
}
+/**
+ * The identity-only form of an entry whose state expired: agentId, sessionId, account and name,
+ * with the state and everything state-derived removed. `undefined` when there is no identity worth
+ * keeping (neither an agentId nor a sessionId). `updatedAt` keeps the state's clock — it is what the
+ * identity TTL is measured from, and it keeps the entry reading as old to any freshness check.
+ */
+function identityOnly(e: MirrorEntry): MirrorEntry | undefined {
+ if (!e.agentId && !e.sessionId) return undefined
+ return {
+ ...(e.agentId ? { agentId: e.agentId } : {}),
+ ...(e.sessionId ? { sessionId: e.sessionId } : {}),
+ ...(e.account ? { account: e.account } : {}),
+ ...(e.name ? { name: e.name } : {}),
+ ...(e.restored ? { restored: true as const } : {}),
+ updatedAt: e.updatedAt,
+ stateExpired: true
+ }
+}
+
+/**
+ * Age one entry against the two horizons. Pure. Returns the entry unchanged while its state is
+ * fresh (or it is hibernated — hibernation IS long idleness), its identity-only form past
+ * EXPIRE_MS, and `undefined` once it should go: past IDENTITY_EXPIRE_MS, or past EXPIRE_MS for a
+ * node `liveIds` says no longer exists. A FRESH entry is never pruned by existence — a brand-new
+ * node may not have been saved yet. `liveIds` undefined = unknowable, prune by TTL only.
+ */
+export function ageEntry(
+ id: string,
+ e: MirrorEntry,
+ now: number,
+ expireMs = EXPIRE_MS,
+ liveIds?: ReadonlySet<string>
+): MirrorEntry | undefined {
+ if (e.hibernated || now - e.updatedAt <= expireMs) return e
+ if (now - e.updatedAt > IDENTITY_EXPIRE_MS) return undefined
+ if (liveIds && !liveIds.has(id)) return undefined
+ if (e.stateExpired) return e
+ return identityOnly(e)
+}
+
/**
* Restrict a mirror doc to the given node ids. Pure. Used by the SSH-host status push: each
* connected host receives ONLY its own project's nodes — the full mirror would leak other
@@ -682,13 +751,16 @@ export function buildFile(
settings?: MirrorSettings,
usage?: MirrorUsage,
inbox?: MirrorInbox,
- server?: MirrorServer
+ server?: MirrorServer,
+ liveIds?: ReadonlySet<string>
): MirrorFile {
const out: MirrorFile = { v: 1, updatedAt: now, nodes: {} }
- for (const [id, e] of Object.entries(nodes)) {
- // A hibernated entry never expires: hibernation IS long idleness, so the staleness rule would
- // erase exactly the durable fact the flag carries (see MirrorEntry.hibernated).
- if (now - e.updatedAt > expireMs && !e.hibernated) continue
+ for (const [id, entry] of Object.entries(nodes)) {
+ // Past `expireMs` the STATE goes but the identity stays (see IDENTITY_EXPIRE_MS). A hibernated
+ // entry never expires at all: hibernation IS long idleness, so the staleness rule would erase
+ // exactly the durable fact the flag carries (see MirrorEntry.hibernated).
+ const e = ageEntry(id, entry, now, expireMs, liveIds)
+ if (!e) continue
// Undefined fields drop out of JSON.stringify — an idle node keeps agentId/sessionId
// without a `state` key.
out.nodes[id] = {
@@ -1333,6 +1405,25 @@ function safeUsage(): MirrorUsage | undefined {
* (spec: server-update). Called once by the SERVER shell on launch; absent ⇒ the mirror writes no
* `server` key (the desktop app's shape is byte-identical to before this block existed).
*/
+let liveNodesProvider: (() => ReadonlySet<string> | undefined) | null = null
+/**
+ * Which node ids exist in ANY project (open or closed), so an identity-only entry for a deleted
+ * node can be dropped (see IDENTITY_EXPIRE_MS). The provider answers `undefined` when it cannot know
+ * the full set — then nothing is pruned by existence, only by TTL. A throw reads as `undefined`.
+ */
+export function setMirrorLiveNodesProvider(p: (() => ReadonlySet<string> | undefined) | null): void {
+ liveNodesProvider = p
+}
+
+function safeLiveNodes(): ReadonlySet<string> | undefined {
+ if (!liveNodesProvider) return undefined
+ try {
+ return liveNodesProvider() ?? undefined
+ } catch {
+ return undefined
+ }
+}
+
export function setMirrorServerProvider(p: (() => MirrorServer | undefined) | null): void {
serverProvider = p
}
@@ -1413,9 +1504,13 @@ function loadPersisted(file: string): void {
// Hibernated entries survive the expiry, as in buildFile: hours of idleness is what the
// flag MEANS. (The renderer also re-reports its persisted set at boot — this restore just
// keeps the file honest in the window before that report lands.)
- if (now - updatedAt > EXPIRE_MS && e.hibernated !== true) continue
+ const expired = now - updatedAt > EXPIRE_MS && e.hibernated !== true
+ // Past EXPIRE_MS only the IDENTITY is restored (as buildFile would write it): the phone's
+ // chat view still needs the session id, the 6 h rule is about the state. Past the identity
+ // TTL, or with no identity at all, nothing is.
+ if (expired && (now - updatedAt > IDENTITY_EXPIRE_MS || (!e.agentId && !e.sessionId))) continue
state.set(id, {
- state: e.state,
+ ...(expired ? { stateExpired: true as const } : { state: e.state }),
agentId: e.agentId,
sessionId: e.sessionId,
// Identity survives the restart like agentId/sessionId does — for a hand-launched
@@ -2034,14 +2129,21 @@ export function workingNodes(): { nodeId: string; agentId?: string; sessionId?:
return out
}
-/** The entries the session-name sweep walks: id + what it needs to resolve and dedupe. */
+/**
+ * The entries the session-name sweep walks: id + what it needs to resolve and dedupe.
+ *
+ * Identity-only entries (`stateExpired`) are left out: before they existed the sweep only ever saw
+ * nodes active within EXPIRE_MS, and keeping it there keeps its cost (a transcript read — over ssh
+ * for a remote node — per node per pass) where it was. A node that has done nothing for 6 h has not
+ * been renamed either; a `/rename` is a prompt, whose hook re-grows the state and re-admits it.
+ */
export function sessionNameSweepEntries(): {
nodeId: string
sessionId?: string
agentId?: string
name?: string
}[] {
- return [...state].map(([nodeId, e]) => ({
+ return [...state].filter(([, e]) => !e.stateExpired).map(([nodeId, e]) => ({
nodeId,
sessionId: e.sessionId,
agentId: e.agentId,
@@ -2147,8 +2249,9 @@ export async function flush(): Promise<void> {
// - RESOLVED must not get a LONGER one. It is the phone's archive, but the phone keeps its own
// copy of what it has read; this file is a live side-channel, not the archive of record, and
// the cap already bounds history.
- // 6 h is the horizon at which the module stops believing anything about a node at all, so an
- // event outliving `state`/`inboxNodes` would be a card about a node the mirror has forgotten.
+ // 6 h is the horizon at which the module stops believing anything about a node's STATE (only its
+ // identity survives it), so an event outliving `state`/`inboxNodes` would be a card about a state
+ // the mirror has forgotten.
// Well clear of QUESTION_DEDUP_WINDOW_MS (10 min), so the title-dedup is untouched.
//
// Pruned BEFORE the doc is built, unlike the two below: `buildFile` applies the expiry to `nodes`
@@ -2158,10 +2261,18 @@ export async function flush(): Promise<void> {
if (inboxEvents.some((e) => now - e.ts > EXPIRE_MS)) {
inboxEvents = inboxEvents.filter((e) => now - e.ts <= EXPIRE_MS)
}
+ // Age memory FIRST, with the same rule buildFile applies: an expired state is stripped to its
+ // identity (so no in-process reader — messaging, triggers, the resync — sees a 6 h-old state),
+ // and an identity past its TTL or for a node that no longer exists is dropped, so the map itself
+ // can't grow without bound.
+ const liveIds = safeLiveNodes()
+ for (const [id, e] of state) {
+ const aged = ageEntry(id, e, now, EXPIRE_MS, liveIds)
+ if (!aged) state.delete(id)
+ else if (aged !== e) state.set(id, aged)
+ }
const inbox: MirrorInbox = { events: inboxEvents, nodes: Object.fromEntries(inboxNodes) }
- const doc = buildFile(Object.fromEntries(state), now, undefined, safeSettings(), safeUsage(), inbox, safeServer())
- // Also drop expired entries from memory so the map itself can't grow without bound.
- for (const [id, e] of state) if (now - e.updatedAt > EXPIRE_MS) state.delete(id)
+ const doc = buildFile(Object.fromEntries(state), now, undefined, safeSettings(), safeUsage(), inbox, safeServer(), liveIds)
// Prune stale per-node activity the same way (events stay — they are capped feed history).
for (const [id, n] of inboxNodes) if (now - n.updatedAt > EXPIRE_MS) inboxNodes.delete(id)
for (const cb of flushListeners) {
@@ -2193,6 +2304,7 @@ export function _resetForTest(): void {
settingsProvider = null
usageProvider = null
serverProvider = null
+ liveNodesProvider = null
inboxEvents = []
inboxNodes.clear()
inboxSeq = 0
diff --git a/src/core/agents/agent-message-decide.test.ts b/src/core/agents/agent-message-decide.test.ts
index aa728caae..758c0bdd1 100644
--- a/src/core/agents/agent-message-decide.test.ts
+++ b/src/core/agents/agent-message-decide.test.ts
@@ -111,6 +111,21 @@ describe('decideDelivery — one case per refusal', () => {
expect((o as { reason: string }).reason).toMatch(/restored from disk/i)
})
+ it('an IDENTITY-ONLY entry (state expired past 6 h) is judged like a never-posted node, never as a stale script', () => {
+ // The mirror keeps agentId/sessionId after EXPIRE_MS so the phone can find the transcript, but
+ // strips every piece of state evidence. Without the `stateExpired` exemption the identity gate
+ // would read it as "observed this run with no clientRevision" and accuse the node's hook script.
+ const expired: MirrorEntry = { agentId: 'claude', sessionId: 's', updatedAt: 1, stateExpired: true }
+ expect(decideDelivery(ready({ target: expired, tokenFilePresent: true })).kind).toBe('targetStatusStale')
+ expect(decideDelivery(ready({ target: expired, tokenFilePresent: false })).kind).toBe(
+ 'targetStatusUnverified'
+ )
+ const verifiedExpired = { ...expired, stateVerified: true }
+ const o = decideDelivery(ready({ target: verifiedExpired }))
+ expect(o.kind).toBe('targetNotIdleUnknown')
+ expect((o as { reason: string }).reason).toMatch(/expired/i)
+ })
+
it('targetNotIdleUnknown for a `done` inferred from idle_prompt', () => {
// A node blocked on an approval is ALSO idle at its prompt. Canvas.tsx already discards the
// idle rescue for an `undefined` node; messaging must not be the one consumer that trusts it.
diff --git a/src/core/agents/agent-message-decide.ts b/src/core/agents/agent-message-decide.ts
index f7692b133..50b368b0e 100644
--- a/src/core/agents/agent-message-decide.ts
+++ b/src/core/agents/agent-message-decide.ts
@@ -231,6 +231,12 @@ function idleRefusal(e: MirrorEntry | undefined): AgentMessageOutcome | null {
kind: 'targetNotIdleUnknown',
reason: 'the last known status was restored from disk at startup, not observed this run'
}
+ // An identity-only entry: the mirror kept the session id past EXPIRE_MS but threw the state away.
+ if (e.stateExpired)
+ return {
+ kind: 'targetNotIdleUnknown',
+ reason: 'the last known status expired (no hook event for over 6 hours)'
+ }
if (e.state === undefined)
return { kind: 'targetNotIdleUnknown', reason: 'the node is between sessions (no current state)' }
if (e.state !== 'done') return { kind: 'targetBusy', state: e.state }
@@ -294,7 +300,9 @@ function identityRefusal(
// and a never-seen node carry no observation, so calling their script stale would be an
// accusation we have no evidence for. They fall through to the token-file question, which is
// answerable without an event.
- const observed = !!e && e.restored !== true
+ // An identity-only entry (`stateExpired`) is not an observation either: its state and every
+ // piece of evidence about that state were stripped when it expired.
+ const observed = !!e && e.restored !== true && e.stateExpired !== true
if (observed && !(typeof e.clientRevision === 'number' && e.clientRevision >= MIN_TOKEN_AWARE_REVISION))
return {
kind: 'targetHookScriptStale',
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index 78aa05f12..5c1e51b97 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -2309,3 +2309,30 @@ describe('getNodeResolved — a node with its cwd as the canvas sees it', () =>
expect(store.getNodeResolved('nope')).toBeUndefined()
})
})
+
+// The agent-status mirror keeps an IDENTITY-ONLY entry past its 6 h state expiry and drops it once
+// its node no longer exists in any project. Dropping on a guess would cost the phone a session id,
+// so the store answers `undefined` whenever it cannot see every project's nodes.
+describe('knownNodeIds — every node id in every project, or undefined when it cannot know', () => {
+ it('is undefined before the index is loaded', () => {
+ expect(new WorkspaceStore().knownNodeIds()).toBeUndefined()
+ })
+ it('lists the nodes of local-ref and inline projects, closed ones included', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([
+ project({ id: 'p-local', cwd: projRoot }),
+ project({ id: 'p-inline', cwd: undefined, closed: true, nodes: [
+ { id: 'term-2', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title: 't', color: '#fff', group: null }
+ ] })
+ ]))
+ expect([...(store.knownNodeIds() ?? [])].sort()).toEqual(['term-1', 'term-2'])
+ })
+ it('is undefined when a local ref has no readable content this run', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ id: 'p-local', cwd: projRoot })]))
+ await fs.rm(path.join(projRoot, '.nodeterm'), { recursive: true, force: true })
+ const fresh = new WorkspaceStore()
+ await fresh.load()
+ expect(fresh.knownNodeIds()).toBeUndefined()
+ })
+})
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index ffd0ee7ca..2b08551a5 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -1504,6 +1504,38 @@ export class WorkspaceStore {
return undefined
}
+ /**
+ * Every node id in every project the index holds — open, closed and SSH alike — or `undefined`
+ * when that set cannot be known: the index is not loaded, a local ref's project.json has not been
+ * read this run (unavailable folder, corrupt file), or an SSH entry has no offline cache.
+ *
+ * The agent-status mirror uses it to drop an IDENTITY-ONLY entry (a session id kept past the 6 h
+ * state expiry) whose node was deleted while this process was not watching. A wrong "gone" costs
+ * the phone that node's session id, so every doubt answers `undefined` — the mirror then bounds
+ * the entry by its identity TTL alone. Same three-entry-kind scan as `findNode`.
+ */
+ knownNodeIds(): Set<string> | undefined {
+ if (!this.index) return undefined
+ const ids = new Set<string>()
+ for (const e of this.index.entries) {
+ let nodes: CanvasNodeState[] | undefined
+ if (e.project) nodes = e.project.nodes
+ else if (e.cache) nodes = e.cache.nodes
+ else if (e.cwd) {
+ const raw = this.lastWritten.get(projectFilePath(e.cwd))
+ if (!raw) return undefined
+ try {
+ nodes = (JSON.parse(raw) as ProjectFileV1).nodes
+ } catch {
+ return undefined
+ }
+ }
+ if (!Array.isArray(nodes)) return undefined
+ for (const n of nodes) if (n && typeof n.id === 'string') ids.add(n.id)
+ }
+ return ids
+ }
+
/**
* Every persisted canvas as {id, nodes, bridges} — the raw material the Server Edition derives
* its context-link map from (src/server/context-link.ts). Same three-entry-kind scan as
diff --git a/src/main/index.ts b/src/main/index.ts
index 2bb6e5fcf..5677e08fa 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -173,6 +173,7 @@ import {
recordRawToolEvent,
recordContextUsage,
setMirrorSettingsProvider,
+ setMirrorLiveNodesProvider,
setMirrorUsageProvider,
buildMirrorUsage,
onInboxActionable,
@@ -2111,6 +2112,9 @@ app.whenReady().then(async () => {
void flushAgentStatusMirror()
})
.catch(() => {})
+ // Lets the mirror drop an identity-only entry (a session id kept past the 6 h state expiry)
+ // once its node is gone from every project. `undefined` = cannot know = keep, TTL-bounded.
+ setMirrorLiveNodesProvider(() => workspaceStore.knownNodeIds())
setMirrorSettingsProvider((): MirrorSettings => {
const s = settingsStore.get()
return {
diff --git a/src/main/notch-hud-model.test.ts b/src/main/notch-hud-model.test.ts
index 24082b7bd..995c2b512 100644
--- a/src/main/notch-hud-model.test.ts
+++ b/src/main/notch-hud-model.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'
import type { NormalizedAgentEvent } from '@shared/agents/normalize'
import type { NodeStateChange, NodeNowChange, MirrorFile } from '../core/agent-status-mirror'
-import { PROMPT_MAX, firstLine } from '../core/agent-status-mirror'
+import { PROMPT_MAX, firstLine, EXPIRE_MS } from '../core/agent-status-mirror'
import {
createHudModel,
bucketState,
@@ -226,6 +226,22 @@ describe('6h drop', () => {
expect(rowFor(rows, 'present')?.state).toBe('done')
})
+ it('an IDENTITY-ONLY mirror entry (state expired) does not keep a node present', () => {
+ // Past EXPIRE_MS the mirror keeps a node's agentId/sessionId (the phone needs the session id)
+ // but drops its state. For the HUD that is the same fact the old full drop was: nothing is
+ // known about this node's state, so it must age out exactly as an absent node does.
+ const m = createHudModel()
+ m.applyStateChange(stateChange({ nodeId: 'old', state: 'done', ts: T0 }))
+ const later = T0 + EXPIRE_MS + 1
+ m.applyMirrorFlush({
+ v: 1,
+ updatedAt: later,
+ nodes: { old: { agentId: 'claude', sessionId: 's', updatedAt: T0 } }
+ })
+ expect(m.prune(T0 + HUD_STALE_DROP_MS + 1)).toBe(true)
+ expect(rowFor(m.buildRows(T0 + HUD_STALE_DROP_MS + 1, titleOf), 'old')).toBeUndefined()
+ })
+
it('never drops a LIVE working node', () => {
const m = createHudModel()
m.applyStateChange(stateChange({ nodeId: 'w', state: 'working', ts: T0 }))
diff --git a/src/main/notch-hud-model.ts b/src/main/notch-hud-model.ts
index bada300df..36c671538 100644
--- a/src/main/notch-hud-model.ts
+++ b/src/main/notch-hud-model.ts
@@ -9,7 +9,7 @@
// clipping constant (PROMPT_MAX) — never electron.
import type { NormalizedAgentEvent, AgentState } from '../shared/agents/normalize'
-import { PROMPT_MAX } from '../core/agent-status-mirror'
+import { PROMPT_MAX, EXPIRE_MS } from '../core/agent-status-mirror'
import type { NodeStateChange, NodeNowChange, MirrorFile } from '../core/agent-status-mirror'
import { WORKING_STALE_MS } from '@shared/agents/stale'
@@ -224,6 +224,12 @@ export function createHudModel(): HudModel {
function applyMirrorFlush(doc: MirrorFile): void {
const seen = new Set<string>()
for (const [nodeId, n] of Object.entries(doc.nodes ?? {})) {
+ // An IDENTITY-ONLY entry (no state, older than the mirror's state expiry): the mirror keeps
+ // the node's session id for the phone, but says nothing about its state. To the HUD that is
+ // the same as the node being absent — it must age out, not be pinned present for 30 days.
+ const identityOnly =
+ !n.state && !n.hibernated && typeof doc.updatedAt === 'number' && doc.updatedAt - n.updatedAt > EXPIRE_MS
+ if (identityOnly) continue
seen.add(nodeId)
// Is this the FIRST time this process hears of the node? The mirror keeps entries for hours
// and is re-read at every launch, so a node we're meeting through the file is HISTORY, not an
diff --git a/src/main/remote-ssh/remote-status-push.test.ts b/src/main/remote-ssh/remote-status-push.test.ts
index fc0a49547..9f5fdc18c 100644
--- a/src/main/remote-ssh/remote-status-push.test.ts
+++ b/src/main/remote-ssh/remote-status-push.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import type { MirrorFile, MirrorSettings } from '../../core/agent-status-mirror'
import { initRemoteStatusPush, STATUS_EDGE_MIN_GAP_MS } from './remote-status-push'
+import { buildFile, EXPIRE_MS } from '../../core/agent-status-mirror'
import type { AgentState } from '../../shared/agents/normalize'
function doc(updatedAt: number, ids: string[]): MirrorFile {
@@ -64,6 +65,20 @@ describe('initRemoteStatusPush', () => {
expect(Object.keys(p2.nodes)).toEqual(['b1'])
})
+ it("pushes an IDENTITY-ONLY entry (state expired) so the phone keeps the node's session id", () => {
+ // The phone's chat view finds a node's transcript ONLY via the sessionId in this slice. Past
+ // EXPIRE_MS the mirror strips the state but keeps the identity; the slice must carry it.
+ const now = EXPIRE_MS * 2
+ const built = buildFile(
+ { a1: { state: 'done', agentId: 'claude', sessionId: 'sess-1', updatedAt: now - EXPIRE_MS - 1 } },
+ now
+ )
+ disposer = initRemoteStatusPush(deps())
+ flushCb!(built)
+ const slice = JSON.parse(pushes[0].json)
+ expect(slice.nodes.a1).toEqual({ agentId: 'claude', sessionId: 'sess-1', updatedAt: now - EXPIRE_MS - 1 })
+ })
+
it('throttles a burst into leading + one trailing push with the LATEST doc', () => {
disposer = initRemoteStatusPush(deps({ throttleMs: 2000 }))
flushCb!(doc(1, ['a1']))
diff --git a/src/server/index.ts b/src/server/index.ts
index 7c527bc72..35ffc3049 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -70,6 +70,7 @@ import {
recordAgentEvent,
ackDone,
setMirrorSettingsProvider,
+ setMirrorLiveNodesProvider,
setMirrorServerProvider,
onInboxActionable,
onNodeStateChange,
@@ -452,6 +453,9 @@ export async function startServer(
void flushAgentStatusMirror()
})
.catch(() => {})
+ // Lets the mirror drop an identity-only entry (a session id kept past the 6 h state expiry)
+ // once its node is gone from every project. `undefined` = cannot know = keep, TTL-bounded.
+ setMirrorLiveNodesProvider(() => workspaceStore.knownNodeIds())
setMirrorSettingsProvider((): MirrorSettings => {
const s = settingsStore.get()
return {