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): keep a "last seen" clock across an app restart

review1842b9f06425
diff --git a/CLAUDE.md b/CLAUDE.md
index a81a8d718..ff2ce1b59 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -852,7 +852,10 @@ Lifecycle, by intent:
Eco defers the Phase-2 viewer release until the node hibernates (hard cap idle+offscreen), but
ONLY when the idle clock is known (`idleKnown` — `lastEventAt` is transient, so after an app
restart nothing can hibernate and deferring would make Eco a memory regression). Eco is
- structurally inert for sessions with no turn in the current app run — documented follow-up.
+ structurally inert for sessions with no turn in the current app run, and that is now a DECISION,
+ not a follow-up: the persisted `agentStatus.lastSeen` clock (see **Status-grouped sessions**) is
+ deliberately never an idle proof — see "A restored clock is not an idle proof" in
+ `terminal/hibernation-policy.ts`.
The deferral is also unaware of `paused`: a deep-paused node's freshly recycled shell keeps its
xterm alive until the hard cap, waiting for a hibernation that (being already exited, or having
no CLI to exit) can never come — a second documented follow-up.
@@ -2901,6 +2904,35 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
another user prompt. Within each section rows sort newest-first by `lastEventAt`, the transition
clock (same-state hook freshness is `stateAt`), and show its short relative age. Missing clocks
stay last with no made-up timestamp. A click may clear the glow but cannot move the row.
+ **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,
+ 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.
+ - **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`.
+ - 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).
- **Session name ⇄ node title** — **two lists, because the two directions are separate facts**:
`TITLE_READ_CAPABLE` (`canReadTitle` — claude, **codex**, grok, **gemini**) is the READ leg,
`RENAME_CAPABLE` (`canRename` — claude, grok) the WRITE leg, and **read ⊇ write** is an invariant
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index aab67070c..0232228ac 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -149,7 +149,9 @@ chain appears, or if anything but `dispatchOnUserMove` creates a queued entry.
A card chip that reads agent state subscribes to a **primitive signature** of the nodes it shows
(`teamProgressSig`, `issueRunChipSig`), never to the whole `agentStatus.byId` map — that map changes
-on every hook event of every node. Before a card shows a fact, check that its place on the board
+on every hook event of every node. A field of `agentStatus` that is persisted across a restart is restored
+as a record of the past, never as live state: `lastSeen` orders and ages sidebar rows but never
+becomes `state` or Eco's idle clock (`lastEventAt`). Before a card shows a fact, check that its place on the board
does not already say it (`lib/cardRedundancy.ts`); the card modal keeps every fact the card drops.
`project.ropes` / `bridges` are hostile input like the board: they are admitted through
`sanitizeLinks` on every load and save seam, and a reader still tolerates anything. A wait rope
diff --git a/src/renderer/components/SessionRow.tsx b/src/renderer/components/SessionRow.tsx
index 1884aa7cb..3ddbb6c23 100644
--- a/src/renderer/components/SessionRow.tsx
+++ b/src/renderer/components/SessionRow.tsx
@@ -4,6 +4,7 @@ import { IconBellFilled, IconCircleCheck, IconClose } from './icons'
import { NodeIconView } from './NodeIcon'
import { ProjectGlyph } from './ProjectGlyph'
import type { SessionRowVM } from '../lib/sessionList'
+import { sessionStateAgeTitle } from '../lib/sessionList'
import { useContextWindow } from '../state/contextWindow'
import { useSessionNaming } from '../state/sessionNaming'
import { useSettings } from '../state/settings'
@@ -201,7 +202,10 @@ export function SessionRow({
{row.sshHost && <span className="ss-meta__ssh">⇅ {row.sshHost}</span>}
{row.cwd && <span className="ss-meta__cwd">{dirName(row.cwd)}</span>}
{stateAgeLabel && (
- <span className="ss-meta__state-age" title={`Entered this state ${stateAgeLabel}`}>
+ <span
+ className={`ss-meta__state-age${row.statusClockRestored ? ' ss-meta__state-age--restored' : ''}`}
+ title={sessionStateAgeTitle(stateAgeLabel, !!row.statusClockRestored, row.lastSeenState)}
+ >
{stateAgeLabel}
</span>
)}
diff --git a/src/renderer/components/SessionsSidebar.tsx b/src/renderer/components/SessionsSidebar.tsx
index e15806781..f541edac7 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)}
+ stateAgeLabel={sessionStateAgeLabel(row.statusUpdatedAt, statusNow, row.statusClockRestored)}
/>
</div>
)
diff --git a/src/renderer/lib/sessionList.ts b/src/renderer/lib/sessionList.ts
index 94a03be6d..277058cc3 100644
--- a/src/renderer/lib/sessionList.ts
+++ b/src/renderer/lib/sessionList.ts
@@ -1,5 +1,6 @@
import type { AgentNodeStatus } from '../state/agentStatus'
import type { AgentId } from '@shared/agents/config'
+import type { AgentState } from '@shared/agents/normalize'
import type { NodeKind, ObservedClaudeAccount } from '@shared/types'
import type { NodeIcon } from '@shared/node-icon'
import { hasUsage } from '@shared/agents/config'
@@ -210,8 +211,26 @@ export function sessionStatusKind(state: AgentNodeStatus['state']): StatusKind {
}
/** Human-readable age of the current state. No timestamp means genuinely unknown, not "just now". */
-export function sessionStateAgeLabel(updatedAt: number | undefined, nowMs: number): string | undefined {
- return updatedAt === undefined ? undefined : relativeTime(updatedAt, nowMs)
+export function sessionStateAgeLabel(
+ updatedAt: number | undefined,
+ nowMs: number,
+ restored = false
+): 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)
+}
+
+/** The age label's tooltip, restored or live. Pure, so the wording is pinned beside the label. */
+export function sessionStateAgeTitle(
+ label: string,
+ restored: boolean,
+ lastSeenState?: AgentState
+): string {
+ if (!restored) return `Entered this state ${label}`
+ 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.`
}
/**
@@ -234,8 +253,16 @@ export interface SessionRowVM {
isAgent: boolean
statusKind: StatusKind
stateLabel: string
- /** When the current live state began. Transient; absent when no transition has been observed. */
+ /**
+ * The row's clock: when the current live state began (`lastEventAt`) or — for a node that has not
+ * reported in this run — when its last hook event landed before the restart (`lastSeen.at`). Sort
+ * 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). */
+ lastSeenState?: AgentState
unread: boolean
session?: string
loop?: { kind: 'loop' | 'schedule' | 'cron'; count: number }
@@ -308,7 +335,11 @@ function toRow(
isAgent: !!n.agentId,
statusKind,
stateLabel: STATE_LABEL[statusKind],
- statusUpdatedAt: status?.lastEventAt,
+ // Live clock first; the persisted one only while this run has seen nothing for the node.
+ statusUpdatedAt: status?.lastEventAt ?? status?.lastSeen?.at,
+ ...(status?.lastEventAt === undefined && status?.lastSeen
+ ? { statusClockRestored: true, lastSeenState: status.lastSeen.state }
+ : {}),
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
new file mode 100644
index 000000000..1f539af8e
--- /dev/null
+++ b/src/renderer/state/agentStatus.lastSeen.test.ts
@@ -0,0 +1,278 @@
+import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
+import { buildHibernationCandidates } from '../lib/hibernationCandidates'
+import { planHibernation } from '../terminal/hibernation-policy'
+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.
+
+function memStorage(seed: Record<string, string> = {}): Storage & { map: Map<string, string> } {
+ 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),
+ clear: () => m.clear(),
+ key: () => null,
+ get length() {
+ return m.size
+ }
+ } as Storage & { map: Map<string, string> }
+}
+
+const KEY = 'nodeterm.agentStatus'
+const HOUR = 3600_000
+
+beforeEach(() => vi.resetModules())
+afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+})
+
+/** Run one app "session": import a fresh store over `storage`. */
+async function boot(storage: Storage): Promise<typeof import('./agentStatus')> {
+ vi.resetModules()
+ vi.stubGlobal('localStorage', storage)
+ return 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 () => {
+ 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!
+
+ const run2 = await boot(storage)
+ const st = run2.useAgentStatus.getState().byId['a']
+ expect(st.lastSeen).toEqual({ at: doneAt, state: 'done' })
+ 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 () => {
+ 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')
+ for (let i = 0; i < 20; i++) {
+ vi.advanceTimersByTime(50)
+ s.setState('b', 'working', 'claude') // same-state freshness (a tool event)
+ }
+ expect(spy).not.toHaveBeenCalled() // no write per tool event
+ 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()
+ })
+
+ it('remove() drops the clock with the node, so a deleted node leaves nothing on disk', 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()
+ 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()
+ const run2 = await boot(storage)
+ expect(run2.useAgentStatus.getState().byId['c']).toBeUndefined()
+ })
+
+ it('bounds the persisted clocks to the newest LAST_SEEN_MAX', async () => {
+ const { lastSeenKeep, LAST_SEEN_MAX } = await boot(memStorage())
+ const byId: Record<string, { lastSeen?: { at: number } }> = {}
+ for (let i = 0; i < LAST_SEEN_MAX + 5; i++) byId[`n${i}`] = { lastSeen: { at: 1_000 + i } }
+ byId.none = {}
+ const keep = lastSeenKeep(byId)
+ expect(keep.size).toBe(LAST_SEEN_MAX)
+ for (let i = 0; i < 5; i++) expect(keep.has(`n${i}`)).toBe(false) // oldest dropped
+ expect(keep.has(`n${LAST_SEEN_MAX + 4}`)).toBe(true)
+ expect(keep.has('none')).toBe(false)
+ })
+})
+
+describe('hostile / corrupt persisted values', () => {
+ const now = Date.UTC(2026, 8, 30)
+ it('readLastSeen refuses what is not a sane past clock', async () => {
+ const { readLastSeen, LAST_SEEN_MAX_AGE_MS, LAST_SEEN_FUTURE_SLACK_MS } = await boot(memStorage())
+ for (const bad of [
+ null,
+ undefined,
+ 42,
+ 'x',
+ [],
+ {},
+ { at: 'yesterday' },
+ { at: NaN },
+ { at: Infinity },
+ { at: -5 },
+ { at: 0 },
+ { at: now + LAST_SEEN_FUTURE_SLACK_MS + 1 }, // future: would pin a row to the top
+ { at: now - LAST_SEEN_MAX_AGE_MS - 1 }
+ ]) {
+ expect(readLastSeen(bad, now)).toBeUndefined()
+ }
+ // Unknown state: keep the time, drop the state. Prototype names are not states.
+ 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({
+ 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' } },
+ nullEntry: null,
+ numEntry: 5,
+ badClock: { sessionId: 's', lastSeen: { at: 'soon', state: 'done' }, state: 'working', lastEventAt: 1 }
+ })
+ })
+ const { useAgentStatus } = await boot(storage)
+ const byId = useAgentStatus.getState().byId
+ expect(byId.good.unread).toBe(true)
+ expect(byId.good.lastSeen?.state).toBe('working')
+ expect(byId.good.state).toBeUndefined() // a restored "working" is not a live one
+ expect(byId.badClock.sessionId).toBe('s')
+ expect(byId.badClock.lastSeen).toBeUndefined()
+ expect(byId.badClock.state).toBeUndefined()
+ expect(byId.badClock.lastEventAt).toBeUndefined()
+ expect(byId.nullEntry).toBeUndefined()
+ expect(byId.numEntry).toBeUndefined()
+ })
+
+ it('a non-object top level loads as empty', async () => {
+ const { useAgentStatus } = await boot(memStorage({ [KEY]: '"hello"' }))
+ expect(useAgentStatus.getState().byId).toEqual({})
+ })
+})
+
+describe('Eco stays inert for a restored clock', () => {
+ const nodes = [{ id: 'e', agentId: 'claude' }]
+ const base = {
+ nodes,
+ subagents: [],
+ isOffscreen: () => true,
+ isWired: () => true,
+ isRemote: () => false
+ }
+ 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 st = useAgentStatus.getState().byId['e']
+ const rows = buildHibernationCandidates({ ...base, statusById: { e: st } })
+ expect(rows[0].lastEventAt).toBeUndefined()
+ expect(rows[0].state).toBeUndefined()
+ expect(planHibernation(rows, Date.now(), cfg)).toEqual([])
+ // Nor does it hold its viewer waiting for a hibernation that cannot come.
+ expect(
+ shouldDeferReleaseForEco({
+ ecoEnabled: true,
+ resumableAgent: true,
+ hibernated: false,
+ idleKnown: st.lastEventAt !== undefined,
+ offscreenElapsedMs: HOUR,
+ idleMinutes: 30,
+ offscreenMinutes: 10
+ })
+ ).toBe(false)
+ })
+
+ 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' } }
+ })
+ 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)
+ useAgentStatus.getState().setState('e', 'done', 'claude')
+ const st = useAgentStatus.getState().byId['e']
+ const rows = buildHibernationCandidates({ ...base, statusById: { e: st } })
+ expect(planHibernation(rows, Date.now(), cfg)).toEqual([])
+ expect(planHibernation(rows, Date.now() + 31 * 60_000, cfg)).toEqual(['e'])
+ })
+})
+
+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 { sessionStateAgeLabel, sessionStateAgeTitle } = await import('../lib/sessionList')
+ const statusById = useAgentStatus.getState().byId
+ const project = {
+ id: 'p',
+ name: 'P',
+ color: '#fff',
+ nodes: [
+ { id: 'noClock', kind: 'terminal' as const, title: 'a-no-clock', color: '#fff', agentId: 'claude' as const },
+ { id: 'old', kind: 'terminal' as const, title: 'b-old', color: '#fff', agentId: 'claude' as const },
+ { id: 'recent', kind: 'terminal' as const, title: 'c-recent', color: '#fff', agentId: 'claude' as const }
+ ]
+ }
+ const groups = buildStatusList([project], null, 'p', statusById, '')
+ 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.lastSeenState).toBe('working')
+ expect(recent.statusKind).toBe('unknown') // the restored state is display-only
+ const label = sessionStateAgeLabel(recent.statusUpdatedAt, now, recent.statusClockRestored)
+ 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.
+ 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')
+ })
+})
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index d049d5fcc..af72340d8 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -8,9 +8,12 @@ import type { WakeContext } from '../terminal/wake-identity'
/**
* Transient per-node status for agent (e.g. Claude Code) sessions, driven by the agent's hooks.
- * `unread`, `session`, `sessionId`, `agentId`, `account`, `loop` and `hibernated` are persisted to
- * localStorage so they survive a reload/restart; the live `state` (working/waiting/…) is not
- * (it'd be stale on relaunch), and neither are its two clocks (`stateAt`, `lastEventAt`).
+ * `unread`, `session`, `sessionId`, `agentId`, `account`, `loop`, `hibernated` and `lastSeen` are
+ * persisted to localStorage so they survive a reload/restart; the live `state` (working/waiting/…)
+ * is not (it'd be stale on relaunch), and neither are its two clocks (`stateAt`, `lastEventAt`).
+ * `lastSeen` is a THIRD clock that exists only to be persisted: when the last hook event landed and
+ * which state it asserted, restored as a "last seen" label and a sort key — never as a state, and
+ * never as an idle clock (see its field comment).
* `agentId` is durable because a PLAIN terminal's agent identity exists nowhere else: an
* explicit agent node re-derives it from `data.agentId`, but a hand-launched `claude` in a
* plain terminal is only known here, and its context links must keep classifying across
@@ -63,6 +66,29 @@ export interface AgentNodeStatus {
* session the moment the app came back. Absent ⇒ unknown idle ⇒ never a hibernation candidate.
*/
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`).
+ *
+ * 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
+ * the app was down (the hook server was down with it), so the state stays unknown until the
+ * next hook event. `lastSeen.state` is shown as "what it was last seen doing", never acted on.
+ * - NOT as `lastEventAt`: that field is the Eco idle clock AND the `idleKnown` signal for the
+ * offscreen release deferral, and a restored stamp read as "idle since before the restart"
+ * would make a session with an unknown state look hours idle. Eco stays inert for a session
+ * 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.
+ *
+ * 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.
+ */
+ lastSeen?: LastSeen
/**
* When this node last launched a BACKGROUND shell task (Claude's `Bash` with
* `run_in_background: true`). Such a task lives inside the CLI process, so `/exit` — Eco
@@ -389,6 +415,54 @@ export interface AgentStatusStore {
remove(id: string): void
}
+/** The persisted "last seen" clock (see `AgentNodeStatus.lastSeen`). */
+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). */
+ state?: AgentState
+}
+
+/** 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. */
+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`. */
+export const LAST_SEEN_MAX_AGE_MS = 90 * 24 * 60 * 60_000
+/** A persisted clock more than this far in the FUTURE is refused, not clamped: localStorage is
+ * 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
+
+const AGENT_STATES: ReadonlySet<string> = new Set<AgentState>(['working', 'waiting', 'blocked', 'done'])
+
+/**
+ * Read a persisted `lastSeen` back — or nothing. Pure and exported for the corrupt-input tests. The
+ * value is hand-editable input: a non-object, a non-finite / non-positive / too-old / future `at`
+ * yields no clock at all; an unknown `state` keeps the clock and drops the state (the time is still
+ * a fact about the node, the label just cannot name what it was doing).
+ */
+export function readLastSeen(v: unknown, nowMs: number): LastSeen | undefined {
+ if (!v || typeof v !== 'object') return undefined
+ const { at, state } = v as { at?: unknown; state?: unknown }
+ if (typeof at !== 'number' || !Number.isFinite(at) || at <= 0) return undefined
+ if (at > nowMs + LAST_SEEN_FUTURE_SLACK_MS) return undefined
+ if (nowMs - at > LAST_SEEN_MAX_AGE_MS) return undefined
+ return typeof state === 'string' && AGENT_STATES.has(state)
+ ? { at, state: state as AgentState }
+ : { at }
+}
+
+/** The ids whose `lastSeen` may be written: the `LAST_SEEN_MAX` newest. Pure, for the bound test. */
+export function lastSeenKeep(byId: Record<string, { lastSeen?: LastSeen }>): Set<string> {
+ const withClock = Object.entries(byId).filter(([, v]) => v.lastSeen)
+ if (withClock.length <= LAST_SEEN_MAX) return new Set(withClock.map(([id]) => id))
+ withClock.sort((a, b) => b[1].lastSeen!.at - a[1].lastSeen!.at)
+ return new Set(withClock.slice(0, LAST_SEEN_MAX).map(([id]) => id))
+}
+
const EMPTY: AgentNodeStatus = { unread: false }
/** The DEFAULT (local-core) persistence key. Only the default instance uses it. */
const KEY = 'nodeterm.agentStatus'
@@ -460,8 +534,14 @@ export function createAgentStatusSession(
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 (
@@ -533,10 +613,15 @@ 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 ||
@@ -559,7 +644,9 @@ 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
+ 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
}
}
}
@@ -569,6 +656,27 @@ export function createAgentStatusSession(
}
}
+ // The trailing save for clock-only changes (see `lastSeen`). One timer per instance; a keyless
+ // instance never arms it.
+ let clockSaveTimer: ReturnType<typeof setTimeout> | undefined
+ function cancelClockSave(): void {
+ if (clockSaveTimer !== undefined) clearTimeout(clockSaveTimer)
+ clockSaveTimer = undefined
+ }
+ function scheduleClockSave(): void {
+ if (!persistKey || clockSaveTimer !== undefined) return
+ clockSaveTimer = setTimeout(() => {
+ clockSaveTimer = undefined
+ save(store.getState().byId)
+ }, LAST_SEEN_SAVE_DEBOUNCE_MS)
+ }
+ // 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)
+ })
+ }
+
// `onHookEvent` listeners, per node id. Outside zustand on purpose (see the interface).
const hookEventSubs = new Map<string, Set<() => void>>()
const pulse = (id: string): void => {
@@ -648,6 +756,10 @@ export function createAgentStatusSession(
// new object here would re-render every node header on each tool event.
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
+ // `stateAt`, and saved on the trailing debounce rather than once per tool event.
+ s.byId[id].lastSeen = { at: now, state }
+ scheduleClockSave()
// The evidence rides along, in place and for the same reason: a re-assert of the SAME
// state by a legacy POST must not leave an earlier `true` standing, or this copy would
// disagree with the mirror the gate actually reads.
@@ -658,7 +770,7 @@ export function createAgentStatusSession(
// The ONE place a state transition is recorded, so it is also the one place the idle
// clock is stamped (the same-state fast path above deliberately does not touch it —
// see `lastEventAt`).
- const next = { ...prev, state, stateAt: now, lastEventAt: now }
+ const next = { ...prev, state, stateAt: now, lastEventAt: now, lastSeen: { at: now, state } }
// Written on the same edge the state is — the evidence describes THIS transition, and an
// absent argument is not evidence.
next.stateVerified = verified === true
@@ -748,6 +860,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()
return { byId }
})
// After the set: a listener reads the store and must see this event applied.
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 3a38df8ad..2023317b2 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -8837,6 +8837,8 @@ button.group-node__setup:disabled {
.ss-meta__cwd { font-family: monospace; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ss-meta__ssh { display: inline-flex; align-items: center; gap: 3px; flex: 0 0 auto; }
.ss-meta__state-age { margin-left: auto; flex: 0 0 auto; font-variant-numeric: tabular-nums; }
+/* A clock restored from before the restart: a record of the past, drawn quieter than a live age. */
+.ss-meta__state-age--restored { font-style: italic; }
.ss-ctx { font-size: 9.5px; padding: 0 5px; border-radius: 4px; color: #000; font-weight: 600; flex: 0 0 auto; }
/* Out of FLOW, not merely invisible. Both buttons already appeared only on hover, yet they held
46px of a 253px line — measured — away from the name at every other moment. Floated over the
diff --git a/src/renderer/terminal/hibernation-policy.ts b/src/renderer/terminal/hibernation-policy.ts
index 8f8bfeb10..7dcb8bc20 100644
--- a/src/renderer/terminal/hibernation-policy.ts
+++ b/src/renderer/terminal/hibernation-policy.ts
@@ -32,6 +32,16 @@
* - **Unknown idle is NOT idle.** A candidate with no `lastEventAt` (no hook event has ever been
* seen for it in this run) is never eligible — the same rule as pendingLaunch's "an unknown
* dependency state is not satisfied". Guessing here costs the user a live session.
+ * - **A restored clock is not an idle proof.** `agentStatus.lastSeen` (the last hook event before
+ * an app restart) is persisted so the sidebar can order and age rows; it deliberately never
+ * reaches `lastEventAt` or this plan, so Eco stays inert for a session with no hook event in
+ * the current run. Two reasons, either sufficient: (1) the hook server was down with the app,
+ * so a turn that started or ended in between left no trace and the restored `done` may describe
+ * a pane that has been working for an hour; (2) even a PROVEN-idle prompt after boot is not
+ * enough, because the two other guards this plan needs — `backgroundTaskAt` (a background shell
+ * inside the CLI) and the subagent cards (async children still running) — are transient and
+ * cannot be rebuilt after a restart, and `/exit` kills both silently. A session becomes a
+ * candidate again with its next live `done`, from which the idle window is counted.
* - **Never a pane the agent does not OWN.** Eco's contract is "quit the CLI in this pane and
* resume it in this pane", and `#{pane_current_command}` cannot tell whether that is what the
* pane holds: an npm-installed CLI reports as `node`, and a CLI reached over an interactive
diff --git a/src/renderer/terminal/offscreen-policy.ts b/src/renderer/terminal/offscreen-policy.ts
index a65b9240f..bf9dd32a6 100644
--- a/src/renderer/terminal/offscreen-policy.ts
+++ b/src/renderer/terminal/offscreen-policy.ts
@@ -155,7 +155,9 @@ export function shouldDeferReleaseForEco(i: {
/**
* Has ANY hook event been seen for this node in this app run (`lastEventAt` is set)? Without
* one, `planHibernation` refuses the node outright — unknown idle is not idle — so there is
- * nothing to wait for. See the header.
+ * nothing to wait for. See the header. The PERSISTED `agentStatus.lastSeen` clock deliberately
+ * does not count here (the caller reads `lastEventAt` only): it cannot make a node hibernatable,
+ * so it must not make its viewer wait for a hibernation either.
*/
idleKnown: boolean
/** How long this node has been continuously out of view. */