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.

feat(power): keep the machine awake while local agents work

enesec3cf4a33f73
diff --git a/src/core/keep-awake.test.ts b/src/core/keep-awake.test.ts
new file mode 100644
index 000000000..1f7a9df40
--- /dev/null
+++ b/src/core/keep-awake.test.ts
@@ -0,0 +1,128 @@
+import { describe, expect, it } from 'vitest'
+import { createKeepAwake, type KeepAwakeEdge, type KeepAwakeOpts } from './keep-awake'
+
+/** A tracker over counting seams. `enabled`/`remote` are live-mutable via the returned handle. */
+function harness(over: { enabled?: boolean; remote?: (id: string) => boolean } = {}) {
+ const calls = { start: 0, stop: 0 }
+ const state = { enabled: over.enabled ?? true }
+ const opts: KeepAwakeOpts = {
+ blocker: {
+ start: () => void calls.start++,
+ stop: () => void calls.stop++
+ },
+ enabled: () => state.enabled,
+ isRemoteNode: over.remote ?? (() => false),
+ log: () => {}
+ }
+ return { tracker: createKeepAwake(opts), calls, state }
+}
+
+const edge = (nodeId: string, event: KeepAwakeEdge['event'], state: string): KeepAwakeEdge => ({
+ nodeId,
+ event,
+ state
+})
+
+describe('keep-awake tracker', () => {
+ it('holds on the first local working edge, and only once across several working nodes', () => {
+ const { tracker, calls } = harness()
+ tracker.onChange(edge('a', 'start', 'working'))
+ expect(calls.start).toBe(1)
+ expect(tracker.holding()).toBe(true)
+ // A second working node (and a repeat edge for the first) must not start a second assertion.
+ tracker.onChange(edge('b', 'start', 'working'))
+ tracker.onChange(edge('a', 'update', 'working'))
+ expect(calls.start).toBe(1)
+ expect(calls.stop).toBe(0)
+ })
+
+ it('releases when the LAST local node ends — not before', () => {
+ const { tracker, calls } = harness()
+ tracker.onChange(edge('a', 'start', 'working'))
+ tracker.onChange(edge('b', 'start', 'working'))
+ tracker.onChange(edge('a', 'end', 'done'))
+ expect(calls.stop).toBe(0) // b still working
+ tracker.onChange(edge('b', 'end', 'done'))
+ expect(calls.stop).toBe(1)
+ expect(tracker.holding()).toBe(false)
+ })
+
+ it('a needsYou edge releases just like an end — waiting on the human is not work', () => {
+ const { tracker, calls } = harness()
+ tracker.onChange(edge('a', 'start', 'working'))
+ // The mirror sends needsYou as event 'update' with state 'needsYou' — event alone must not
+ // keep the node in the working set.
+ tracker.onChange(edge('a', 'update', 'needsYou'))
+ expect(calls.stop).toBe(1)
+ expect(tracker.holding()).toBe(false)
+ // Answering resumes work: the next working edge holds again.
+ tracker.onChange(edge('a', 'start', 'working'))
+ expect(calls.start).toBe(2)
+ })
+
+ it('remote (SSH-homed) nodes never hold', () => {
+ const { tracker, calls } = harness({ remote: (id) => id.startsWith('ssh-') })
+ tracker.onChange(edge('ssh-x', 'start', 'working'))
+ tracker.onChange(edge('ssh-x', 'update', 'working'))
+ expect(calls.start).toBe(0)
+ expect(tracker.holding()).toBe(false)
+ // A local node alongside still holds; the remote node's end does not release it.
+ tracker.onChange(edge('local-y', 'start', 'working'))
+ expect(calls.start).toBe(1)
+ tracker.onChange(edge('ssh-x', 'end', 'done'))
+ expect(calls.stop).toBe(0)
+ })
+
+ it('disabled: edges never hold; enabling + refresh() mid-run holds without a new edge', () => {
+ const { tracker, calls, state } = harness({ enabled: false })
+ tracker.onChange(edge('a', 'start', 'working'))
+ expect(calls.start).toBe(0)
+ // The working set kept folding while disabled — the live toggle takes effect immediately.
+ state.enabled = true
+ tracker.refresh()
+ expect(calls.start).toBe(1)
+ expect(tracker.holding()).toBe(true)
+ // And back: disabling releases while the node is still working.
+ state.enabled = false
+ tracker.refresh()
+ expect(calls.stop).toBe(1)
+ expect(tracker.holding()).toBe(false)
+ // Re-enabling again re-holds from the still-folded set.
+ state.enabled = true
+ tracker.refresh()
+ expect(calls.start).toBe(2)
+ })
+
+ it('end for an unknown node / double-end never calls stop() when not holding (no underflow)', () => {
+ const { tracker, calls } = harness()
+ tracker.onChange(edge('ghost', 'end', 'done'))
+ expect(calls.stop).toBe(0)
+ tracker.onChange(edge('a', 'start', 'working'))
+ tracker.onChange(edge('a', 'end', 'done'))
+ tracker.onChange(edge('a', 'end', 'done')) // duplicate end (e.g. natural end + ackDone re-send)
+ expect(calls.stop).toBe(1)
+ // The duplicate must not have poisoned the count: a new working node holds again.
+ tracker.onChange(edge('b', 'start', 'working'))
+ expect(calls.start).toBe(2)
+ })
+
+ it('dispose() while holding stops exactly once; while not holding, not at all', () => {
+ const { tracker, calls } = harness()
+ tracker.onChange(edge('a', 'start', 'working'))
+ tracker.dispose()
+ expect(calls.stop).toBe(1)
+ expect(tracker.holding()).toBe(false)
+ tracker.dispose()
+ expect(calls.stop).toBe(1)
+ })
+
+ it('the stale sweep synthetic end releases — the leak backstop story', () => {
+ const { tracker, calls } = harness()
+ tracker.onChange(edge('a', 'start', 'working'))
+ // sweepStaleWorking (agent-status-mirror) fires exactly this shape for a node silent past
+ // WORKING_STALE_MS: event 'end', state 'done' (plus stale:true, which the tracker ignores).
+ tracker.onChange({ ...edge('a', 'end', 'done'), stale: true } as KeepAwakeEdge)
+ expect(calls.stop).toBe(1)
+ expect(tracker.holding()).toBe(false)
+ })
+})
diff --git a/src/core/keep-awake.ts b/src/core/keep-awake.ts
new file mode 100644
index 000000000..a2a2f6369
--- /dev/null
+++ b/src/core/keep-awake.ts
@@ -0,0 +1,107 @@
+// Keep awake while agents work: hold an idle-sleep power assertion while at least one LOCAL
+// agent node is actively `working`, and release it the moment the last one stops — so a long
+// unattended run survives the laptop's Energy Saver settings without turning nodeterm into an
+// app that pins the machine awake for as long as it is open.
+//
+// Spec: docs/superpowers/specs/2026-08-18-keep-awake-design.md. Scope rules:
+// - LOCAL nodes only. The mirror carries SSH-homed nodes too (hook events tunnel in), but their
+// work happens on the remote host — they must never keep THIS machine awake.
+// - `working` only. `needsYou` (waiting on the human) and `done` both RELEASE: a question nobody
+// answers overnight must not hold the laptop out of sleep.
+// - Assertion leaks are impossible by construction: every exit that never sends its own edge
+// (crash, Esc mid-tool, dropped SSH, node deleted while working) is covered by the mirror's
+// 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.
+//
+// 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.
+
+/** The power-assertion seam. Both calls are edge-triggered by the tracker (never re-entrant):
+ * `start()` fires only on the not-holding→holding transition, `stop()` only on the reverse. */
+export interface KeepAwakeBlocker {
+ start(): void
+ stop(): void
+}
+
+/** One main-state edge as the tracker needs it — a structural subset of the mirror's
+ * NodeStateChange (core/agent-status-mirror.ts), so the full edge object folds in unchanged. */
+export interface KeepAwakeEdge {
+ nodeId: string
+ event: 'start' | 'update' | 'end'
+ /** The phone-facing bucket: 'working' | 'needsYou' | 'done'. Anything but 'working' releases. */
+ state: string
+}
+
+export interface KeepAwakeOpts {
+ blocker: KeepAwakeBlocker
+ /** Reads the setting LIVE (settings.keepAwakeWhileAgentsWork) — never cached here. */
+ enabled(): boolean
+ /** True for nodes homed on an SSH project — their work isn't on this machine. */
+ isRemoteNode(nodeId: string): boolean
+ log?(msg: string): void
+}
+
+export interface KeepAwakeTracker {
+ /** Fold one NodeStateChange edge (agent-status-mirror). */
+ onChange(c: KeepAwakeEdge): void
+ /** Re-evaluate after a settings change (live toggle). */
+ refresh(): void
+ /** Currently holding the assertion? (tests + future UI) */
+ holding(): boolean
+ /** Release + clear (quit path). */
+ dispose(): void
+}
+
+/**
+ * The tracker: folds edges into a set of currently-working LOCAL node ids and drives the blocker
+ * on exactly two transitions — empty↔non-empty and enabled↔disabled. Idempotence lives HERE, not
+ * in the caller: however many edges arrive, the underlying blocker sees one start per hold.
+ *
+ * A disabled tracker keeps folding edges without holding, so flipping the setting ON mid-run
+ * takes effect on the very next `refresh()` — no waiting for a new edge from the agent.
+ */
+export function createKeepAwake(opts: KeepAwakeOpts): KeepAwakeTracker {
+ const log = opts.log ?? ((m: string): void => console.log(m))
+ const working = new Set<string>()
+ let held = false
+
+ const reconcile = (): void => {
+ const want = opts.enabled() && working.size > 0
+ if (want === held) return
+ held = want
+ if (want) {
+ opts.blocker.start()
+ log(`[keep-awake] holding idle-sleep assertion (${working.size} working)`)
+ } else {
+ opts.blocker.stop()
+ log(`[keep-awake] released idle-sleep assertion (${working.size} working)`)
+ }
+ }
+
+ return {
+ onChange(c: KeepAwakeEdge): void {
+ if (c.event !== 'end' && c.state === 'working') {
+ // Membership is checked at ADD time, on every edge — an SSH project knows its node ids by
+ // the time its nodes emit work (fail-open: an unresolvable id counts as local, which at
+ // worst holds the assertion until the node's own release edge).
+ if (!opts.isRemoteNode(c.nodeId)) working.add(c.nodeId)
+ } else {
+ // Any non-working edge for the node releases it: `end` (done / stale synthetic end), and
+ // equally a needsYou `update` — blocked-on-the-human is not work worth staying awake for.
+ working.delete(c.nodeId)
+ }
+ reconcile()
+ },
+ refresh(): void {
+ reconcile()
+ },
+ holding(): boolean {
+ return held
+ },
+ dispose(): void {
+ working.clear()
+ reconcile()
+ }
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index a1e42b8bb..e449a2d71 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -68,6 +68,8 @@ import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
import { createGrantsAccessor } from '../core/push-grants'
import { createAckSweeper } from '../core/ack-sweep'
import { createSessionReaper } from '../core/session-budget'
+import { initKeepAwake } from './keep-awake'
+import type { KeepAwakeTracker } from '../core/keep-awake'
import { getDeviceId } from '../core/device-id'
import { initRemoteStatusPush } from './remote-ssh/remote-status-push'
import { initCanvasSync } from '../core/canvas-sync'
@@ -293,6 +295,9 @@ let activeRemote: { cwd: string; ref: GitRemoteRef } | null = null
// True from the first before-quit on: lets window close-events through (see hide-on-close).
let quitting = false
+// Keep-awake tracker (created in whenReady next to the notch HUD, disposed in before-quit).
+let keepAwake: KeepAwakeTracker | undefined
+
// Browser <webview> guest webContents id → its browser node id (for new-window capture).
const browserGuests = new Map<number, string>()
@@ -891,6 +896,17 @@ app.whenReady().then(async () => {
if (win.isVisible()) startNotchHud()
else win.once('show', startNotchHud)
settingsStore.onChange(() => applyNotchHudSettings(notchTunables()))
+ // Keep awake while agents work (docs/superpowers/specs/2026-08-18-keep-awake-design.md): hold an
+ // idle-sleep power assertion while a LOCAL agent node is working, released the moment the last
+ // one stops. Folds the same mirror edges the notch does; the stale sweep's synthetic end
+ // (WORKING_STALE_MS) is the leak backstop for exits that never send their own edge.
+ keepAwake = initKeepAwake({
+ enabled: () => settingsStore.get().keepAwakeWhileAgentsWork,
+ // SSH-homed nodes work on the remote host — they must not pin THIS machine awake.
+ isRemoteNode: (nodeId) => workspaceStore.sshProjectIdForNode(nodeId) !== undefined
+ })
+ onNodeStateChange((c) => keepAwake?.onChange(c))
+ settingsStore.onChange(() => keepAwake?.refresh())
// 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.
@@ -1953,6 +1969,8 @@ 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.
+ keepAwake?.dispose()
workspaceWatcher.dispose()
if (quitFlushed) {
// Second pass (the deferred app.quit() below): the flush had its chance — drop the masters.
diff --git a/src/main/keep-awake.ts b/src/main/keep-awake.ts
new file mode 100644
index 000000000..d86f9460e
--- /dev/null
+++ b/src/main/keep-awake.ts
@@ -0,0 +1,37 @@
+// Keep-awake shell: binds the Electron-free tracker (core/keep-awake.ts) to Electron's
+// powerSaveBlocker. `prevent-app-suspension` holds off IDLE sleep only — never display sleep,
+// and a closed lid still sleeps the machine (no app can override that; user-facing copy says so).
+// index.ts wires the seams (mirror edges, settings, SSH membership) next to the notch HUD block.
+
+import { powerSaveBlocker } from 'electron'
+import { createKeepAwake, type KeepAwakeTracker } from '../core/keep-awake'
+
+export interface KeepAwakeDeps {
+ /** Reads settings.keepAwakeWhileAgentsWork live. */
+ enabled(): boolean
+ /** True for nodes homed on an SSH project (workspaceStore.sshProjectIdForNode). */
+ isRemoteNode(nodeId: string): boolean
+ log?(msg: string): void
+}
+
+export function initKeepAwake(deps: KeepAwakeDeps): KeepAwakeTracker {
+ // The one live assertion id. The core tracker already edge-triggers start/stop, so the id
+ // checks here are pure paranoia — a double-start can never stack assertions, a stop without a
+ // live id is a no-op, and `isStarted` guards against an id Electron already tore down.
+ let blockerId: number | undefined
+ return createKeepAwake({
+ blocker: {
+ start(): void {
+ if (blockerId !== undefined && powerSaveBlocker.isStarted(blockerId)) return
+ blockerId = powerSaveBlocker.start('prevent-app-suspension')
+ },
+ stop(): void {
+ if (blockerId !== undefined && powerSaveBlocker.isStarted(blockerId)) {
+ powerSaveBlocker.stop(blockerId)
+ }
+ blockerId = undefined
+ }
+ },
+ ...deps
+ })
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 3eafa0879..5cb8a4992 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -917,6 +917,10 @@ export interface Settings {
* hook holds briefly for a phone/canvas Approve/Deny before falling through to the normal
* interactive prompt. Off ⇒ the env var is absent ⇒ exact legacy behavior. Claude-only. */
hookReplyApprovals: boolean
+ /** Hold an idle-sleep power assertion while a LOCAL agent node is working, so long runs
+ * survive an unattended laptop. Released when the last one stops (or goes stale). Cannot
+ * hold through a closed lid. Asked in the setup tour; Settings → Behavior. */
+ keepAwakeWhileAgentsWork: boolean
/** macOS Notch HUD (docs/notch-hud.md): a transparent always-on-top strip by the notch showing
* walking agent mascots while agents work, expanding into a mini session panel. Default on;
* macOS + desktop only (ignored on other platforms / Server Edition). */
@@ -1003,6 +1007,9 @@ export const DEFAULT_SETTINGS: Settings = {
// Deterministic hook-reply approvals default ON (existing users pick it up on hydrate). Only
// affects Claude terminal sessions; off reproduces the pre-feature launch bit-for-bit.
hookReplyApprovals: true,
+ // Keep-awake-while-agents-work default ON (existing users pick it up on hydrate — deliberate,
+ // same note style as hookReplyApprovals). Held only while a local agent is actually working.
+ keepAwakeWhileAgentsWork: true,
// macOS Notch HUD default ON (guarded to darwin at runtime; a no-op elsewhere).
notchHud: true,
notchWidth: 168,