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(status): clock on its own key with a real trailing debounce; drop "restored" on the first event

review6497e58133fd
diff --git a/CLAUDE.md b/CLAUDE.md
index ff2ce1b59..603399b18 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2907,29 +2907,43 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
**The clock survives an app restart as "last seen", never as a state** (`agentStatus.lastSeen`,
`{at, state}`). `lastEventAt`/`stateAt`/`state` are transient, so before this every row after a
restart sorted as "no clock" and lost its age. `lastSeen` is the time of the LAST hook event (a
- same-state one included) and the state it asserted, persisted in the SAME localStorage record as
- `unread`/`sessionId` — chosen over the core mirror because the sidebar already reads this store,
+ same-state one included) and the state it asserted, persisted beside the agentStatus record under
+ its OWN small key (`nodeterm.agentStatus.lastSeen`) — chosen over the core mirror because the
+ sidebar already reads this store,
the mirror expires state after 6 h and identity later, and reading it would need a new IPC leg for
a display fact. Rules a refactor must not undo:
- **Restored as a clock only.** Load fills `lastSeen` and nothing else: `state` stays unknown (the
hook server was down with the app, so a turn may have started or ended in between), and
- `lastEventAt` stays unset. The row reads `lastEventAt ?? lastSeen.at`, marks itself
- `statusClockRestored` only while `lastEventAt` is unset, and the label says `seen 3h ago` with a
- tooltip naming the state it was last seen in and that the current state is unknown. The first
- live hook event replaces it with the ordinary in-run clock.
+ `lastEventAt` stays unset. Load marks the clock `restored` (transient, never written); the row
+ reads `lastEventAt ?? lastSeen.at` and its `statusClock` is `transition` / `seen` (a hook event
+ this run but no transition yet) / `restored`. Only `restored` says "before nodeterm restarted"
+ (`seen 3h ago`, tooltip naming the state it was last seen in). **The first event after a restart
+ is usually a SAME-state one** (a cold-restore `--resume` fires SessionStart = `state: undefined`
+ on an entry whose state is already unknown), so the store's in-place fast path must not take it:
+ it replaces the entry (the row loses `restored` and re-sorts at once) without stamping
+ `lastEventAt` (an unknown state is not an idle clock).
- **Eco never reads it** (so `idleKnown` and `planHibernation` are unchanged). Even a proven-idle
prompt after boot would not be enough: the background-task stamp and the subagent cards Eco
also needs are transient and cannot be rebuilt after a restart, and `/exit` kills both
silently. A session becomes a candidate again from its next live `done`.
- - **Bounded and cheap.** Same-state events update it in place (no re-render) and save on a 2 s
- trailing debounce plus `pagehide`, never per tool event. At most `LAST_SEEN_MAX` (1000) newest
- clocks are written, a clock older than 90 days or more than 5 min in the future is refused on
- load (hand-editable input — a future stamp would pin a row to the top), an unknown `state` keeps
- the time and drops the state. Measured: ~47 bytes per clock, 1000 entries 188 KB vs 141 KB and
- 1.6 ms vs 0.9 ms per `JSON.stringify` on this dev host.
- - **It cannot create a row**: rows come from canvas nodes, never from the status table, and
- `remove(id)` (every node-deletion path) drops the clock with the entry, a pending debounced save
- included. Tests: `state/agentStatus.lastSeen.test.ts`.
+ - **Its own key, so the main table's write cadence is unchanged.** State events still write
+ nothing to `nodeterm.agentStatus`. That matters twice: the main table carries `loop.items` (up to
+ 100 × 4000 chars per loop node — 428 KB and ~2.1 ms per stringify with one full loop, measured in
+ review), and on the Server Edition every tab rewrites its whole in-memory table, so a periodic
+ rewrite would let tab B undo tab A's `clearUnread`/`hibernated` within seconds. A first version
+ stored the clock inside that table on a 2 s THROTTLE and rewrote it every 2 s while any agent
+ worked. The clock key is saved on a real TRAILING debounce (5 s quiet, `LAST_SEEN_SAVE_MAX_WAIT_MS`
+ 30 s at most while never quiet) plus `pagehide`: 2 Hz hook events for 10 s = ONE write. Measured:
+ ~59 bytes per clock, 1000 clocks = 59 KB and 0.7 ms per `JSON.stringify` on this dev host. Two
+ Server Edition tabs still race on the CLOCK key (last writer wins), which costs only display.
+ - **Bounded.** At most `LAST_SEEN_MAX` (1000) newest clocks are written; a clock older than 90 days
+ or more than 5 min in the future is refused on load (hand-editable input — a future stamp would
+ pin a row to the top); an unknown `state` keeps the time and drops the state; an unreadable clock
+ key costs the clocks, never the table.
+ - **It cannot create a row**: rows come from canvas nodes, never from the status table.
+ `remove(id)` writes the clock key at once, a pending debounced save included; a deletion path
+ that bypasses `remove` (e.g. `reloadActiveProject` dropping nodes) leaves a clock that simply
+ ages out. Tests: `state/agentStatus.lastSeen.test.ts`.
- Surfaces: Desktop full; Server Edition per browser profile (localStorage, like `unread`); relay
tabs keep a keyless store and persist nothing; kanban has no clock-ordered view, so nothing to
wire there; Mobile N/A (its own state).
diff --git a/src/renderer/components/SessionRow.tsx b/src/renderer/components/SessionRow.tsx
index 3ddbb6c23..898fecd2b 100644
--- a/src/renderer/components/SessionRow.tsx
+++ b/src/renderer/components/SessionRow.tsx
@@ -203,8 +203,8 @@ export function SessionRow({
{row.cwd && <span className="ss-meta__cwd">{dirName(row.cwd)}</span>}
{stateAgeLabel && (
<span
- className={`ss-meta__state-age${row.statusClockRestored ? ' ss-meta__state-age--restored' : ''}`}
- title={sessionStateAgeTitle(stateAgeLabel, !!row.statusClockRestored, row.lastSeenState)}
+ className={`ss-meta__state-age${row.statusClock === 'restored' ? ' ss-meta__state-age--restored' : ''}`}
+ title={sessionStateAgeTitle(stateAgeLabel, row.statusClock, row.lastSeenState)}
>
{stateAgeLabel}
</span>
diff --git a/src/renderer/components/SessionsSidebar.tsx b/src/renderer/components/SessionsSidebar.tsx
index f541edac7..ecad5f84e 100644
--- a/src/renderer/components/SessionsSidebar.tsx
+++ b/src/renderer/components/SessionsSidebar.tsx
@@ -442,7 +442,7 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
onContextMenu={(e) => props.onRowContextMenu(e, row.projectId!, row.id)}
onDragStart={() => {}}
onDragEnd={() => {}}
- stateAgeLabel={sessionStateAgeLabel(row.statusUpdatedAt, statusNow, row.statusClockRestored)}
+ stateAgeLabel={sessionStateAgeLabel(row.statusUpdatedAt, statusNow, row.statusClock)}
/>
</div>
)
diff --git a/src/renderer/lib/sessionList.ts b/src/renderer/lib/sessionList.ts
index 277058cc3..97960b05b 100644
--- a/src/renderer/lib/sessionList.ts
+++ b/src/renderer/lib/sessionList.ts
@@ -211,26 +211,37 @@ export function sessionStatusKind(state: AgentNodeStatus['state']): StatusKind {
}
/** Human-readable age of the current state. No timestamp means genuinely unknown, not "just now". */
+/**
+ * Which clock a row's age comes from:
+ * - `transition` — `lastEventAt`, when the current live state began (this run);
+ * - `seen` — `lastSeen`, the last hook event of THIS run for a node with no state transition yet
+ * (e.g. only a SessionStart since the restart);
+ * - `restored` — `lastSeen` off disk, from before the app restarted.
+ */
+export type StatusClockKind = 'transition' | 'seen' | 'restored'
+
export function sessionStateAgeLabel(
updatedAt: number | undefined,
nowMs: number,
- restored = false
+ clock: StatusClockKind = 'transition'
): string | undefined {
if (updatedAt === undefined) return undefined
- // A restored clock is the LAST HOOK EVENT from before the restart, not the start of a live state
- // (there is no live state yet) — so it must not read like the in-run "entered this state" age.
- return restored ? `seen ${relativeTime(updatedAt, nowMs)}` : relativeTime(updatedAt, nowMs)
+ // A "last seen" clock is the time of a hook event, not the start of a live state (there is no
+ // live state yet) — so it must not read like the in-run "entered this state" age.
+ return clock === 'transition' ? relativeTime(updatedAt, nowMs) : `seen ${relativeTime(updatedAt, nowMs)}`
}
-/** The age label's tooltip, restored or live. Pure, so the wording is pinned beside the label. */
+/** The age label's tooltip. Pure, so the wording is pinned beside the label. */
export function sessionStateAgeTitle(
label: string,
- restored: boolean,
+ clock: StatusClockKind = 'transition',
lastSeenState?: AgentState
): string {
- if (!restored) return `Entered this state ${label}`
+ if (clock === 'transition') return `Entered this state ${label}`
+ const when = label.replace(/^seen /, '')
+ if (clock === 'seen') return `Last hook event ${when}. The current state is unknown until the agent reports one.`
const what = lastSeenState ? ` (${STATE_LABEL[sessionStatusKind(lastSeenState)]})` : ''
- return `Last hook event ${label.replace(/^seen /, '')}${what}, before nodeterm restarted. The current state is unknown until the agent reports again.`
+ return `Last hook event ${when}${what}, before nodeterm restarted. The current state is unknown until the agent reports again.`
}
/**
@@ -259,9 +270,9 @@ export interface SessionRowVM {
* key within a section, and the age label. Absent when neither is known.
*/
statusUpdatedAt?: number
- /** `statusUpdatedAt` came from the persisted "last seen" clock, not from this run. */
- statusClockRestored?: boolean
- /** The state that restored clock was for (display only — never the row's live state). */
+ /** Which clock `statusUpdatedAt` is (see `StatusClockKind`); absent when there is none. */
+ statusClock?: StatusClockKind
+ /** The state a RESTORED clock was for (display only — never the row's live state). */
lastSeenState?: AgentState
unread: boolean
session?: string
@@ -318,6 +329,16 @@ export interface SessionGroup {
ungrouped: SessionRowVM[]
}
+function statusClockOf(
+ status: AgentNodeStatus | undefined
+): Pick<SessionRowVM, 'statusClock' | 'lastSeenState'> {
+ if (status?.lastEventAt !== undefined) return { statusClock: 'transition' }
+ const seen = status?.lastSeen
+ if (!seen) return {}
+ // `restored` is set only on load and dropped by the first hook event of this run.
+ return seen.restored ? { statusClock: 'restored', lastSeenState: seen.state } : { statusClock: 'seen' }
+}
+
function toRow(
n: SessionNodeInput,
status: AgentNodeStatus | undefined,
@@ -335,11 +356,9 @@ function toRow(
isAgent: !!n.agentId,
statusKind,
stateLabel: STATE_LABEL[statusKind],
- // Live clock first; the persisted one only while this run has seen nothing for the node.
+ // Transition clock first; the "last seen" one only while this run has seen no transition.
statusUpdatedAt: status?.lastEventAt ?? status?.lastSeen?.at,
- ...(status?.lastEventAt === undefined && status?.lastSeen
- ? { statusClockRestored: true, lastSeenState: status.lastSeen.state }
- : {}),
+ ...statusClockOf(status),
unread: !!status?.unread,
session: status?.session,
// A dismissed cron/schedule entry is retained as a fact (the hibernation guard reads it) but
diff --git a/src/renderer/state/agentStatus.lastSeen.test.ts b/src/renderer/state/agentStatus.lastSeen.test.ts
index 1f539af8e..76d8ad574 100644
--- a/src/renderer/state/agentStatus.lastSeen.test.ts
+++ b/src/renderer/state/agentStatus.lastSeen.test.ts
@@ -5,12 +5,12 @@ import { shouldDeferReleaseForEco } from '../terminal/offscreen-policy'
import { buildStatusList } from '../lib/sessionList'
// The persisted "last seen" clock (`AgentNodeStatus.lastSeen`): restored across an app restart as a
-// CLOCK that orders and ages sidebar rows — never as a live state, never as Eco's idle clock.
+// CLOCK that orders and ages sidebar rows — never as a live state, never as Eco's idle clock. It
+// lives under its OWN key so a hook event never rewrites the main status table.
-function memStorage(seed: Record<string, string> = {}): Storage & { map: Map<string, string> } {
+function memStorage(seed: Record<string, string> = {}): Storage {
const m = new Map(Object.entries(seed))
return {
- map: m,
getItem: (k: string) => m.get(k) ?? null,
setItem: (k: string, v: string) => void m.set(k, v),
removeItem: (k: string) => void m.delete(k),
@@ -19,12 +19,17 @@ function memStorage(seed: Record<string, string> = {}): Storage & { map: Map<str
get length() {
return m.size
}
- } as Storage & { map: Map<string, string> }
+ } as Storage
}
const KEY = 'nodeterm.agentStatus'
+const CLOCK_KEY = 'nodeterm.agentStatus.lastSeen'
const HOUR = 3600_000
+function seeded(main: Record<string, unknown>, clocks: Record<string, unknown>): Storage {
+ return memStorage({ [KEY]: JSON.stringify(main), [CLOCK_KEY]: JSON.stringify(clocks) })
+}
+
beforeEach(() => vi.resetModules())
afterEach(() => {
vi.useRealTimers()
@@ -39,57 +44,75 @@ async function boot(storage: Storage): Promise<typeof import('./agentStatus')> {
}
describe('lastSeen survives a restart as a clock, not a state', () => {
- it('persist → new store: the clock and its state come back, the live state and idle clock do not', async () => {
+ it('persist → new store: the clock and its state come back marked restored; live state and idle clock do not', async () => {
vi.useFakeTimers()
const storage = memStorage()
const run1 = await boot(storage)
run1.useAgentStatus.getState().setState('a', 'working', 'claude')
vi.advanceTimersByTime(1000)
run1.useAgentStatus.getState().setState('a', 'done', 'claude')
- // Debounced — flush it.
vi.advanceTimersByTime(run1.LAST_SEEN_SAVE_DEBOUNCE_MS + 10)
const doneAt = run1.useAgentStatus.getState().byId['a'].lastEventAt!
+ // Only the two fields go to disk, under the clock key; the main table carries no clock.
+ expect(JSON.parse(storage.getItem(CLOCK_KEY)!)).toEqual({ a: { at: doneAt, state: 'done' } })
+ expect(storage.getItem(KEY)).toBeNull()
const run2 = await boot(storage)
const st = run2.useAgentStatus.getState().byId['a']
- expect(st.lastSeen).toEqual({ at: doneAt, state: 'done' })
+ expect(st.lastSeen).toEqual({ at: doneAt, state: 'done', restored: true })
expect(st.state).toBeUndefined()
expect(st.lastEventAt).toBeUndefined()
expect(st.stateAt).toBeUndefined()
})
- it('a same-state hook event moves the clock and is saved on the debounce, not per event', async () => {
+ it('a long burst of hook events writes the clock key ONCE (trailing debounce) and never the main table', async () => {
vi.useFakeTimers()
const storage = memStorage()
const spy = vi.spyOn(storage, 'setItem')
const run1 = await boot(storage)
const s = run1.useAgentStatus.getState()
s.setState('b', 'working', 'claude')
+ // 2 Hz for 10 s — a busy turn's tool events.
for (let i = 0; i < 20; i++) {
- vi.advanceTimersByTime(50)
- s.setState('b', 'working', 'claude') // same-state freshness (a tool event)
+ vi.advanceTimersByTime(500)
+ s.setState('b', 'working', 'claude')
}
- expect(spy).not.toHaveBeenCalled() // no write per tool event
+ expect(spy).not.toHaveBeenCalled()
vi.advanceTimersByTime(run1.LAST_SEEN_SAVE_DEBOUNCE_MS + 10)
- expect(spy).toHaveBeenCalledTimes(1)
- const saved = JSON.parse(storage.getItem(KEY)!)
- expect(saved.b.lastSeen.at).toBe(run1.useAgentStatus.getState().byId['b'].stateAt)
- expect(saved.b.lastSeen.at).toBeGreaterThan(run1.useAgentStatus.getState().byId['b'].lastEventAt!)
- expect(saved.b.state).toBeUndefined()
- expect(saved.b.lastEventAt).toBeUndefined()
+ expect(spy.mock.calls.map((c) => c[0])).toEqual([CLOCK_KEY])
+ const saved = JSON.parse(storage.getItem(CLOCK_KEY)!)
+ expect(saved.b.at).toBe(run1.useAgentStatus.getState().byId['b'].stateAt)
+ expect(storage.getItem(KEY)).toBeNull() // state events still write nothing to the main table
+ })
+
+ it('a canvas that is never quiet still persists within the max wait', async () => {
+ vi.useFakeTimers()
+ const storage = memStorage()
+ const spy = vi.spyOn(storage, 'setItem')
+ const run1 = await boot(storage)
+ const s = run1.useAgentStatus.getState()
+ s.setState('c', 'working', 'claude')
+ const steps = Math.ceil(run1.LAST_SEEN_SAVE_MAX_WAIT_MS / 1000) + 1
+ for (let i = 0; i < steps; i++) {
+ vi.advanceTimersByTime(1000)
+ s.setState('c', 'working', 'claude')
+ }
+ expect(spy.mock.calls.filter((c) => c[0] === CLOCK_KEY)).toHaveLength(1)
+ expect(spy.mock.calls.some((c) => c[0] === KEY)).toBe(false)
})
- it('remove() drops the clock with the node, so a deleted node leaves nothing on disk', async () => {
+ it('remove() drops the clock with the node at once, and a pending debounce cannot resurrect it', async () => {
vi.useFakeTimers()
const storage = memStorage()
const run1 = await boot(storage)
run1.useAgentStatus.getState().setState('c', 'done', 'claude')
vi.advanceTimersByTime(run1.LAST_SEEN_SAVE_DEBOUNCE_MS + 10)
- expect(JSON.parse(storage.getItem(KEY)!).c.lastSeen).toBeDefined()
+ expect(JSON.parse(storage.getItem(CLOCK_KEY)!).c).toBeDefined()
+ run1.useAgentStatus.getState().setState('c', 'working', 'claude') // arms a debounce
run1.useAgentStatus.getState().remove('c')
- // Even a debounced save that was already pending cannot resurrect it.
- vi.advanceTimersByTime(run1.LAST_SEEN_SAVE_DEBOUNCE_MS + 10)
- expect(JSON.parse(storage.getItem(KEY)!).c).toBeUndefined()
+ expect(JSON.parse(storage.getItem(CLOCK_KEY)!).c).toBeUndefined()
+ vi.advanceTimersByTime(run1.LAST_SEEN_SAVE_MAX_WAIT_MS)
+ expect(JSON.parse(storage.getItem(CLOCK_KEY)!).c).toBeUndefined()
const run2 = await boot(storage)
expect(run2.useAgentStatus.getState().byId['c']).toBeUndefined()
})
@@ -107,6 +130,37 @@ describe('lastSeen survives a restart as a clock, not a state', () => {
})
})
+describe('the first event after a restart (SessionStart of a cold-restore resume)', () => {
+ it('drops the restored mark, re-renders so the row re-sorts, and leaves the idle clock unknown', async () => {
+ const now = Date.now()
+ const storage = seeded(
+ { r: { agentId: 'claude', sessionId: 's' } },
+ { r: { at: now - 5 * HOUR, state: 'done' } }
+ )
+ const { useAgentStatus } = await boot(storage)
+ const before = useAgentStatus.getState().byId
+ // A SessionStart normalizes to `state: undefined` — same-state for a restored entry.
+ useAgentStatus.getState().setState('r', undefined, 'claude')
+ const after = useAgentStatus.getState().byId
+ expect(after).not.toBe(before) // a new table: subscribers (the sidebar) re-sort now
+ expect(after.r.lastSeen?.restored).toBeUndefined()
+ expect(Date.now() - after.r.lastSeen!.at).toBeLessThan(5000)
+ expect(after.r.lastEventAt).toBeUndefined() // an unknown state is not an idle one
+ expect(after.r.sessionId).toBe('s')
+
+ const project = {
+ id: 'p',
+ name: 'P',
+ color: '#fff',
+ nodes: [{ id: 'r', kind: 'terminal' as const, title: 'r', color: '#fff', agentId: 'claude' as const }]
+ }
+ const row = buildStatusList([project], null, 'p', after, '').flatMap((g) => g.rows)[0]
+ expect(row.statusClock).toBe('seen') // NOT "before nodeterm restarted"
+ const { sessionStateAgeTitle } = await import('../lib/sessionList')
+ expect(sessionStateAgeTitle('seen just now', row.statusClock)).not.toMatch(/restarted/)
+ })
+})
+
describe('hostile / corrupt persisted values', () => {
const now = Date.UTC(2026, 8, 30)
it('readLastSeen refuses what is not a sane past clock', async () => {
@@ -128,24 +182,26 @@ describe('hostile / corrupt persisted values', () => {
]) {
expect(readLastSeen(bad, now)).toBeUndefined()
}
- // Unknown state: keep the time, drop the state. Prototype names are not states.
+ // Unknown state: keep the time, drop the state. Prototype names are not states. A forged
+ // `restored` never comes through (the loader sets it itself).
expect(readLastSeen({ at: now - HOUR, state: 'constructor' }, now)).toEqual({ at: now - HOUR })
expect(readLastSeen({ at: now - HOUR, state: 7 }, now)).toEqual({ at: now - HOUR })
- expect(readLastSeen({ at: now - HOUR, state: 'blocked', extra: 1 }, now)).toEqual({
+ expect(readLastSeen({ at: now - HOUR, state: 'blocked', extra: 1, restored: 'no' }, now)).toEqual({
at: now - HOUR,
state: 'blocked'
})
})
- it('a corrupt entry never breaks the load of its neighbours, and never becomes a state', async () => {
- const storage = memStorage({
- [KEY]: JSON.stringify({
- good: { unread: true, lastSeen: { at: Date.now() - HOUR, state: 'working' } },
+ it('a corrupt clock never breaks the load of the table or its neighbours, and never becomes a state', async () => {
+ const storage = seeded(
+ { good: { unread: true }, badClock: { sessionId: 's', state: 'working', lastEventAt: 1 } },
+ {
+ good: { at: Date.now() - HOUR, state: 'working' },
nullEntry: null,
numEntry: 5,
- badClock: { sessionId: 's', lastSeen: { at: 'soon', state: 'done' }, state: 'working', lastEventAt: 1 }
- })
- })
+ badClock: { at: 'soon', state: 'done' }
+ }
+ )
const { useAgentStatus } = await boot(storage)
const byId = useAgentStatus.getState().byId
expect(byId.good.unread).toBe(true)
@@ -159,7 +215,16 @@ describe('hostile / corrupt persisted values', () => {
expect(byId.numEntry).toBeUndefined()
})
- it('a non-object top level loads as empty', async () => {
+ it('an unparseable or non-object clock key costs the clocks only', async () => {
+ for (const raw of ['{not json', '"hello"', '[1,2]', 'null']) {
+ const { useAgentStatus } = await boot(
+ memStorage({ [KEY]: JSON.stringify({ k: { unread: true } }), [CLOCK_KEY]: raw })
+ )
+ expect(useAgentStatus.getState().byId).toEqual({ k: { unread: true } })
+ }
+ })
+
+ it('a non-object main table loads as empty', async () => {
const { useAgentStatus } = await boot(memStorage({ [KEY]: '"hello"' }))
expect(useAgentStatus.getState().byId).toEqual({})
})
@@ -177,12 +242,9 @@ describe('Eco stays inert for a restored clock', () => {
const cfg = { enabled: true, idleMinutes: 30 }
it('a status restored from disk (lastSeen done, hours old) is never a candidate', async () => {
- const storage = memStorage({
- [KEY]: JSON.stringify({
- e: { agentId: 'claude', sessionId: 'sess', lastSeen: { at: Date.now() - 6 * HOUR, state: 'done' } }
- })
- })
- const { useAgentStatus } = await boot(storage)
+ const { useAgentStatus } = await boot(
+ seeded({ e: { agentId: 'claude', sessionId: 'sess' } }, { e: { at: Date.now() - 6 * HOUR, state: 'done' } })
+ )
const st = useAgentStatus.getState().byId['e']
const rows = buildHibernationCandidates({ ...base, statusById: { e: st } })
expect(rows[0].lastEventAt).toBeUndefined()
@@ -203,27 +265,19 @@ describe('Eco stays inert for a restored clock', () => {
})
it('pins why neither field may be restored: fed a guessed done + the old clock, the plan WOULD exit it', () => {
- // Pins WHY the adapter must not read lastSeen: were the restored clock fed in as lastEventAt with a
- // restored state, the pure plan WOULD pick it. The only thing keeping Eco inert is that neither
- // field is restored — which the test above pins through the real store.
const guessed = buildHibernationCandidates({
...base,
statusById: { e: { state: 'done', sessionId: 's', lastEventAt: Date.now() - 6 * HOUR } }
})
expect(planHibernation(guessed, Date.now(), cfg)).toEqual(['e'])
- const restored = buildHibernationCandidates({
- ...base,
- statusById: { e: { sessionId: 's' } }
- })
+ const restored = buildHibernationCandidates({ ...base, statusById: { e: { sessionId: 's' } } })
expect(planHibernation(restored, Date.now(), cfg)).toEqual([])
})
it('the first live done after boot starts the idle window from NOW, not from the restored clock', async () => {
- vi.useFakeTimers()
- const storage = memStorage({
- [KEY]: JSON.stringify({ e: { agentId: 'claude', sessionId: 's', lastSeen: { at: Date.now() - 6 * HOUR, state: 'done' } } })
- })
- const { useAgentStatus } = await boot(storage)
+ const { useAgentStatus } = await boot(
+ seeded({ e: { agentId: 'claude', sessionId: 's' } }, { e: { at: Date.now() - 6 * HOUR, state: 'done' } })
+ )
useAgentStatus.getState().setState('e', 'done', 'claude')
const st = useAgentStatus.getState().byId['e']
const rows = buildHibernationCandidates({ ...base, statusById: { e: st } })
@@ -235,17 +289,18 @@ describe('Eco stays inert for a restored clock', () => {
describe('sidebar ordering and age label', () => {
it('orders rows by the restored clock and labels it as from before the restart', async () => {
const now = Date.now()
- const storage = memStorage({
- [KEY]: JSON.stringify({
- old: { agentId: 'claude', lastSeen: { at: now - 5 * HOUR, state: 'done' } },
- recent: { agentId: 'claude', lastSeen: { at: now - 1 * HOUR, state: 'working' } },
- // A persisted clock for a node that no longer exists on any canvas: it must not make a row.
- ghost: { agentId: 'claude', lastSeen: { at: now - 60_000, state: 'done' } }
- })
- })
- const { useAgentStatus } = await boot(storage)
+ const { useAgentStatus } = await boot(
+ seeded(
+ { old: { agentId: 'claude' }, recent: { agentId: 'claude' } },
+ {
+ old: { at: now - 5 * HOUR, state: 'done' },
+ recent: { at: now - 1 * HOUR, state: 'working' },
+ // A clock for a node that no longer exists on any canvas: it must not make a row.
+ ghost: { at: now - 60_000, state: 'done' }
+ }
+ )
+ )
const { sessionStateAgeLabel, sessionStateAgeTitle } = await import('../lib/sessionList')
- const statusById = useAgentStatus.getState().byId
const project = {
id: 'p',
name: 'P',
@@ -256,23 +311,23 @@ describe('sidebar ordering and age label', () => {
{ id: 'recent', kind: 'terminal' as const, title: 'c-recent', color: '#fff', agentId: 'claude' as const }
]
}
- const groups = buildStatusList([project], null, 'p', statusById, '')
+ const groups = buildStatusList([project], null, 'p', useAgentStatus.getState().byId, '')
const unknown = groups.find((g) => g.kind === 'unknown')!
expect(unknown.rows.map((r) => r.id)).toEqual(['recent', 'old', 'noClock'])
expect(groups.flatMap((g) => g.rows).some((r) => r.id === 'ghost')).toBe(false)
const recent = unknown.rows[0]
- expect(recent.statusClockRestored).toBe(true)
+ expect(recent.statusClock).toBe('restored')
expect(recent.lastSeenState).toBe('working')
expect(recent.statusKind).toBe('unknown') // the restored state is display-only
- const label = sessionStateAgeLabel(recent.statusUpdatedAt, now, recent.statusClockRestored)
+ const label = sessionStateAgeLabel(recent.statusUpdatedAt, now, recent.statusClock)
expect(label).toBe('seen 1h ago')
- expect(sessionStateAgeTitle(label!, true, 'working')).toMatch(/before nodeterm restarted/)
- expect(sessionStateAgeTitle(label!, true, 'working')).toMatch(/Running/)
- // A live clock wins and is not marked restored.
+ expect(sessionStateAgeTitle(label!, 'restored', 'working')).toMatch(/before nodeterm restarted/)
+ expect(sessionStateAgeTitle(label!, 'restored', 'working')).toMatch(/Running/)
+ // A live transition wins.
useAgentStatus.getState().setState('old', 'done', 'claude')
const after = buildStatusList([project], null, 'p', useAgentStatus.getState().byId, '')
const oldRow = after.flatMap((g) => g.rows).find((r) => r.id === 'old')!
- expect(oldRow.statusClockRestored).toBeUndefined()
- expect(sessionStateAgeLabel(oldRow.statusUpdatedAt, Date.now(), oldRow.statusClockRestored)).toBe('just now')
+ expect(oldRow.statusClock).toBe('transition')
+ expect(sessionStateAgeLabel(oldRow.statusUpdatedAt, Date.now(), oldRow.statusClock)).toBe('just now')
})
})
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index af72340d8..3ee369b4e 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -68,8 +68,11 @@ export interface AgentNodeStatus {
lastEventAt?: number
/**
* When the LAST hook event for this node landed, and the state it asserted — the one status clock
- * that survives an app restart. PERSISTED (bounded: `LAST_SEEN_MAX` newest, `LAST_SEEN_MAX_AGE_MS`
- * old at most, dropped with the node by `remove`).
+ * that survives an app restart. PERSISTED under its OWN small key (`<persistKey>.lastSeen`, see
+ * `saveClocks`) — never inside the main table, whose write cadence stays exactly what it was.
+ * Bounded: `LAST_SEEN_MAX` newest, `LAST_SEEN_MAX_AGE_MS` old at most, dropped with the node by
+ * `remove` (a deletion path that bypasses `remove` leaves a clock that ages out; it can never make
+ * a row, since rows come from canvas nodes).
*
* It is a record of the PAST, restored as nothing else:
* - NOT as `state`: after a relaunch nothing has reported, a turn may have started or ended while
@@ -81,12 +84,13 @@ export interface AgentNodeStatus {
* with no hook event in this run, deliberately — see `hibernation-policy.ts` ("A restored clock
* is not an idle proof").
* Its readers are the sessions sidebar's order and age label (`sessionList.ts`), which use it only
- * while `lastEventAt` is unset, i.e. only for a node that has not reported in this run.
+ * while `lastEventAt` is unset. `lastSeen.restored` (set on load, never written) is what says the
+ * clock is from BEFORE the restart; any hook event in this run replaces the object without it.
*
* Written on EVERY hook event, same-state ones included (in place, no re-render — the fast path's
- * rule), and saved on a trailing debounce plus `pagehide`, so a busy turn costs no write per tool
- * event. A same-state refresh is "last hook event time", which is what "last seen" means; the
- * in-run age label keeps reading the transition clock.
+ * rule — except the first event after a restart, which re-renders so the row re-sorts and loses
+ * its "restored" label), and saved on a trailing debounce (`LAST_SEEN_SAVE_DEBOUNCE_MS`, capped by
+ * `LAST_SEEN_SAVE_MAX_WAIT_MS`) plus `pagehide`, so a busy turn costs no write per tool event.
*/
lastSeen?: LastSeen
/**
@@ -419,12 +423,16 @@ export interface AgentStatusStore {
export interface LastSeen {
/** Epoch ms of the last hook event this machine received for the node. */
at: number
- /** The state that event asserted; undefined = it left the node idle/unknown (a SessionEnd). */
+ /** The state that event asserted; undefined = the event left the state unknown (a SessionStart
+ * or SessionEnd). */
state?: AgentState
+ /** TRANSIENT, set on load only: this clock came off disk, from before the app restarted. Never
+ * written back — every hook event in this run builds a fresh object without it. */
+ restored?: true
}
-/** At most this many persisted clocks (newest kept). The status table is rewritten whole on every
- * save, and a canvas that has churned through thousands of nodes must not grow it forever. */
+/** At most this many persisted clocks (newest kept): a canvas that has churned through thousands of
+ * nodes must not grow the clock key forever. */
export const LAST_SEEN_MAX = 1000
/** A clock older than this is dropped on load: "last seen 4 months ago" orders nothing useful, and
* an entry that old most likely belongs to a node deleted by a path that never reached `remove`. */
@@ -433,8 +441,13 @@ export const LAST_SEEN_MAX_AGE_MS = 90 * 24 * 60 * 60_000
* hand-editable, and a future stamp would pin a row to the top of its section for good. The slack
* covers an ordinary clock correction between two runs. */
export const LAST_SEEN_FUTURE_SLACK_MS = 5 * 60_000
-/** Trailing debounce for a save that only moved `lastSeen` (a same-state hook event). */
-export const LAST_SEEN_SAVE_DEBOUNCE_MS = 2000
+/** Trailing debounce for the clock key: written once the hook events have been quiet this long… */
+export const LAST_SEEN_SAVE_DEBOUNCE_MS = 5000
+/** …or at the latest this long after the first unsaved event, so a canvas that is never quiet still
+ * persists its clocks (a crash then loses at most this window). The key is ~47 bytes per clock. */
+export const LAST_SEEN_SAVE_MAX_WAIT_MS = 30_000
+/** The clocks' own localStorage key, beside (never inside) the main table. */
+export const lastSeenKey = (persistKey: string): string => `${persistKey}.lastSeen`
const AGENT_STATES: ReadonlySet<string> = new Set<AgentState>(['working', 'waiting', 'blocked', 'done'])
@@ -528,20 +541,38 @@ export function createAgentStatusSession(
if (persistKey === KEY) migrateLegacyKey()
function load(): Record<string, AgentNodeStatus> {
+ const out = loadMain()
+ if (!persistKey) return out
+ // The clocks ride their own key (see `lastSeen`). Restored as a CLOCK marked `restored`, never
+ // as `state` or `lastEventAt`.
+ try {
+ const raw = localStorage.getItem(lastSeenKey(persistKey))
+ const data: unknown = raw ? JSON.parse(raw) : undefined
+ if (data && typeof data === 'object' && !Array.isArray(data)) {
+ const nowMs = Date.now()
+ for (const [id, v] of Object.entries(data as Record<string, unknown>)) {
+ const seen = readLastSeen(v, nowMs)
+ if (!seen) continue
+ out[id] = { ...(out[id] ?? EMPTY), lastSeen: { ...seen, restored: true } }
+ }
+ }
+ } catch {
+ /* an unreadable clock key costs the clocks, never the table */
+ }
+ return out
+ }
+
+ function loadMain(): 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> = {}
- const nowMs = Date.now()
if (!data || typeof data !== 'object') return {}
for (const [id, v] of Object.entries(data)) {
if (!v || typeof v !== 'object') continue
out[id] = { unread: !!v.unread, session: v.session, sessionId: v.sessionId, agentId: v.agentId }
- // Restored as a CLOCK, never as `state` or `lastEventAt` (see the field comment).
- const seen = readLastSeen(v.lastSeen, nowMs)
- if (seen) out[id].lastSeen = seen
// Minimal shape check, like `loop` below: this file is on disk and hand-editable, and a
// half-written entry must not put a chip on a node claiming an identity it never had.
if (
@@ -613,15 +644,10 @@ export function createAgentStatusSession(
// Persist only the durable fields (not the live `state`).
function save(byId: Record<string, AgentNodeStatus>): void {
if (!persistKey) return
- // Any full save also writes the latest clocks, so a pending debounced one is superseded.
- cancelClockSave()
try {
const out: Record<string, Partial<AgentNodeStatus>> = {}
- const keepClock = lastSeenKeep(byId)
for (const [id, v] of Object.entries(byId)) {
- const lastSeen = keepClock.has(id) ? v.lastSeen : undefined
if (
- lastSeen ||
v.unread ||
v.session ||
v.sessionId ||
@@ -644,9 +670,7 @@ export function createAgentStatusSession(
hibernated: v.hibernated,
// Never written without a flag it belongs to (see `hibernatedContext`'s load comment).
hibernatedContext: v.hibernated || v.paused ? v.hibernatedContext : undefined,
- paused: v.paused,
- // A fresh object of exactly the two fields, never the live one: nothing else rides out.
- lastSeen: lastSeen ? { at: lastSeen.at, state: lastSeen.state } : undefined
+ paused: v.paused
}
}
}
@@ -656,24 +680,47 @@ export function createAgentStatusSession(
}
}
- // The trailing save for clock-only changes (see `lastSeen`). One timer per instance; a keyless
- // instance never arms it.
+ // The clock key (see `lastSeen`): its own small record, so a hook event never rewrites the main
+ // table (which carries loop items and is shared, per key, by every Server Edition tab).
+ function saveClocks(byId: Record<string, AgentNodeStatus>): void {
+ cancelClockSave()
+ if (!persistKey) return
+ try {
+ const out: Record<string, { at: number; state?: AgentState }> = {}
+ // A fresh object of exactly the two fields: `restored` and anything else never ride out.
+ for (const id of lastSeenKeep(byId)) {
+ const c = byId[id].lastSeen!
+ out[id] = c.state ? { at: c.at, state: c.state } : { at: c.at }
+ }
+ localStorage.setItem(lastSeenKey(persistKey), JSON.stringify(out))
+ } catch {
+ // ignore quota / serialization errors
+ }
+ }
+ // A TRAILING debounce with a max wait: each event pushes the write back by the debounce window,
+ // but never past `LAST_SEEN_SAVE_MAX_WAIT_MS` after the first unsaved event.
let clockSaveTimer: ReturnType<typeof setTimeout> | undefined
+ let clockDirtySince: number | undefined
function cancelClockSave(): void {
if (clockSaveTimer !== undefined) clearTimeout(clockSaveTimer)
clockSaveTimer = undefined
+ clockDirtySince = undefined
}
function scheduleClockSave(): void {
- if (!persistKey || clockSaveTimer !== undefined) return
- clockSaveTimer = setTimeout(() => {
- clockSaveTimer = undefined
- save(store.getState().byId)
- }, LAST_SEEN_SAVE_DEBOUNCE_MS)
+ if (!persistKey) return
+ const now = Date.now()
+ if (clockDirtySince === undefined) clockDirtySince = now
+ if (clockSaveTimer !== undefined) clearTimeout(clockSaveTimer)
+ const wait = Math.max(
+ 0,
+ Math.min(LAST_SEEN_SAVE_DEBOUNCE_MS, clockDirtySince + LAST_SEEN_SAVE_MAX_WAIT_MS - now)
+ )
+ clockSaveTimer = setTimeout(() => saveClocks(store.getState().byId), wait)
}
// A quit/reload inside the debounce window must not lose the newest clock.
if (persistKey && typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
window.addEventListener('pagehide', () => {
- if (clockSaveTimer !== undefined) save(store.getState().byId)
+ if (clockSaveTimer !== undefined) saveClocks(store.getState().byId)
})
}
@@ -754,6 +801,20 @@ export function createAgentStatusSession(
) {
// 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]?.lastSeen?.restored) {
+ // The FIRST event after a restart for a node whose state is still unknown (a
+ // SessionStart from a cold-restore resume, say) is same-state by construction. Not in
+ // place: the row must lose its "restored" label and re-sort NOW, not whenever another
+ // node's event happens to replace `byId`. The idle clock is deliberately left unset —
+ // an unknown state is not an idle one.
+ scheduleClockSave()
+ return {
+ byId: {
+ ...s.byId,
+ [id]: { ...s.byId[id], stateAt: now, stateVerified: verified === true, lastSeen: { at: now, state } }
+ }
+ }
+ }
if (s.byId[id]) {
s.byId[id].stateAt = now
// "Last seen" is the last hook EVENT, so a same-state one moves it too — in place, like
@@ -860,7 +921,7 @@ export function createAgentStatusSession(
// PERSISTED flag has to reach disk, or a relaunch would restore a hibernated/paused node
// that has been demonstrably running since.
if (alive && (prev.hibernated || prev.paused)) save(byId)
- else scheduleClockSave()
+ scheduleClockSave()
return { byId }
})
// After the set: a listener reads the store and must see this event applied.
@@ -1133,6 +1194,8 @@ export function createAgentStatusSession(
const byId = { ...s.byId }
delete byId[id]
save(byId)
+ // Now, not on the debounce: the deleted node's clock must not outlive it on disk.
+ if (s.byId[id].lastSeen) saveClocks(byId)
return { byId }
})
}))