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(push): a Live Activity can no longer be left stuck on "Working"
enes5282cd3f0b9d
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.tsindex 6bd0771d5..5cf25d076 100644--- a/src/core/agent-status-mirror.test.ts+++ b/src/core/agent-status-mirror.test.ts@@ -492,6 +492,63 @@ describe('inbox event production (via recordAgentEvent)', () => {expect(_inboxSnapshot().events[0].resolved).toBe(true)})+ // A CLI that exits mid-turn (`/exit`, Ctrl-C, a crash) is the one transition that MEANS "this+ // session is over", and it used to emit nothing: `reduceEntry` resets it to `state: undefined`+ // while every `end` was keyed on the edge into `done`. It escaped the rescue too, because+ // `sweepStaleWorking` matches `state === 'working'` — which the reset had just stopped being+ // true. The phone was left holding a card nothing would ever end.+ describe('a session that ends mid-turn ends its Live Activity', () => {+ const edgesFor = (fn: () => void): NodeStateChange[] => {+ const edges: NodeStateChange[] = []+ const un = onNodeStateChange((c) => edges.push(c))+ fn()+ un()+ return edges+ }++ it('emits an end when the agent quits while WORKING', () => {+ recordAgentEvent(ev({ state: 'working', newTurn: true }))+ const edges = edgesFor(() => recordAgentEvent(ev({ kind: 'session', sessionPhase: 'end' })))+ expect(edges).toHaveLength(1)+ expect(edges[0]).toMatchObject({ event: 'end', state: 'done' })+ })++ it('emits an end when the agent quits while it was BLOCKED on an approval', () => {+ // The worst case: the card carries Approve/Deny buttons for a hook ticket that is now gone.+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write' }))+ const edges = edgesFor(() => recordAgentEvent(ev({ kind: 'session', sessionPhase: 'end' })))+ expect(edges).toHaveLength(1)+ expect(edges[0]).toMatchObject({ event: 'end', state: 'done' })+ })++ it('stays silent when the turn already finished — the done edge spoke for it', () => {+ recordAgentEvent(ev({ state: 'working', newTurn: true }))+ recordAgentEvent(ev({ state: 'done' }))+ const edges = edgesFor(() => recordAgentEvent(ev({ kind: 'session', sessionPhase: 'end' })))+ expect(edges).toEqual([])+ })++ it('stays silent for an idle node and for a session START', () => {+ // Nothing was live → nothing to end.+ expect(edgesFor(() => recordAgentEvent(ev({ kind: 'session', sessionPhase: 'end' })))).toEqual(+ []+ )+ // A SessionStart also resets to idle, but ending there would kill the activity of the turn+ // that is just beginning.+ recordAgentEvent(ev({ state: 'working', newTurn: true }))+ expect(edgesFor(() => recordAgentEvent(ev({ kind: 'session', sessionPhase: 'start' })))).toEqual(+ []+ )+ })++ it('adds no inbox card — the session going away is not news for the feed', () => {+ recordAgentEvent(ev({ state: 'working', newTurn: true }))+ const before = _inboxSnapshot().events.length+ recordAgentEvent(ev({ kind: 'session', sessionPhase: 'end' }))+ expect(_inboxSnapshot().events.length).toBe(before)+ })+ })+it('synthetic "answered" working transition resolves the open approval and adds no new ask', () => {// The deterministic-approval answered signal (built exactly as the hook POST / desktop optimistic// flip does) is a working state → it goes through the same blocked→working path a normal resumediff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex 8eaf70d3a..a22ee5af2 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -1258,6 +1258,39 @@ function produceInboxFromState(})// A finished turn is no longer "doing" anything — clear its live activity line.clearActivity(nodeId, now)+ } else if (+ nextState === undefined &&+ prevState !== undefined &&+ prevState !== 'done' &&+ ev.kind === 'session' &&+ ev.sessionPhase === 'end'+ ) {+ // The CLI EXITED mid-turn (`/exit`, Ctrl-C, a crash) — the one transition that means "this+ // session is over", and the only one that used to emit nothing at all.+ //+ // `reduceEntry` resets a session event to `state: undefined`, while every `end` above is keyed+ // on the edge INTO `done` — so a node that was working or blocked when its agent quit produced+ // none. It escaped the rescue too: `sweepStaleWorking` matches `state === 'working'`+ // (isStaleWorking), which the reset had just stopped being true, so the 20-minute net written+ // for exactly this failure was structurally bypassed. The phone was left holding a Live+ // Activity nothing would ever end — a Lock Screen card stuck on "Working…", or worse on+ // "Needs you" with Approve/Deny buttons whose hook ticket no longer exists — until iOS's own+ // 8 h staleness.+ //+ // Deliberately narrow: only a session END (a SessionStart also resets to idle, and ending a+ // card there would kill the activity of the turn just beginning), only when the node was+ // actually mid-turn, and only when the done edge has not already spoken for it.+ //+ // No inbox card: a finished turn's card comes from the `done` edge, and this transition means+ // the session went away, which is not itself news for the feed — the node's pending+ // approval/question cards were already resolved by the leave-blocked/waiting branch above.+ fireNodeStateChange({+ ...stateBase,+ event: 'end',+ state: 'done',+ message: 'Ended'+ })+ clearActivity(nodeId, now)}}diff --git a/src/core/push-notify.test.ts b/src/core/push-notify.test.tsindex 6c9750df5..594a96005 100644--- a/src/core/push-notify.test.ts+++ b/src/core/push-notify.test.ts@@ -824,6 +824,105 @@ describe('createLiveUpdatePush', () => {h.stop()})+ // A now-tick carries no state of its own, so it used to hardcode `state: 'working'` — and it can+ // sit parked for the whole coalesce window. Two producers fire one at exactly the wrong moment+ // (the raw Stop hook clears the activity; the context tail's 1 s poll lands the turn's final+ // usage record), so a tick would land AFTER the end and flip the island back to Working, with no+ // further edge left to end it.+ describe('a coalesced tick can never resurrect a finished session', () => {+ it('drops a PARKED tick when the state edge that supersedes it goes out', async () => {+ const { h, st, nw } = wire()+ clock = 0+ nw.emit({ nodeId: 'a', activity: 'Editing a.ts', ts: 0 }) // leading edge → sent+ await vi.advanceTimersByTimeAsync(1000)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ // A tick parked inside the window…+ clock = 5000+ nw.emit({ nodeId: 'a', activity: 'Editing b.ts', ts: 5000 })+ // …then the turn ends.+ st.emit({ nodeId: 'a', event: 'end', state: 'done', ts: 6000 } as NodeStateChange)+ await vi.advanceTimersByTimeAsync(1000)+ expect(liveBodyOf(1).updates[0]).toMatchObject({ event: 'end', state: 'done' })+ // Past the coalesce window: the parked tick must NOT flush behind the end.+ clock = 30000+ await vi.advanceTimersByTimeAsync(30000)+ expect(fetchMock).toHaveBeenCalledTimes(2)+ h.stop()+ })++ it('drops a tick that arrives AFTER the end (the 1 s context tail lands late)', async () => {+ const { h, st, nw } = wire()+ clock = 0+ st.emit({ nodeId: 'a', event: 'end', state: 'done', ts: 0 } as NodeStateChange)+ await vi.advanceTimersByTimeAsync(1000)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ clock = 2000+ nw.emit({ nodeId: 'a', activity: 'Editing late.ts', contextPercent: 42, ts: 2000 })+ await vi.advanceTimersByTimeAsync(30000)+ expect(fetchMock).toHaveBeenCalledTimes(1) // nothing followed the end+ h.stop()+ })++ it('also refuses a tick once the node is NEEDS-YOU (it would drop the buttons)', async () => {+ const { h, st, nw } = wire()+ clock = 0+ st.emit({+ nodeId: 'a',+ event: 'update',+ state: 'needsYou',+ kind: 'approval',+ pendingId: 'p1',+ ts: 0+ } as NodeStateChange)+ await vi.advanceTimersByTimeAsync(1000)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ clock = 2000+ nw.emit({ nodeId: 'a', activity: 'Running tests', ts: 2000 })+ await vi.advanceTimersByTimeAsync(30000)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ h.stop()+ })++ it('a working node keeps ticking, and a re-entry into working resumes them', async () => {+ const { h, st, nw } = wire()+ clock = 0+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 0 } as NodeStateChange)+ await vi.advanceTimersByTimeAsync(1000)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ // Still working → the tick goes out as before.+ clock = 2000+ nw.emit({ nodeId: 'a', activity: 'Editing a.ts', ts: 2000 })+ await vi.advanceTimersByTimeAsync(1000)+ expect(fetchMock).toHaveBeenCalledTimes(2)+ expect(liveBodyOf(1).updates[0]).toMatchObject({ state: 'working', activity: 'Editing a.ts' })+ // needsYou silences ticks…+ clock = 30000+ st.emit({ nodeId: 'a', event: 'update', state: 'needsYou', ts: 30000 } as NodeStateChange)+ await vi.advanceTimersByTimeAsync(1000)+ expect(fetchMock).toHaveBeenCalledTimes(3)+ // …and answering it (back to working) lets them through again.+ clock = 60000+ st.emit({ nodeId: 'a', event: 'update', state: 'working', ts: 60000 } as NodeStateChange)+ await vi.advanceTimersByTimeAsync(1000)+ clock = 90000+ nw.emit({ nodeId: 'a', activity: 'Editing c.ts', ts: 90000 })+ await vi.advanceTimersByTimeAsync(1000)+ expect(fetchMock).toHaveBeenCalledTimes(5)+ expect(liveBodyOf(4).updates[0]).toMatchObject({ state: 'working', activity: 'Editing c.ts' })+ h.stop()+ })++ it('a node we have seen no edge for still ticks (unchanged pre-edge behaviour)', async () => {+ const { h, nw } = wire()+ clock = 0+ nw.emit({ nodeId: 'never-edged', activity: 'Editing a.ts', ts: 0 })+ await vi.advanceTimersByTimeAsync(1000)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(liveBodyOf(0).updates[0]).toMatchObject({ state: 'working' })+ h.stop()+ })+ })+it('a state edge is NOT subject to the now-coalesce window', async () => {const { h, st, nw } = wire()clock = 0diff --git a/src/core/push-notify.ts b/src/core/push-notify.tsindex 75bc998f8..181a6f4e7 100644--- a/src/core/push-notify.ts+++ b/src/core/push-notify.ts@@ -440,6 +440,21 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {// Per-node coalescing of activity/context ticks.const lastNowSentAt = new Map<string, number>()const pendingNow = new Map<string, NodeNowChange>()+ /**+ * The last STATE we told the phone about, per node. A now-tick carries no state of its own+ * (`NodeNowChange` has none — the notch HUD, the other consumer of that seam, correctly never+ * reads one), yet it has to send something, and it used to hardcode `working`. Two producers+ * fire a tick at exactly the wrong moment — the raw `Stop` hook clears the activity, and the+ * context tail's 1 s poll lands the turn's final usage record — so a tick would be parked for up+ * to `coalesceMs` and then assert "working" AFTER the end had already gone out, flipping the+ * island back to Working with nothing left to end it.+ *+ * So ticks are now told what the node's state actually is, and are dropped entirely once it is+ * no longer working. Undefined = we have not seen an edge for this node yet; a tick then still+ * goes out as working, which is the pre-existing behaviour for a node whose activity we learn+ * about before its first edge.+ */+ const lastStateSent = new Map<string, NodeStateChange['state']>()let batchTimer: ReturnType<typeof setTimeout> | null = nulllet coalesceTimer: ReturnType<typeof setTimeout> | null = null@@ -479,6 +494,11 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {function onStateChange(c: NodeStateChange): void {if (!resolveTarget()) return+ // This edge is newer than anything coalescing for the node, and a tick asserts `working` —+ // so a parked one must never be allowed to land after it and undo it. Drop it and record the+ // state, which also gates any tick that arrives later in the same turn (see lastStateSent).+ lastStateSent.set(c.nodeId, c.state)+ pendingNow.delete(c.nodeId)const title = nodeTitleOf(c.nodeId)// kind/options/multiSelect/pendingId ride only a needsYou edge (spec:// interactive-push-live-activities addendum) — belt-and-braces gate on state so a working/done@@ -549,6 +569,12 @@ export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {function onNowChange(c: NodeNowChange): void {if (!resolveTarget()) return+ // A tick describes work in progress. Once the node has left `working` (needs-you, or an end)+ // there is nothing for it to say, and saying `working` would contradict the edge we just sent.+ if ((lastStateSent.get(c.nodeId) ?? 'working') !== 'working') {+ pendingNow.delete(c.nodeId)+ return+ }const t = now()const last = lastNowSentAt.get(c.nodeId) ?? -Infinityif (t - last >= coalesceMs) {