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(power): close the two keep-awake edges review found — session-boundary leak + relaunch seed

enes9057e812cdba
diff --git a/src/core/agent-status-mirror.restart.test.ts b/src/core/agent-status-mirror.restart.test.ts
index 377e06fe1..582a75119 100644
--- a/src/core/agent-status-mirror.restart.test.ts
+++ b/src/core/agent-status-mirror.restart.test.ts
@@ -18,6 +18,7 @@ import {
_resetForTest,
_inboxSnapshot,
_snapshot,
+ workingNodeIds,
type InboxEvent
} from './agent-status-mirror'
@@ -127,4 +128,18 @@ describe('agent-status mirror — restart survival of the done dedup', () => {
expect(Object.keys(_snapshot())).toHaveLength(0)
expect(_inboxSnapshot().events).toHaveLength(0)
})
+
+ it('workingNodeIds() sees a restored working entry (keep-awake reseeds from it at boot)', async () => {
+ // The restore deliberately fires NO edges, so an edge-driven consumer starts blind; the
+ // tmux-backed run it describes is still going. workingNodeIds() is the seam that lets the
+ // main shell reseed keep-awake — without it an app relaunch mid-run drops the assertion
+ // until the next turn boundary.
+ initAgentStatusMirror(file)
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ nodeId: 'n2', state: 'done' }))
+
+ await restart()
+
+ expect(workingNodeIds()).toEqual(['n1'])
+ })
})
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.ts
index 06948aeaf..d9f1e14cd 100644
--- a/src/core/agent-status-mirror.test.ts
+++ b/src/core/agent-status-mirror.test.ts
@@ -1307,6 +1307,27 @@ describe('onNodeStateChange seam', () => {
expect('pendingId' in c).toBe(false)
}
})
+
+ it('a session boundary mid-working fires a not-a-completion end (the exit the sweep cannot see)', () => {
+ // SessionStart/SessionEnd reset the entry to idle, which takes it out of the stale sweep's
+ // jurisdiction (isStaleWorking wants state === 'working') — so without this edge every
+ // edge-driven consumer (Live Activity, keep-awake) would hold a phantom worker forever.
+ const seen: NodeStateChange[] = []
+ onNodeStateChange((c) => seen.push(c))
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ const before = _inboxSnapshot().events.length
+ recordAgentEvent(ev({ kind: 'session', sessionPhase: 'end' }))
+ const ends = seen.filter((c) => c.event === 'end')
+ expect(ends).toHaveLength(1)
+ expect(ends[0]).toMatchObject({ state: 'done', message: 'Stopped', interrupted: true })
+ // Like the sweep: no inbox card — nothing finished, nothing to read.
+ expect(_inboxSnapshot().events.length).toBe(before)
+ // And it is guarded on prevState === 'working': a session boundary on an idle/done node
+ // (the common clean-start case) must stay silent.
+ seen.length = 0
+ recordAgentEvent(ev({ kind: 'session', sessionPhase: 'start' }))
+ expect(seen).toHaveLength(0)
+ })
})
describe('onNodeNowChange seam', () => {
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 6ec7cc852..a71e6160c 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -585,7 +585,9 @@ export interface NodeStateChange {
* 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.
+ /** done only: the turn ended because the user interrupted it (Esc/Ctrl-C) rather than
+ * finishing — or a session boundary (SessionStart/SessionEnd) reset the node while it was
+ * still `working`, which is the same story: the run stopped without producing anything.
* 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. */
interrupted?: boolean
@@ -1126,6 +1128,21 @@ function produceInboxFromState(
}
const baseEvent = { ts: now, nodeId, agentId: ev.agentId, sessionId: ev.sessionId }
const stateBase = { nodeId, agentId: ev.agentId, sessionId: ev.sessionId, ts: now }
+ // A session boundary (SessionStart/SessionEnd) resets a `working` node to idle with no done
+ // edge of its own (reduceEntry clears the state) — yet every edge-driven consumer (the phone's
+ // Live Activity, keep-awake's power assertion) still believes the node is working, and the
+ // stale sweep can never correct them: it only watches entries still marked `working`, and this
+ // one just left that set. Fire the same not-a-completion end the sweep fires, so the seam sees
+ // every exit. Like the sweep, deliberately NO inbox event — nothing finished.
+ if (ev.kind === 'session' && prevState === 'working') {
+ fireNodeStateChange({
+ ...stateBase,
+ event: 'end',
+ state: 'done',
+ message: 'Stopped',
+ interrupted: true
+ })
+ }
// Working START edge (fresh turn / session open): a Live Activity begins here. reduceEntry's
// done-holdoff means a held-off late working keeps `nextState === 'done'`, so it never reaches
// here — no spurious 'start'.
@@ -1418,6 +1435,17 @@ export function nodeState(nodeId: string): AgentState | undefined {
return state.get(nodeId)?.state
}
+/** Node ids currently `working` — including entries restored by loadPersisted, which fires no
+ * edges by design. Read-only peek for the shells: keep-awake seeds its tracker from this at
+ * boot, because a tmux-backed run survives an app relaunch and would otherwise go unprotected
+ * until its next turn boundary. A restored entry that is in fact gone is released by the stale
+ * sweep's synthetic end within its next tick. */
+export function workingNodeIds(): string[] {
+ const out: string[] = []
+ for (const [nodeId, e] of state) if (e.state === 'working') out.push(nodeId)
+ return out
+}
+
/** The entries the session-name sweep walks: id + what it needs to resolve and dedupe. */
export function sessionNameSweepEntries(): {
nodeId: string
diff --git a/src/core/keep-awake.ts b/src/core/keep-awake.ts
index a2a2f6369..245ca9b85 100644
--- a/src/core/keep-awake.ts
+++ b/src/core/keep-awake.ts
@@ -13,6 +13,9 @@
// stale sweep (`sweepStaleWorking`, shared/agents/stale.ts WORKING_STALE_MS), which fires a
// synthetic `end` edge per silent node through the SAME onNodeStateChange seam this tracker
// folds — worst case the assertion outlives the last real work by that window, never forever.
+// A session boundary (SessionStart/SessionEnd) mid-`working` is the one exit the sweep cannot
+// see — it resets the mirror entry to idle, out of the sweep's jurisdiction — so the mirror
+// fires the same synthetic end on that path itself (produceInboxFromState's session guard).
//
// Electron-free (src/core): the actual powerSaveBlocker lives behind the injected `blocker` seam
// (template: session-budget.ts); the thin shell in src/main/keep-awake.ts binds it.
diff --git a/src/main/index.ts b/src/main/index.ts
index e449a2d71..8f16e7fb8 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -62,7 +62,8 @@ import {
setNodeSessionName,
sessionNameSweepEntries,
nodeState,
- nodeSessionName
+ nodeSessionName,
+ workingNodeIds
} from '../core/agent-status-mirror'
import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
import { createGrantsAccessor } from '../core/push-grants'
@@ -907,6 +908,14 @@ app.whenReady().then(async () => {
})
onNodeStateChange((c) => keepAwake?.onChange(c))
settingsStore.onChange(() => keepAwake?.refresh())
+ // Seed from the restored mirror: an app relaunch (auto-update, crash) does not stop a
+ // tmux-backed run, and loadPersisted deliberately restores its `working` entry WITHOUT firing
+ // edges — so without this the machine would go unprotected until the run's next turn boundary.
+ // The tracker applies the same isRemoteNode/enabled gates as a live edge, and an entry that is
+ // in fact gone is released by the stale sweep's synthetic end within its next tick.
+ for (const nodeId of workingNodeIds()) {
+ keepAwake.onChange({ nodeId, event: 'start', state: 'working' })
+ }
// Advertise launch settings to the mobile companion through the mirror. The provider is
// consulted at every flush (heartbeat ≤60s), so a settings change propagates without extra
// plumbing. Caps arrive async: re-flush once the memoized probe answers.
@@ -1969,8 +1978,11 @@ let quitFlushed = false
app.on('before-quit', (e) => {
quitting = true // from here on, window close-events must NOT be turned into hide
destroyNotchHud()
- // Electron releases power assertions at exit anyway; disposing keeps the hold/release log honest.
+ // Electron releases power assertions at exit anyway; disposing keeps the hold/release log
+ // honest. Clearing the ref too keeps a hook edge that lands during the quit flush (the pty
+ // teardown window below) from re-holding an assertion nothing will ever release.
keepAwake?.dispose()
+ keepAwake = undefined
workspaceWatcher.dispose()
if (quitFlushed) {
// Second pass (the deferred app.quit() below): the flush had its chance — drop the masters.