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.

refactor(agentStatus): per-session factory; local session reuses default instance

enes3442a6a22dac
diff --git a/src/renderer/session/session.ts b/src/renderer/session/session.ts
index c3ae112c9..685c6e317 100644
--- a/src/renderer/session/session.ts
+++ b/src/renderer/session/session.ts
@@ -1,18 +1,7 @@
import { createContext, createElement, useContext, type ReactNode } from 'react'
import type { NodeTerminalApi } from '@shared/types'
import { createPresenceSession, type PresenceSession } from '../state/presence'
-
-// Placeholder store-instance type. Task 4 replaces `AgentStatusSession` with the real
-// per-session agent-status store type (`../state/agentStatus`) — that store is not a
-// per-instance factory yet, so importing it here would be wrong. Deliberately not exported:
-// nothing may depend on the placeholder shape.
-// BRANDED on purpose: a bare `object` would accept a real store, so wiring one into
-// `buildStores()` while forgetting to swap the alias would typecheck cleanly and leave the
-// slot typed as a placeholder forever. The unique-symbol brand makes that assignment a compile
-// error at the exact line — replacing the alias is the only way to satisfy the compiler.
-declare const PLACEHOLDER: unique symbol
-/** Task 4 replaces this with the real per-session agent-status store type. */
-type AgentStatusSession = { readonly [PLACEHOLDER]: 'replace in Task 4' }
+import { agentStatusForApi, type AgentStatusSession } from '../state/agentStatus'
export type SessionSource = 'local' | 'relay' | 'server'
@@ -49,11 +38,14 @@ let remoteSeq = 0
* (a loopback debug session, a test double) shares that api's existing store rather than
* racing it for the bridge's first-subscriber replay buffer. A different api (a different
* core, a different peer-id space) gets a fresh instance.
- * Task 4 replaces the agentStatus placeholder with the real default instance. */
+ * `agentStatusForApi` follows the same rule: the local api resolves to the default persisted
+ * instance (the exact object the historical `state/agentStatus` imports use), any other api
+ * gets a keyless in-memory instance — a remote core's per-node status must never clobber the
+ * local user's persisted unread/session under `nodeterm.agentStatus`. */
function buildStores(api: NodeTerminalApi): SessionStores {
return {
presence: createPresenceSession(api),
- agentStatus: {} as AgentStatusSession
+ agentStatus: agentStatusForApi(api)
}
}
diff --git a/src/renderer/state/agentStatus-session.test.ts b/src/renderer/state/agentStatus-session.test.ts
new file mode 100644
index 000000000..9429337f9
--- /dev/null
+++ b/src/renderer/state/agentStatus-session.test.ts
@@ -0,0 +1,125 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import type { NodeTerminalApi } from '@shared/types'
+
+// The store binds localStorage per instance at construction time, so each test stubs a fresh
+// in-memory storage and re-imports the module (vi.resetModules) to exercise the factory.
+function memStorage(seed: Record<string, string> = {}): Storage {
+ const m = new Map(Object.entries(seed))
+ return {
+ getItem: (k) => m.get(k) ?? null,
+ setItem: (k, v) => void m.set(k, v),
+ removeItem: (k) => void m.delete(k),
+ clear: () => m.clear(),
+ key: () => null,
+ get length() {
+ return m.size
+ }
+ } as Storage
+}
+
+beforeEach(() => {
+ vi.resetModules()
+ vi.stubGlobal('localStorage', memStorage())
+})
+afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+})
+
+describe('createAgentStatusSession — per-instance isolation', () => {
+ it('two instances keep independent byId tables', async () => {
+ const { createAgentStatusSession } = await import('./agentStatus')
+ const a = createAgentStatusSession()
+ const b = createAgentStatusSession()
+ a.store.getState().setState('n1', 'working', 'claude')
+ expect(a.store.getState().byId['n1']?.state).toBe('working')
+ expect(b.store.getState().byId['n1']).toBeUndefined()
+ })
+
+ it('a keyless instance never writes to localStorage; a keyed one does', async () => {
+ const { createAgentStatusSession } = await import('./agentStatus')
+ const keyed = createAgentStatusSession('nodeterm.agentStatus.test')
+ const keyless = createAgentStatusSession()
+ keyed.store.getState().markUnread('n1')
+ keyless.store.getState().markUnread('n2')
+ expect(localStorage.getItem('nodeterm.agentStatus.test')).toContain('n1')
+ // keyless left no other key behind:
+ expect(localStorage.getItem('nodeterm.agentStatus')).toBeNull()
+ })
+
+ it('inferInterruptAfterSettle is bound to its own instance', async () => {
+ vi.useFakeTimers()
+ const { createAgentStatusSession } = await import('./agentStatus')
+ const a = createAgentStatusSession()
+ const b = createAgentStatusSession()
+ a.store.getState().setState('n1', 'working', 'claude')
+ b.store.getState().setState('n1', 'working', 'claude')
+ a.inferInterruptAfterSettle('n1', 1000)
+ vi.advanceTimersByTime(1000)
+ expect(a.store.getState().byId['n1'].state).toBe('done')
+ // b's node saw no interrupt — a different core's table is never touched.
+ expect(b.store.getState().byId['n1'].state).toBe('working')
+ })
+})
+
+describe('createAgentStatusSession — persistence stays per-key correct', () => {
+ it('migrates the legacy key into the DEFAULT instance only', async () => {
+ vi.stubGlobal(
+ 'localStorage',
+ memStorage({ 'nodeterm.claudeStatus': JSON.stringify({ n9: { unread: true } }) })
+ )
+ const { useAgentStatus, createAgentStatusSession } = await import('./agentStatus')
+ // The default instance (built at import time under 'nodeterm.agentStatus') migrated…
+ expect(useAgentStatus.getState().byId['n9']).toMatchObject({ unread: true })
+ expect(localStorage.getItem('nodeterm.agentStatus')).toContain('n9')
+ // …but a differently-keyed instance neither migrates nor reads the default key.
+ const other = createAgentStatusSession('nodeterm.agentStatus.other')
+ expect(other.store.getState().byId['n9']).toBeUndefined()
+ expect(localStorage.getItem('nodeterm.agentStatus.other')).toBeNull()
+ })
+
+ it('two keyed instances hydrate from and save to their OWN keys', async () => {
+ vi.stubGlobal(
+ 'localStorage',
+ memStorage({
+ 'k.a': JSON.stringify({ na: { unread: true } }),
+ 'k.b': JSON.stringify({ nb: { unread: true } })
+ })
+ )
+ const { createAgentStatusSession } = await import('./agentStatus')
+ const a = createAgentStatusSession('k.a')
+ const b = createAgentStatusSession('k.b')
+ expect(a.store.getState().byId['na']?.unread).toBe(true)
+ expect(a.store.getState().byId['nb']).toBeUndefined()
+ a.store.getState().markUnread('na2')
+ expect(localStorage.getItem('k.a')).toContain('na2')
+ expect(localStorage.getItem('k.b')).not.toContain('na2')
+ expect(b.store.getState().byId['nb']?.unread).toBe(true)
+ })
+})
+
+describe('agentStatusForApi — one store per core, keyed by api identity', () => {
+ it('memoizes by api object; distinct apis get distinct instances', async () => {
+ const { agentStatusForApi } = await import('./agentStatus')
+ const apiA = { marker: 'a' } as unknown as NodeTerminalApi
+ const apiB = { marker: 'b' } as unknown as NodeTerminalApi
+ expect(agentStatusForApi(apiA)).toBe(agentStatusForApi(apiA))
+ expect(agentStatusForApi(apiA)).not.toBe(agentStatusForApi(apiB))
+ })
+
+ it('a non-local api gets a KEYLESS instance — a remote core never clobbers the local persisted key', async () => {
+ const { agentStatusForApi } = await import('./agentStatus')
+ const remote = agentStatusForApi({ marker: 'remote' } as unknown as NodeTerminalApi)
+ remote.store.getState().markUnread('nt-x')
+ remote.store.getState().setSessionId('nt-x', 'remote-session')
+ expect(localStorage.getItem('nodeterm.agentStatus')).toBeNull()
+ })
+
+ it('window.nodeTerminal resolves to the default (persisted) instance — the WeakMap seed', async () => {
+ const api = { marker: 'preload' } as unknown as NodeTerminalApi
+ vi.stubGlobal('window', { nodeTerminal: api })
+ const mod = await import('./agentStatus')
+ expect(mod.agentStatusForApi(api)).toBe(mod.defaultAgentStatus)
+ expect(mod.defaultAgentStatus.store).toBe(mod.useAgentStatus)
+ })
+})
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index dd6880296..1d1de16d5 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -1,11 +1,32 @@
-import { create } from 'zustand'
+import { create, type StoreApi, type UseBoundStore } from 'zustand'
import type { AgentId } from '@shared/agents/config'
import type { AgentState } from '@shared/agents/normalize'
+import type { NodeTerminalApi } from '@shared/types'
/**
* Transient per-node status for agent (e.g. Claude Code) sessions, driven by the agent's hooks.
* `unread`, `session` and `sessionId` are persisted to localStorage so they survive a
* reload/restart; the live `state` (working/waiting/…) is not (it'd be stale on relaunch).
+ *
+ * ONE STORE PER CORE (stage 4): `createAgentStatusSession(persistKey?)` builds an isolated
+ * instance — node ids are per-core, so status tables from two cores must never mix. The module
+ * keeps a DEFAULT instance for the local core and re-exports its members under the historical
+ * names, so the existing single-session consumers are untouched. The session registry resolves
+ * a store through `agentStatusForApi(api)` — memoized BY API IDENTITY like presence, and seeded
+ * with `window.nodeTerminal → defaultAgentStatus`, so the local session (and any path handed a
+ * repeat api) structurally gets the one existing store, never a parallel twin.
+ *
+ * PERSISTENCE IS PER-KEY, AND ONLY THE DEFAULT HAS ONE. This is deliberately the opposite call
+ * from presence's shared ME_KEY: {name, color} is who the HUMAN is (one per person, shared
+ * across sessions), but agent status is per-NODE state on a SPECIFIC core — a remote core's
+ * unread/sessionId for `nt-x` is not this machine's `nt-x` (tmux persistKeys are unique within
+ * one core only), and `save()` rewrites the WHOLE table, so a remote session sharing
+ * `nodeterm.agentStatus` would clobber the local nodes' persisted unread/session/loop on its
+ * first write. So: the default instance keeps the historical key (bit-for-bit today's
+ * behavior, legacy migration included); a keyless instance persists NOTHING (remote status is
+ * rebuilt from the remote core's hooks on reconnect — a durable per-remote key needs a stable
+ * session identity, which sub-stage 4c owns); the `persistKey` parameter is how 4c opts a
+ * session into its own namespaced key without touching this file.
*/
export interface AgentNodeStatus {
/** Live activity; undefined = idle/unknown. */
@@ -37,7 +58,7 @@ export interface AgentNodeStatus {
}
}
-interface AgentStatusStore {
+export interface AgentStatusStore {
byId: Record<string, AgentNodeStatus>
/** The terminal node the user is currently focused in (for unread decisions). */
activeId: string | null
@@ -63,7 +84,9 @@ interface AgentStatusStore {
}
const EMPTY: AgentNodeStatus = { unread: false }
+/** The DEFAULT (local-core) persistence key. Only the default instance uses it. */
const KEY = 'nodeterm.agentStatus'
+const LEGACY_KEY = 'nodeterm.claudeStatus'
// Claude Code runs hooks in PARALLEL, so the last PostToolUse's POST can arrive after the
// Stop's POST — hold done against any non-newTurn working for this long.
@@ -77,205 +100,272 @@ export const STALE_WORKING_MS = 30 * 60_000
// turn was cancelled without a final Stop.
export const INTERRUPT_SETTLE_MS = 1500
-// One-time localStorage migration from the old key. Runs before the store hydrates.
-const LEGACY_KEY = 'nodeterm.claudeStatus'
-try {
- if (!localStorage.getItem(KEY)) {
- const legacy = localStorage.getItem(LEGACY_KEY)
- if (legacy) localStorage.setItem(KEY, legacy)
+/** One-time localStorage migration from the old key. Runs before the default store hydrates —
+ * and ONLY for the default key: a namespaced or keyless instance must never adopt legacy data
+ * that belongs to the local core. */
+function migrateLegacyKey(): void {
+ try {
+ if (!localStorage.getItem(KEY)) {
+ const legacy = localStorage.getItem(LEGACY_KEY)
+ if (legacy) localStorage.setItem(KEY, legacy)
+ }
+ } catch {
+ /* ignore */
}
-} catch {
- /* ignore */
}
-function load(): Record<string, AgentNodeStatus> {
- try {
- const raw = localStorage.getItem(KEY)
- if (!raw) return {}
- const data = JSON.parse(raw) as Record<string, Partial<AgentNodeStatus>>
- const out: Record<string, AgentNodeStatus> = {}
- for (const [id, v] of Object.entries(data)) {
- out[id] = { unread: !!v.unread, session: v.session, sessionId: v.sessionId }
- // A recurring job (cron/schedule — and tmux keeps in-session loops alive too) outlives
- // the app: restore its card. Minimal shape check so a corrupt entry can't break load.
- if (v.loop && typeof v.loop === 'object' && v.loop.kind) {
- out[id].loop = {
- count: v.loop.count ?? 0,
- kind: v.loop.kind,
- schedule: v.loop.schedule,
- task: v.loop.task,
- items: Array.isArray(v.loop.items) ? v.loop.items : []
+/** One session's agent status: its store plus the interrupt-inference helper bound to it. */
+export interface AgentStatusSession {
+ store: UseBoundStore<StoreApi<AgentStatusStore>>
+ /**
+ * Esc/Ctrl-C interrupt inference: Claude Code fires NO hook when the user
+ * cancels a turn, so a node interrupted mid-work would sit on "working" forever. Called
+ * from the terminal's input path on a lone Esc / Ctrl-C: wait one settle window; if the
+ * node is still `working` and NOT ONE hook event arrived since the keystroke (stateAt
+ * unchanged), conclude the turn was cancelled and flip it to done. A wrong guess
+ * self-corrects: the next real hook event sets working again (it's past the holdoff).
+ */
+ inferInterruptAfterSettle(id: string, settleMs?: number): void
+}
+
+/**
+ * Build the agent-status store for ONE core. `persistKey` is the localStorage key this
+ * instance hydrates from and saves to; `undefined` = in-memory only (load returns nothing,
+ * save is a no-op — the instance never touches localStorage). See the module docblock for
+ * why only the default instance has a key today.
+ */
+export function createAgentStatusSession(persistKey?: string): AgentStatusSession {
+ if (persistKey === KEY) migrateLegacyKey()
+
+ function load(): Record<string, AgentNodeStatus> {
+ if (!persistKey) return {}
+ try {
+ const raw = localStorage.getItem(persistKey)
+ if (!raw) return {}
+ const data = JSON.parse(raw) as Record<string, Partial<AgentNodeStatus>>
+ const out: Record<string, AgentNodeStatus> = {}
+ for (const [id, v] of Object.entries(data)) {
+ out[id] = { unread: !!v.unread, session: v.session, sessionId: v.sessionId }
+ // A recurring job (cron/schedule — and tmux keeps in-session loops alive too) outlives
+ // the app: restore its card. Minimal shape check so a corrupt entry can't break load.
+ if (v.loop && typeof v.loop === 'object' && v.loop.kind) {
+ out[id].loop = {
+ count: v.loop.count ?? 0,
+ kind: v.loop.kind,
+ schedule: v.loop.schedule,
+ task: v.loop.task,
+ items: Array.isArray(v.loop.items) ? v.loop.items : []
+ }
}
}
+ return out
+ } catch {
+ return {}
}
- return out
- } catch {
- return {}
}
-}
-// Persist only the durable fields (not the live `state`).
-function save(byId: Record<string, AgentNodeStatus>): void {
- try {
- const out: Record<string, Partial<AgentNodeStatus>> = {}
- for (const [id, v] of Object.entries(byId)) {
- if (v.unread || v.session || v.sessionId || v.loop) {
- out[id] = { unread: v.unread, session: v.session, sessionId: v.sessionId, loop: v.loop }
+ // Persist only the durable fields (not the live `state`).
+ function save(byId: Record<string, AgentNodeStatus>): void {
+ if (!persistKey) return
+ try {
+ const out: Record<string, Partial<AgentNodeStatus>> = {}
+ for (const [id, v] of Object.entries(byId)) {
+ if (v.unread || v.session || v.sessionId || v.loop) {
+ out[id] = { unread: v.unread, session: v.session, sessionId: v.sessionId, loop: v.loop }
+ }
}
+ localStorage.setItem(persistKey, JSON.stringify(out))
+ } catch {
+ // ignore quota / serialization errors
}
- localStorage.setItem(KEY, JSON.stringify(out))
- } catch {
- // ignore quota / serialization errors
}
-}
-export const useAgentStatus = create<AgentStatusStore>((set) => ({
- byId: load(),
- activeId: null,
+ const store = create<AgentStatusStore>((set) => ({
+ byId: load(),
+ activeId: null,
- setActive: (id, active) =>
- set((s) => {
- if (active) return s.activeId === id ? s : { activeId: id }
- return s.activeId === id ? { activeId: null } : s
- }),
+ setActive: (id, active) =>
+ set((s) => {
+ if (active) return s.activeId === id ? s : { activeId: id }
+ return s.activeId === id ? { activeId: null } : s
+ }),
- setState: (id, state, agentId, newTurn) =>
- set((s) => {
- const prev = s.byId[id] ?? EMPTY
- const now = Date.now()
- // Done-holdoff: a late working event (parallel hook curls arrive out of order, or a
- // tool POST that was in flight when the user interrupted) must not resurrect a turn
- // that just finished. Only a genuine new turn (UserPromptSubmit) may.
- if (
- state === 'working' &&
- !newTurn &&
- prev.state === 'done' &&
- now - (prev.stateAt ?? 0) < DONE_HOLDOFF_MS
- ) {
- return s
- }
- if (prev.state === state && (agentId === undefined || prev.agentId === agentId)) {
- // Same-state event: refresh freshness in place — stateAt is never rendered, and a
- // new object here would re-render every node header on each tool event.
- if (s.byId[id]) s.byId[id].stateAt = now
- return s
- }
- const next = { ...prev, state, stateAt: now }
- if (agentId !== undefined) next.agentId = agentId
- return { byId: { ...s.byId, [id]: next } }
- }),
+ setState: (id, state, agentId, newTurn) =>
+ set((s) => {
+ const prev = s.byId[id] ?? EMPTY
+ const now = Date.now()
+ // Done-holdoff: a late working event (parallel hook curls arrive out of order, or a
+ // tool POST that was in flight when the user interrupted) must not resurrect a turn
+ // that just finished. Only a genuine new turn (UserPromptSubmit) may.
+ if (
+ state === 'working' &&
+ !newTurn &&
+ prev.state === 'done' &&
+ now - (prev.stateAt ?? 0) < DONE_HOLDOFF_MS
+ ) {
+ return s
+ }
+ if (prev.state === state && (agentId === undefined || prev.agentId === agentId)) {
+ // Same-state event: refresh freshness in place — stateAt is never rendered, and a
+ // new object here would re-render every node header on each tool event.
+ if (s.byId[id]) s.byId[id].stateAt = now
+ return s
+ }
+ const next = { ...prev, state, stateAt: now }
+ if (agentId !== undefined) next.agentId = agentId
+ return { byId: { ...s.byId, [id]: next } }
+ }),
- sweepStaleWorking: (staleMs = STALE_WORKING_MS) =>
- set((s) => {
- const now = Date.now()
- let changed = false
- const byId = { ...s.byId }
- for (const [id, v] of Object.entries(byId)) {
- if (v.state === 'working' && now - (v.stateAt ?? 0) > staleMs) {
- byId[id] = { ...v, state: undefined, stateAt: now }
- changed = true
+ sweepStaleWorking: (staleMs = STALE_WORKING_MS) =>
+ set((s) => {
+ const now = Date.now()
+ let changed = false
+ const byId = { ...s.byId }
+ for (const [id, v] of Object.entries(byId)) {
+ if (v.state === 'working' && now - (v.stateAt ?? 0) > staleMs) {
+ byId[id] = { ...v, state: undefined, stateAt: now }
+ changed = true
+ }
}
- }
- return changed ? { byId } : s
- }),
+ return changed ? { byId } : s
+ }),
- setSession: (id, session) =>
- set((s) => {
- const prev = s.byId[id] ?? EMPTY
- if (prev.session === session) return s
- const byId = { ...s.byId, [id]: { ...prev, session } }
- save(byId)
- return { byId }
- }),
+ setSession: (id, session) =>
+ set((s) => {
+ const prev = s.byId[id] ?? EMPTY
+ if (prev.session === session) return s
+ const byId = { ...s.byId, [id]: { ...prev, session } }
+ save(byId)
+ return { byId }
+ }),
- setSessionId: (id, sessionId) =>
- set((s) => {
- const prev = s.byId[id] ?? EMPTY
- if (prev.sessionId === sessionId) return s
- const byId = { ...s.byId, [id]: { ...prev, sessionId } }
- save(byId)
- return { byId }
- }),
+ setSessionId: (id, sessionId) =>
+ set((s) => {
+ const prev = s.byId[id] ?? EMPTY
+ if (prev.sessionId === sessionId) return s
+ const byId = { ...s.byId, [id]: { ...prev, sessionId } }
+ save(byId)
+ return { byId }
+ }),
- markUnread: (id) =>
- set((s) => {
- const prev = s.byId[id] ?? EMPTY
- if (prev.unread) return s
- const byId = { ...s.byId, [id]: { ...prev, unread: true } }
- save(byId)
- return { byId }
- }),
+ markUnread: (id) =>
+ set((s) => {
+ const prev = s.byId[id] ?? EMPTY
+ if (prev.unread) return s
+ const byId = { ...s.byId, [id]: { ...prev, unread: true } }
+ save(byId)
+ return { byId }
+ }),
- clearUnread: (id) =>
- set((s) => {
- const prev = s.byId[id]
- if (!prev?.unread) return s
- const byId = { ...s.byId, [id]: { ...prev, unread: false } }
- save(byId)
- return { byId }
- }),
+ clearUnread: (id) =>
+ set((s) => {
+ const prev = s.byId[id]
+ if (!prev?.unread) return s
+ const byId = { ...s.byId, [id]: { ...prev, unread: false } }
+ save(byId)
+ return { byId }
+ }),
+
+ setLoop: (id, active, kind = 'loop', opts) =>
+ set((s) => {
+ const prev = s.byId[id] ?? EMPTY
+ if (active) {
+ const byId = {
+ ...s.byId,
+ [id]: {
+ ...prev,
+ loop: { count: 0, kind, schedule: opts?.schedule, task: opts?.task, items: [] }
+ }
+ }
+ save(byId)
+ return { byId }
+ }
+ if (!prev.loop) return s
+ const { loop: _drop, ...rest } = prev
+ const byId = { ...s.byId, [id]: rest }
+ save(byId)
+ return { byId }
+ }),
- setLoop: (id, active, kind = 'loop', opts) =>
- set((s) => {
- const prev = s.byId[id] ?? EMPTY
- if (active) {
+ bumpLoop: (id, message) =>
+ set((s) => {
+ const prev = s.byId[id]
+ // Only count in-session /loop turns; /schedule and /cron run in the background.
+ if (!prev?.loop || prev.loop.kind !== 'loop') return s
+ const items = message
+ ? [...prev.loop.items, message.trim().slice(0, 4000)].slice(-100)
+ : prev.loop.items
const byId = {
...s.byId,
- [id]: { ...prev, loop: { count: 0, kind, schedule: opts?.schedule, task: opts?.task, items: [] } }
+ [id]: { ...prev, loop: { ...prev.loop, count: prev.loop.count + 1, items } }
}
save(byId)
return { byId }
- }
- if (!prev.loop) return s
- const { loop: _drop, ...rest } = prev
- const byId = { ...s.byId, [id]: rest }
- save(byId)
- return { byId }
- }),
+ }),
- bumpLoop: (id, message) =>
- set((s) => {
- const prev = s.byId[id]
- // Only count in-session /loop turns; /schedule and /cron run in the background.
- if (!prev?.loop || prev.loop.kind !== 'loop') return s
- const items = message
- ? [...prev.loop.items, message.trim().slice(0, 4000)].slice(-100)
- : prev.loop.items
- const byId = {
- ...s.byId,
- [id]: { ...prev, loop: { ...prev.loop, count: prev.loop.count + 1, items } }
+ remove: (id) =>
+ set((s) => {
+ if (!(id in s.byId)) return s
+ const byId = { ...s.byId }
+ delete byId[id]
+ save(byId)
+ return { byId }
+ })
+ }))
+
+ function inferInterruptAfterSettle(id: string, settleMs = INTERRUPT_SETTLE_MS): void {
+ const st = store.getState().byId[id]
+ if (st?.state !== 'working') return
+ const baseline = st.stateAt
+ setTimeout(() => {
+ const cur = store.getState()
+ const now = cur.byId[id]
+ if (now?.state === 'working' && now.stateAt === baseline) {
+ cur.setState(id, 'done', now.agentId)
}
- save(byId)
- return { byId }
- }),
+ }, settleMs)
+ }
+
+ return { store, inferInterruptAfterSettle }
+}
- remove: (id) =>
- set((s) => {
- if (!(id in s.byId)) return s
- const byId = { ...s.byId }
- delete byId[id]
- save(byId)
- return { byId }
- })
-}))
+/** One instance per api OBJECT — the one-store-per-core guarantee, keyed on identity exactly
+ * like presence's (a WeakMap, so a dropped api never pins its store). Seeded below with
+ * `window.nodeTerminal → defaultAgentStatus`. */
+const instanceByApi = new WeakMap<NodeTerminalApi, AgentStatusSession>()
/**
- * Esc/Ctrl-C interrupt inference: Claude Code fires NO hook when the user
- * cancels a turn, so a node interrupted mid-work would sit on "working" forever. Called
- * from the terminal's input path on a lone Esc / Ctrl-C: wait one settle window; if the
- * node is still `working` and NOT ONE hook event arrived since the keystroke (stateAt
- * unchanged), conclude the turn was cancelled and flip it to done. A wrong guess
- * self-corrects: the next real hook event sets working again (it's past the holdoff).
+ * The agent-status store for ONE core (one api). MEMOIZED BY API IDENTITY: the session
+ * registry resolves its store here, so ANY session handed the local api — the local session
+ * itself, a loopback debug session, a test double — shares the default (persisted) instance
+ * rather than growing a parallel table the canvas listener isn't driving. A DIFFERENT api (a
+ * different core, a different node-id space) gets a fresh KEYLESS instance: a remote core's
+ * status must never clobber the local user's persisted unread/session under `KEY` (see the
+ * module docblock). A nullish api (node-environment tests) is not memoizable and gets a
+ * fresh inert instance.
*/
-export function inferInterruptAfterSettle(id: string, settleMs = INTERRUPT_SETTLE_MS): void {
- const st = useAgentStatus.getState().byId[id]
- if (st?.state !== 'working') return
- const baseline = st.stateAt
- setTimeout(() => {
- const cur = useAgentStatus.getState()
- const now = cur.byId[id]
- if (now?.state === 'working' && now.stateAt === baseline) {
- cur.setState(id, 'done', now.agentId)
- }
- }, settleMs)
+export function agentStatusForApi(api: NodeTerminalApi): AgentStatusSession {
+ const existing = api ? instanceByApi.get(api) : undefined
+ if (existing) return existing
+ const session = createAgentStatusSession() // keyless — remote status is never persisted (4a)
+ if (api) instanceByApi.set(api, session)
+ return session
+}
+
+/**
+ * The DEFAULT instance — the local core's agent status, persisted under the historical key
+ * (with the one-time legacy-key migration). Every historical export below resolves to this
+ * exact object, so the existing single-session consumers are untouched. Seeding the WeakMap
+ * with `window.nodeTerminal` (safe at module load for the boot-order reason documented in
+ * localSession.ts; the `typeof window` guard covers node-environment tests) is what makes
+ * `agentStatusForApi(window.nodeTerminal)` — the session registry's local session — resolve
+ * here, never to a parallel twin.
+ */
+const defaultAgentStatus = createAgentStatusSession(KEY)
+export { defaultAgentStatus }
+if (typeof window !== 'undefined' && window.nodeTerminal) {
+ instanceByApi.set(window.nodeTerminal as NodeTerminalApi, defaultAgentStatus)
}
+
+export const useAgentStatus = defaultAgentStatus.store
+export const inferInterruptAfterSettle = defaultAgentStatus.inferInterruptAfterSettle