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(agent-status): one central rule for a working session that went quiet

enesc746b77f28cb
diff --git a/docs/notch-hud.md b/docs/notch-hud.md
index c538942bb..0a661705a 100644
--- a/docs/notch-hud.md
+++ b/docs/notch-hud.md
@@ -60,10 +60,14 @@ Row shape sent to the HUD:
EDGE — a turn ending while the HUD is running — raises the highlight. A restored `needsYou` still
shows, because it genuinely still needs you.
- **working watchdog**: a session leaves `working` only when something says so, and some exits say
- nothing — Esc during a tool call, a killed CLI, a slept machine, a dropped SSH. So a `working`
- node with no event for `WORKING_STALE_MS` (20 min, well past Claude's ~10 min Bash cap) stops
- being displayed as working. DISPLAY-ONLY: nothing is mutated, so any later event restores the row
- instantly; the 60 s sweep re-pushes so a row can age out with no event at all. An **interrupted**
+ nothing — Esc during a tool call, a killed CLI, a slept machine, a dropped SSH. The DECIDER is
+ central: `agent-status-mirror`'s `sweepStaleWorking` (window in `shared/agents/stale.ts`,
+ `WORKING_STALE_MS` 20 min, well past Claude's ~10 min Bash cap) moves the entry off working and
+ fires ONE end edge marked `stale`, which every `onNodeStateChange` consumer honors — the notch
+ drops the row AND the phone's Live Activity ends. The HUD keeps a DISPLAY-ONLY copy of the same
+ check so the capsule never depends on that edge arriving; nothing is mutated, so any later event
+ restores the row instantly, and the 60 s sweep re-pushes so a row can age out with no event at
+ all. An **interrupted**
done (`NodeStateChange.interrupted`, Esc) never lights the green highlight — nothing was
accomplished, so there is nothing to go and read (same rule as the notification path).
- **dismiss** latches the RAW state, so the watchdog flipping a hidden row's display cannot count
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.ts
index 6d4599973..977d0c735 100644
--- a/src/core/agent-status-mirror.test.ts
+++ b/src/core/agent-status-mirror.test.ts
@@ -42,7 +42,8 @@ import {
type MirrorFile,
type MirrorUsage,
type NodeStateChange,
- type NodeNowChange
+ type NodeNowChange,
+ sweepStaleWorking
} from './agent-status-mirror'
// Minimal event factory — only the fields the reducer reads.
@@ -1494,3 +1495,44 @@ describe('isEventUnresolved (presence-hold flush lookup)', () => {
expect(isEventUnresolved('other-node', id)).toBe(false)
})
})
+
+
+describe('stale-working sweep (shared/agents/stale)', () => {
+ it('ends a working node nobody has heard from, once, without an inbox event', () => {
+ _resetForTest()
+ const edges: NodeStateChange[] = []
+ const un = onNodeStateChange((c) => edges.push(c))
+ recordAgentEvent({
+ nodeId: 'n1',
+ agentId: 'claude',
+ kind: 'state',
+ state: 'working',
+ newTurn: true,
+ task: 'do a thing'
+ } as never)
+ const before = _inboxSnapshot().events.length
+ edges.length = 0
+
+ // Not yet stale.
+ expect(sweepStaleWorking(Date.now(), 20 * 60_000)).toEqual([])
+ // Nothing heard for the whole window → presumed gone.
+ const swept = sweepStaleWorking(Date.now() + 21 * 60_000, 20 * 60_000)
+ expect(swept).toEqual(['n1'])
+ expect(edges).toHaveLength(1)
+ expect(edges[0]).toMatchObject({ nodeId: 'n1', event: 'end', state: 'done', stale: true })
+ // Nothing "finished", so the feed (and the push it drives) stays untouched.
+ expect(_inboxSnapshot().events.length).toBe(before)
+ // Idempotent: it is no longer working, so a second sweep says nothing.
+ expect(sweepStaleWorking(Date.now() + 40 * 60_000, 20 * 60_000)).toEqual([])
+ un()
+ })
+
+ it('self-heals — a later event puts the node back to working', () => {
+ _resetForTest()
+ recordAgentEvent({ nodeId: 'n2', agentId: 'claude', kind: 'state', state: 'working' } as never)
+ expect(sweepStaleWorking(Date.now() + 21 * 60_000, 20 * 60_000)).toEqual(['n2'])
+ expect(_snapshot().n2.state).toBe('done')
+ recordAgentEvent({ nodeId: 'n2', agentId: 'claude', kind: 'state', state: 'working', newTurn: true } as never)
+ expect(_snapshot().n2.state).toBe('working')
+ })
+})
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 2c234b053..536adebfe 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -3,6 +3,7 @@ import path from 'path'
import { platform } from './platform'
import type { AgentId } from '@shared/agents/config'
import type { AgentState, NormalizedAgentEvent } from '@shared/agents/normalize'
+import { WORKING_STALE_MS, isStaleWorking } from '@shared/agents/stale'
/**
* Mirrors the live per-node agent status to a small JSON file so an EXTERNAL reader (the
@@ -445,6 +446,9 @@ function newestUnresolved(events: ReadonlyArray<InboxEvent>, nodeId: string): In
// ---- Stateful singleton (production side) --------------------------------------------------
const state = new Map<string, MirrorEntry>()
+/** How often the stale-working sweep runs. The window it enforces is WORKING_STALE_MS. */
+const STALE_SWEEP_MS = 60_000
+let sweepTimer: ReturnType<typeof setInterval> | null = null
let targetFile: string | null = null
let writeTimer: NodeJS.Timeout | null = null
let writeSeq = 0
@@ -513,6 +517,10 @@ export interface NodeStateChange {
/** approval needsYou only: the deterministic hook-reply ticket from the just-produced approval
* event, letting an intent answer the held hook. Absent otherwise. */
pendingId?: string
+ /** done only: this 'end' was produced by the stale-working SWEEP, not by the session itself —
+ * nobody heard from a `working` node for `WORKING_STALE_MS`, so it is presumed gone (see
+ * shared/agents/stale.ts). Like `interrupted`, it must never be celebrated as a completion. */
+ stale?: boolean
/** done only: the turn ended because the user interrupted it (Esc/Ctrl-C) rather than finishing.
* Consumers that celebrate a completion (notification, the notch HUD's "finished, unseen"
* highlight) skip it — nothing was accomplished, so there is nothing to go and read. */
@@ -961,6 +969,7 @@ function loadPersisted(file: string): void {
export function initAgentStatusMirror(filePath?: string): void {
targetFile = filePath ?? path.join(platform().userDataDir, 'agent-status.json')
loadPersisted(targetFile)
+ startStaleSweep()
}
function resolveFile(): string | null {
@@ -1294,6 +1303,53 @@ export function ackDone(nodeId: string): void {
scheduleWrite()
}
+/**
+ * The one place that decides a `working` session is gone (shared/agents/stale.ts).
+ *
+ * For each node that has been `working` with no event for `staleMs`: move the entry off working and
+ * fire ONE synthetic end edge, marked `stale` so no consumer treats it as an achievement. Every
+ * surface that already listens to `onNodeStateChange` inherits the fix — the notch drops the row,
+ * the phone's Live Activity ENDS instead of sitting on the Lock Screen until iOS's 8 h staleness.
+ *
+ * Deliberately NOT done here: no inbox event is pushed (nothing finished, so there is nothing to
+ * show in the feed or to notify about), and `updatedAt` is left alone — falsifying it would both
+ * rewrite history and arm the 3 s done-holdoff, which would swallow a real event arriving right
+ * after a wrong guess. The sweep is self-healing: one later event puts the node back to `working`.
+ *
+ * Returns the swept node ids (empty when nothing was stale). `now`/`staleMs` injected for tests.
+ */
+export function sweepStaleWorking(
+ now: number = Date.now(),
+ staleMs: number = WORKING_STALE_MS
+): string[] {
+ const swept: string[] = []
+ for (const [nodeId, e] of state) {
+ if (!isStaleWorking(e.state, e.updatedAt, now, staleMs)) continue
+ state.set(nodeId, { ...e, state: 'done' })
+ clearActivity(nodeId, now)
+ swept.push(nodeId)
+ fireNodeStateChange({
+ nodeId,
+ ...(e.agentId ? { agentId: e.agentId } : {}),
+ ...(e.sessionId ? { sessionId: e.sessionId } : {}),
+ event: 'end',
+ state: 'done',
+ message: 'Stopped',
+ stale: true,
+ ts: now
+ })
+ }
+ return swept
+}
+
+function startStaleSweep(): void {
+ if (sweepTimer) return
+ sweepTimer = setInterval(() => {
+ if (sweepStaleWorking().length > 0) scheduleWrite()
+ }, STALE_SWEEP_MS)
+ sweepTimer.unref?.()
+}
+
function scheduleWrite(): void {
if (writeTimer) return
writeTimer = setTimeout(() => {
@@ -1336,6 +1392,8 @@ export async function flush(): Promise<void> {
/** Reset all module state (in-memory map + config + listeners + inbox). Test-only. */
export function _resetForTest(): void {
state.clear()
+ if (sweepTimer) clearInterval(sweepTimer)
+ sweepTimer = null
targetFile = null
if (writeTimer) clearTimeout(writeTimer)
writeTimer = null
diff --git a/src/main/notch-hud-model.ts b/src/main/notch-hud-model.ts
index 9ec5e50ac..18af985a7 100644
--- a/src/main/notch-hud-model.ts
+++ b/src/main/notch-hud-model.ts
@@ -9,21 +9,18 @@
import type { NormalizedAgentEvent, AgentState } from '../shared/agents/normalize'
import type { NodeStateChange, NodeNowChange, MirrorFile } from '../core/agent-status-mirror'
+import { WORKING_STALE_MS } from '@shared/agents/stale'
/** A node dropped once it's gone from the mirror AND has been idle longer than this. */
export const HUD_STALE_DROP_MS = 6 * 60 * 60 * 1000
/**
- * A `working` node with NO event for this long stops being displayed as working.
- *
- * A session leaves `working` only when something says so — and some exits say nothing: an Esc
- * during a tool call, a killed CLI, a machine that slept, an SSH drop. The node then walks its
- * mascot forever. This is the watchdog, and it is deliberately DISPLAY-ONLY: the state is not
- * mutated, so any later event (a tool result, a new turn, a mirror flush) brings the row straight
- * back. 20 min is well past a real gap between hook events — Claude's Bash tool caps out around 10
- * — so a genuinely long turn is never hidden.
+ * The HUD's belt-and-braces copy of the stale-working rule. The DECIDER is the mirror's sweep
+ * (`sweepStaleWorking`), which fires a synthetic end edge every surface honors; this display-only
+ * check just means the capsule never depends on that edge arriving. Same window, one constant
+ * (shared/agents/stale.ts) — nothing is mutated, so any later event restores the row.
*/
-export const WORKING_STALE_MS = 20 * 60 * 1000
+export { WORKING_STALE_MS }
/** The phone-facing bucket the HUD colors rows by. `idle` = a seen/finished session. */
export type HudRowState = 'working' | 'needsYou' | 'done' | 'idle'
@@ -154,9 +151,9 @@ export function createHudModel(): HudModel {
a.doneSeen = false
} else if (c.state === 'done') {
// New done → unseen (highlight it) unless this end was an explicit read-ack, or the turn was
- // INTERRUPTED (Esc): nothing was accomplished, so there is nothing to go and read. Same rule
- // the notification path uses.
- a.doneSeen = c.ack === true || c.interrupted === true
+ // INTERRUPTED (Esc) / swept as STALE: nothing was accomplished, so there is nothing to go and
+ // read. Same rule the notification path uses.
+ a.doneSeen = c.ack === true || c.interrupted === true || c.stale === true
}
}
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index b2a6c21c3..5eec6d893 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -1,4 +1,5 @@
import { create, type StoreApi, type UseBoundStore } from 'zustand'
+import { WORKING_STALE_MS } from '@shared/agents/stale'
import type { AgentId } from '@shared/agents/config'
import type { AgentState } from '@shared/agents/normalize'
import type { NodeTerminalApi } from '@shared/types'
@@ -120,7 +121,10 @@ export const DONE_HOLDOFF_MS = 3000
// all for this long decays to idle. Long on purpose:
// a single silent tool run (e.g. a long build) fires no hooks between Pre- and PostToolUse,
// so anything shorter would flip genuinely-running turns to idle.
-export const STALE_WORKING_MS = 30 * 60_000
+// One rule, three surfaces — the window lives in shared/agents/stale.ts and the mirror's sweep is
+// the decider (it fires a synthetic end edge). This local sweeper stays as the renderer's own
+// safety net for a badge whose events never reached the mirror.
+export const STALE_WORKING_MS = WORKING_STALE_MS
// Esc/Ctrl-C interrupt inference: how long to wait for a hook event before concluding the
// turn was cancelled without a final Stop.
export const INTERRUPT_SETTLE_MS = 1500
diff --git a/src/shared/agents/stale.ts b/src/shared/agents/stale.ts
new file mode 100644
index 000000000..8c9139cb8
--- /dev/null
+++ b/src/shared/agents/stale.ts
@@ -0,0 +1,31 @@
+// ONE rule, three surfaces.
+//
+// A session leaves `working` only when something says so — and some exits say nothing at all: Esc
+// during a tool call (Claude's Stop hook never runs), a killed CLI, a slept machine, a dropped SSH.
+// Whatever is watching then shows a session working forever: the node badge's RUNNING, the notch
+// capsule's walking mascot, and — worst, because it sits on a Lock Screen you aren't looking at —
+// the phone's Live Activity.
+//
+// Each surface used to invent its own timeout (30 min in the renderer store, 20 in the notch, none
+// at all on the phone). This module is the single number, and `core/agent-status-mirror.ts` is the
+// single DECIDER: its sweep fires one synthetic end edge per stale node, which every consumer of
+// `onNodeStateChange` already knows how to handle.
+
+/**
+ * How long a `working` node may go without any event before it is presumed gone.
+ *
+ * Well past a real gap between hook events — Claude's Bash tool caps out around 10 minutes, and
+ * every tool call refreshes the entry — so a genuinely long turn is never swept. And the sweep is
+ * self-healing anyway: one later event puts the node straight back into `working`.
+ */
+export const WORKING_STALE_MS = 20 * 60_000
+
+/** Has a `working` node gone quiet for longer than the window? Pure; `now` is injected. */
+export function isStaleWorking(
+ state: string | undefined,
+ updatedAt: number,
+ now: number,
+ staleMs: number = WORKING_STALE_MS
+): boolean {
+ return state === 'working' && now - updatedAt > staleMs
+}