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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(relay): a snapshot working keeps its freshness clock so the stale sweep spares it
reviewae1ed72532d1
diff --git a/src/core/agent-status-snapshot.test.ts b/src/core/agent-status-snapshot.test.tsindex 3979882af..2e70c8115 100644--- a/src/core/agent-status-snapshot.test.ts+++ b/src/core/agent-status-snapshot.test.ts@@ -1,6 +1,6 @@// `agent:status-snapshot` — what a relay tab that joins late reads to start from the host's states// (bug D). Built from the agent-status mirror, registered by both shells.-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { AGENT_STATUS_SNAPSHOT_MAX } from '../shared/agent-status-snapshot'import { IPC } from '../shared/ipc'import type { CorePlatform } from './platform'@@ -15,18 +15,24 @@ const ENTRIES: Array<[string, MirrorEntry]> = [['restored', { state: 'done', agentId: 'claude', sessionId: 's-restored', updatedAt: 100, restored: true, stateVerified: false }]]+/** This host's clock for the pure builds below. */+const NOW = 1000+const entry = (nodeId: string) => {- const e = buildAgentStatusSnapshot(ENTRIES).find((x) => x.nodeId === nodeId)+ const e = buildAgentStatusSnapshot(ENTRIES, NOW).find((x) => x.nodeId === nodeId)if (!e) throw new Error(`no snapshot entry for ${nodeId}`)return e}-afterEach(() => _resetForTest())+afterEach(() => {+ vi.useRealTimers()+ _resetForTest()+})describe('buildAgentStatusSnapshot', () => {it('maps mirror entries to snapshot entries', () => {- // Only the five fields a joiner's store takes travel: no proof, no clock, no inbox ticket.- expect(entry('live')).toEqual({ nodeId: 'live', state: 'working', agentId: 'claude', sessionId: 's-live', account })+ // Only the fields a joiner's store takes travel: no proof, no host clock, no inbox ticket.+ expect(entry('live')).toEqual({ nodeId: 'live', state: 'working', agentId: 'claude', sessionId: 's-live', account, ageMs: 700 })})it('omits state for identity-only and restored entries', () => {@@ -36,6 +42,25 @@ describe('buildAgentStatusSnapshot', () => {expect(entry('expired').agentId).toBe('codex')expect(entry('restored').sessionId).toBe('s-restored')expect('state' in entry('restored')).toBe(false)+ // No state, so no age of one.+ expect(entry('expired').ageMs).toBeUndefined()+ expect(entry('restored').ageMs).toBeUndefined()+ })++ it("an entry's ageMs is the host-side age of its updatedAt, never below 0", () => {+ const out = buildAgentStatusSnapshot(+ [+ ['old', { state: 'working', updatedAt: 400 }],+ ['now', { state: 'done', updatedAt: 1000 }],+ // Stamped after `now` (this host's clock stepped back since): an age, never a negative one.+ ['ahead', { state: 'blocked', updatedAt: 1500 }]+ ],+ NOW+ )+ const age = (id: string) => out.find((e) => e.nodeId === id)?.ageMs+ expect(age('old')).toBe(600)+ expect(age('now')).toBe(0)+ expect(age('ahead')).toBe(0)})it('keeps the newest AGENT_STATUS_SNAPSHOT_MAX entries by updatedAt', () => {@@ -53,14 +78,17 @@ describe('buildAgentStatusSnapshot', () => {})it('registers agent:status-snapshot on the platform', async () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-11-01T10:00:00Z'))const handlers = new Map<string, (...args: unknown[]) => unknown>()const platform = { handle: (ch: string, fn: (...args: unknown[]) => unknown) => void handlers.set(ch, fn) } as unknown as CorePlatformregisterAgentStatusSnapshotIpc(platform)expect([...handlers.keys()]).toEqual([IPC.agentStatusSnapshot])// The default read is the REAL mirror, as each shell's hook events left it.recordAgentEvent({ nodeId: 'term-a', agentId: 'claude', kind: 'state', state: 'working', sessionId: 's1', newTurn: true })+ vi.setSystemTime(Date.now() + 1234)expect(await handlers.get(IPC.agentStatusSnapshot)!()).toEqual([- { nodeId: 'term-a', state: 'working', agentId: 'claude', sessionId: 's1' }+ { nodeId: 'term-a', state: 'working', agentId: 'claude', sessionId: 's1', ageMs: 1234 }])// An injected read replaces it.registerAgentStatusSnapshotIpc(platform, () => [{ nodeId: 'x' }])diff --git a/src/core/agent-status-snapshot.ts b/src/core/agent-status-snapshot.tsindex 4309c8195..f0fd1b109 100644--- a/src/core/agent-status-snapshot.ts+++ b/src/core/agent-status-snapshot.ts@@ -8,20 +8,28 @@ import type { CorePlatform } from './platform'/*** The snapshot of `entries`: the newest `AGENT_STATUS_SNAPSHOT_MAX` by `updatedAt`, each reduced to- * the fields a joiner's store takes. Pure.+ * the fields a joiner's store takes. Pure; `now` is this host's clock.** `state` is left out for an identity-only entry (`stateExpired`) and for one restored from disk* (`restored`): neither is an observation made this run, and a joiner shown a 6-hour-old `working`* would read it as live. Their identity (agent, session, account) still travels — that is what lets* the joiner's chat view and account chip find the node's session.+ *+ * An entry with a `state` also carries `ageMs`, how long ago this host last asserted it (never+ * below 0, so a clock that stepped back never yields a negative age). It is an age, not a time, so+ * the host's clock never reaches the joiner.*/export function buildAgentStatusSnapshot(- entries: Iterable<readonly [string, Readonly<MirrorEntry>]>+ entries: Iterable<readonly [string, Readonly<MirrorEntry>]>,+ now: number = Date.now()): AgentStatusSnapshotEntry[] {const sorted = [...entries].sort((a, b) => b[1].updatedAt - a[1].updatedAt).slice(0, AGENT_STATUS_SNAPSHOT_MAX)return sorted.map(([nodeId, e]) => {const out: AgentStatusSnapshotEntry = { nodeId }- if (e.state !== undefined && !e.stateExpired && !e.restored) out.state = e.state+ if (e.state !== undefined && !e.stateExpired && !e.restored) {+ out.state = e.state+ out.ageMs = Math.max(0, now - e.updatedAt)+ }if (e.agentId !== undefined) out.agentId = e.agentIdif (e.sessionId !== undefined) out.sessionId = e.sessionIdif (e.account !== undefined) out.account = e.accountdiff --git a/src/renderer/session/relay-agent-status.test.ts b/src/renderer/session/relay-agent-status.test.tsindex ae45a6bba..f303e8a4e 100644--- a/src/renderer/session/relay-agent-status.test.ts+++ b/src/renderer/session/relay-agent-status.test.ts@@ -252,23 +252,49 @@ describe('wireRelayAgentStatus — the snapshot a late joiner starts from', () =const doneFor = (nodeId: string): NormalizedAgentEvent => ev({ nodeId, state: 'done', lastMessage: 'ok' })it('asks for the snapshot after subscribing, and applies it', async () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-11-01T10:00:00Z'))const { api, order, resolve } = fakeApi()const stop = wireRelayAgentStatus(api, status, { hasFocus: () => false })expect(order).toEqual(['subscribe', 'snapshot'])- resolve([{ nodeId: 'a', state: 'working', agentId: 'claude', sessionId: 's' }])+ resolve([{ nodeId: 'a', state: 'working', agentId: 'claude', sessionId: 's', ageMs: 5000 }])await flush()const byId = byIdOf()expect(byId.a.state).toBe('working')expect(byId.a.agentId).toBe('claude')expect(byId.a.sessionId).toBe('s')- // No clock: the joiner saw no transition, and a stamped one would claim it did.+ // The freshness clock is the host's age on this machine's clock; the transition clocks stay+ // unset: the joiner saw no transition, and a stamped one would claim it did.+ expect(byId.a.stateAt).toBe(Date.now() - 5000)expect(byId.a.lastEventAt).toBeUndefined()- expect(byId.a.stateAt).toBeUndefined()expect(byId.a.lastSeen).toBeUndefined()expect(byId.a.unread).toBe(false)stop()})+ it('a snapshot working survives the stale-working sweep', async () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-11-01T10:00:00Z'))+ const { api, resolve } = fakeApi()+ const stop = wireRelayAgentStatus(api, status, { hasFocus: () => false, sweepMs: 1000 })+ resolve([+ { nodeId: 'a', state: 'working', ageMs: 2000 },+ // The host has held this one quiet for longer than the window: the same decay a live event+ // that old would get.+ { nodeId: 'b', state: 'working', ageMs: STALE_WORKING_MS + 1 },+ // An age below zero is no age: the clock is never put ahead of this machine's.+ { nodeId: 'c', state: 'working', ageMs: -60_000 }+ ])+ await flush()+ const t0 = Date.now()+ expect(byIdOf().c.stateAt).toBe(t0)+ vi.advanceTimersByTime(1000)+ expect(byIdOf().a.state).toBe('working')+ expect(byIdOf().c.state).toBe('working')+ expect(byIdOf().b.state).toBeUndefined()+ stop()+ })+it('a live event that lands before the snapshot is not overwritten by it', async () => {const { api, fire, resolve } = fakeApi()const stop = wireRelayAgentStatus(api, status, { hasFocus: () => false })@@ -301,6 +327,7 @@ describe('wireRelayAgentStatus — the snapshot a late joiner starts from', () =const a = byIdOf().aexpect(a.state).toBeUndefined()expect('state' in a).toBe(false)+ expect(a.stateAt).toBeUndefined() // no state, so no freshness clock for oneexpect(a.sessionId).toBe('s-old')expect(a.agentId).toBe('claude')// The host's account label is another machine's, exactly as a live relay event records it.diff --git a/src/renderer/session/relay-agent-status.ts b/src/renderer/session/relay-agent-status.tsindex 9162a7fb0..086b5a84a 100644--- a/src/renderer/session/relay-agent-status.ts+++ b/src/renderer/session/relay-agent-status.ts@@ -38,19 +38,31 @@ export interface RelayAgentStatusDeps {}/**- * Write the entries no live event has touched; never stamps a clock. Returns how many it wrote.+ * Write the entries no live event has touched; never stamps a TRANSITION clock. Returns how many it+ * wrote. `now` is this machine's clock.** One `setState` for the whole snapshot. Each entry merges only the fields it carries (`state`,* `agentId`, `sessionId`, `account`) onto whatever the node already has, so an identity-only entry- * (no `state`) leaves the state alone and `unread` is kept (default `false`). `lastEventAt`,- * `stateAt` and `lastSeen` are NEVER set: the joiner saw no transition, a fabricated clock would- * claim one, and the sidebar sorts a missing clock last. The account is recorded as another- * machine's (`remote: true`), exactly as the live relay events record it.+ * (no `state`) leaves the state alone and `unread` is kept (default `false`). The account is+ * recorded as another machine's (`remote: true`), exactly as the live relay events record it.+ *+ * The clocks, which are not alike:+ * • `stateAt` (freshness: when the state was last ASSERTED, which the stale-working sweep reads) is+ * set for an entry that carries a `state`, to `now - ageMs`. The age is the host's measurement of+ * its own mirror entry, so no host clock value is involved, and a negative or missing age counts+ * as 0, never as a time ahead of this one. Without it the sweep reads a missing `stateAt` as 0+ * and decays a served `working` on its first tick, although the host still holds it live (its+ * mirror expires stale states itself).+ * • `lastEventAt` (the transition clock, the sidebar's sort key and the Eco idle clock) and+ * `lastSeen` (the persisted last-hook record) are NEVER set: the joiner saw no transition, and a+ * fabricated one would claim it did. The sidebar sorts a missing clock last.+ * An entry without a `state` sets no `stateAt`: it describes no state to be fresh about.*/export function applyAgentStatusSnapshot(status: Pick<StoreApi<AgentStatusStore>, 'getState' | 'setState'>,entries: readonly AgentStatusSnapshotEntry[],- liveSeen: ReadonlySet<string>+ liveSeen: ReadonlySet<string>,+ now: number = Date.now()): number {if (!Array.isArray(entries)) return 0const prev = status.getState().byId@@ -62,7 +74,11 @@ export function applyAgentStatusSnapshot(if (typeof nodeId !== 'string' || !nodeId || liveSeen.has(nodeId)) continueconst existing = writes.get(nodeId) ?? (Object.hasOwn(prev, nodeId) ? prev[nodeId] : undefined)const merged: AgentNodeStatus = { ...existing, unread: existing?.unread ?? false }- if (entry.state !== undefined) merged.state = entry.state+ if (entry.state !== undefined) {+ merged.state = entry.state+ const age = entry.ageMs+ merged.stateAt = now - (typeof age === 'number' && Number.isFinite(age) && age > 0 ? age : 0)+ }if (entry.agentId !== undefined) merged.agentId = entry.agentIdif (entry.sessionId !== undefined) merged.sessionId = entry.sessionIdif (entry.account !== undefined) merged.account = { ...entry.account, remote: true }diff --git a/src/shared/agent-status-snapshot.ts b/src/shared/agent-status-snapshot.tsindex f22d8e603..7e67ca820 100644--- a/src/shared/agent-status-snapshot.ts+++ b/src/shared/agent-status-snapshot.ts@@ -19,6 +19,13 @@ export interface AgentStatusSnapshotEntry {agentId?: AgentIdsessionId?: stringaccount?: ObservedClaudeAccount+ /**+ * How long ago, in ms, the host last asserted `state` (host `Date.now() - updatedAt`, never below+ * 0). Present only with a `state`. An AGE rather than a timestamp, so no host clock value crosses+ * the wire and the two machines' clock skew never enters: the joiner subtracts it from its own+ * clock to get the freshness clock (`stateAt`) its stale-working sweep reads.+ */+ ageMs?: number}/** At most this many entries, the newest by the mirror's `updatedAt`. */diff --git a/test/acceptance/hosted-relay-agent-status.test.ts b/test/acceptance/hosted-relay-agent-status.test.tsindex 82ce9ae8f..477a02548 100644--- a/test/acceptance/hosted-relay-agent-status.test.ts+++ b/test/acceptance/hosted-relay-agent-status.test.ts@@ -392,9 +392,11 @@ describe('hosted team tab: agent status reaches the relay session', () => {expect(a?.agentId).toBe('claude')expect(a?.sessionId).toBe('s1')expect(a?.unread).toBe(false)- // The joiner saw no transition: no clock is claimed for one.+ // The freshness clock comes from the host's age of the entry; the joiner saw no transition, so+ // no transition clock is claimed.+ expect(typeof a?.stateAt).toBe('number')expect(a?.lastEventAt).toBeUndefined()- expect(a?.stateAt).toBeUndefined()+ expect(a?.lastSeen).toBeUndefined()// A viewer's snapshot holds the shared nodes only.expect(relayStore(late.tab).getState().byId[PRIVATE_NODE]).toBeUndefined()})