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
feat(keep-awake): let the machine sleep on low battery or critical heat
review9d06f766a250
diff --git a/README.md b/README.mdindex 218cf58e7..2bc3ff8be 100644--- a/README.md+++ b/README.md@@ -153,7 +153,9 @@ Gemini / GitHub Copilot / opencode / Grok / custom) · 📝 **Sticky note** (linfrom your phone — plus push notifications and a mobile board view.- **Power & sleep** — while an agent is working, nodeterm keeps the machine fromidle-sleeping, and lets go the moment it finishes (on by default; toggle in the setup- tour or Settings → Behavior). No app can hold a machine awake through a closed lid —+ tour or Settings → Behavior). It lets the machine sleep anyway on battery below 20% or+ when the machine runs critically hot. No app can hold a machine awake through a closed lid+ (a Mac with the lid closed stays awake only while plugged in with an external display) —for overnight runs keep the laptop open and plugged in, or run the agents on a boxthat doesn't sleep via the [Server Edition](./docs/SERVER.md).- **Command palette** (⌘K), **file explorer** (⌘⇧E), **markdown view** (⌘M),diff --git a/src/core/keep-awake-power.test.ts b/src/core/keep-awake-power.test.tsnew file mode 100644index 000000000..1b66620a3--- /dev/null+++ b/src/core/keep-awake-power.test.ts@@ -0,0 +1,219 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import {+ createPowerGuard,+ linuxBatteryPercent,+ parsePmsetBatt,+ type PowerGuardDeps,+ type ThermalState+} from './keep-awake-power'+import { createKeepAwake } from './keep-awake'++function harness(over: Partial<{ onBattery: boolean; thermal: ThermalState; percent: number | null }> = {}) {+ const state = {+ onBattery: over.onBattery ?? false,+ thermal: (over.thermal ?? 'nominal') as ThermalState,+ percent: over.percent === undefined ? 80 : over.percent+ }+ const changes = { count: 0 }+ const logs: string[] = []+ const deps: PowerGuardDeps = {+ onBattery: () => state.onBattery,+ thermal: () => state.thermal,+ readPercent: async () => state.percent,+ onChange: () => void changes.count++,+ log: (m) => void logs.push(m),+ pollMs: 1000+ }+ return { guard: createPowerGuard(deps), state, changes, logs }+}++afterEach(() => {+ vi.useRealTimers()+})++describe('power guard', () => {+ it('allows on AC whatever the battery level', async () => {+ const { guard, state } = harness({ onBattery: false, percent: 3 })+ await guard.refreshBattery()+ expect(guard.allows()).toBe(true)+ state.onBattery = true+ expect(guard.allows()).toBe(false)+ })++ it('blocks on battery below the floor, allows at the floor', async () => {+ const { guard, state } = harness({ onBattery: true, percent: 19 })+ await guard.refreshBattery()+ expect(guard.allows()).toBe(false)+ expect(guard.blockReason()).toMatch(/19%/)+ state.percent = 20+ await guard.refreshBattery()+ expect(guard.allows()).toBe(true)+ })++ it('fails open when the level cannot be read (null or a throwing reader)', async () => {+ const { guard } = harness({ onBattery: true, percent: null })+ await guard.refreshBattery()+ expect(guard.allows()).toBe(true)++ const throwing = createPowerGuard({+ onBattery: () => true,+ thermal: () => 'nominal',+ readPercent: async () => {+ throw new Error('pmset missing')+ },+ onChange: () => {},+ log: () => {}+ })+ await throwing.refreshBattery()+ expect(throwing.allows()).toBe(true)+ })++ it('blocks at critical heat and latches through serious, clearing at fair', () => {+ const { guard, state } = harness({ thermal: 'serious' })+ expect(guard.allows()).toBe(true) // serious alone does not block+ state.thermal = 'critical'+ expect(guard.allows()).toBe(false)+ state.thermal = 'serious'+ expect(guard.allows()).toBe(false) // latched — no flapping on the boundary+ state.thermal = 'fair'+ expect(guard.allows()).toBe(true)+ state.thermal = 'serious'+ expect(guard.allows()).toBe(true)+ })++ it('unknown thermal state never blocks', () => {+ const { guard } = harness({ thermal: 'unknown' })+ expect(guard.allows()).toBe(true)+ })++ it('notifies on refresh and logs only when the verdict changes', async () => {+ const { guard, state, changes, logs } = harness({ onBattery: true, percent: 10 })+ await guard.refreshBattery()+ await guard.refreshBattery()+ expect(changes.count).toBe(2)+ expect(logs.filter((l) => l.includes('letting the machine sleep'))).toHaveLength(1)+ state.onBattery = false+ guard.poke()+ expect(logs.some((l) => l.includes('cleared'))).toBe(true)+ })++ it('polls the level only while holding, and only on battery', async () => {+ vi.useFakeTimers()+ const reads = { count: 0 }+ const state = { onBattery: true }+ const guard = createPowerGuard({+ onBattery: () => state.onBattery,+ thermal: () => 'nominal',+ readPercent: async () => {+ reads.count+++ return 50+ },+ onChange: () => {},+ log: () => {},+ pollMs: 1000+ })+ vi.advanceTimersByTime(5000)+ expect(reads.count).toBe(0)+ guard.setHolding(true)+ expect(reads.count).toBe(1) // immediate read at hold start+ vi.advanceTimersByTime(2000)+ expect(reads.count).toBe(3)+ state.onBattery = false+ vi.advanceTimersByTime(2000)+ expect(reads.count).toBe(3) // on AC: no reads+ guard.setHolding(false)+ state.onBattery = true+ vi.advanceTimersByTime(5000)+ expect(reads.count).toBe(3)+ guard.dispose()+ })++ it('a disposed guard notifies nobody', async () => {+ const { guard, changes } = harness({ onBattery: true })+ guard.dispose()+ await guard.refreshBattery()+ guard.poke()+ expect(changes.count).toBe(0)+ })+})++describe('tracker + power guard', () => {+ it('releases the assertion when power stops allowing it, and re-holds when it allows again', () => {+ const calls = { start: 0, stop: 0 }+ const power = { ok: true }+ const tracker = createKeepAwake({+ blocker: { start: () => void calls.start++, stop: () => void calls.stop++ },+ enabled: () => true,+ isRemoteNode: () => false,+ powerAllows: () => power.ok,+ log: () => {}+ })+ tracker.onChange({ nodeId: 'a', event: 'start', state: 'working' })+ expect(tracker.holding()).toBe(true)+ power.ok = false+ tracker.refresh()+ expect(tracker.holding()).toBe(false)+ expect(calls.stop).toBe(1)+ // Still working: plugging in re-holds without a new edge.+ power.ok = true+ tracker.refresh()+ expect(tracker.holding()).toBe(true)+ expect(calls.start).toBe(2)+ })++ it('never asks power when nothing is working', () => {+ const asked = { count: 0 }+ const tracker = createKeepAwake({+ blocker: { start: () => {}, stop: () => {} },+ enabled: () => true,+ isRemoteNode: () => false,+ powerAllows: () => {+ asked.count+++ return true+ },+ log: () => {}+ })+ tracker.refresh()+ expect(asked.count).toBe(0)+ })+})++describe('parsePmsetBatt', () => {+ it('reads the internal battery percent', () => {+ const out = "Now drawing from 'Battery Power'\n -InternalBattery-0 (id=1234567)\t54%; discharging; 4:12 remaining present: true\n"+ expect(parsePmsetBatt(out)).toBe(54)+ })+ it('null on a desktop Mac (no internal battery line)', () => {+ expect(parsePmsetBatt("Now drawing from 'AC Power'\n")).toBeNull()+ })+ it('ignores a UPS line and reads only the internal battery', () => {+ const out = " -CP1500PFCLCD (id=1)\t100%; AC attached; not charging present: true\n -InternalBattery-0 (id=2)\t7%; discharging\n"+ expect(parsePmsetBatt(out)).toBe(7)+ })+})++describe('linuxBatteryPercent', () => {+ it('ignores peripheral batteries', () => {+ expect(+ linuxBatteryPercent([+ { type: 'Battery\n', scope: 'Device\n', capacity: '5\n' },+ { type: 'Mains\n' }+ ])+ ).toBeNull()+ })+ it('combines two system batteries by energy', () => {+ expect(+ linuxBatteryPercent([+ { type: 'Battery', energyNow: '10000000', energyFull: '40000000', capacity: '25' },+ { type: 'Battery', energyNow: '30000000', energyFull: '40000000', capacity: '75' }+ ])+ ).toBe(50)+ })+ it('averages capacity when energy is not reported', () => {+ expect(linuxBatteryPercent([{ type: 'Battery', capacity: '42\n' }])).toBe(42)+ })+ it('null when nothing usable', () => {+ expect(linuxBatteryPercent([{ type: 'Battery' }])).toBeNull()+ expect(linuxBatteryPercent([])).toBeNull()+ })+})diff --git a/src/core/keep-awake-power.ts b/src/core/keep-awake-power.tsnew file mode 100644index 000000000..da6bef145--- /dev/null+++ b/src/core/keep-awake-power.ts@@ -0,0 +1,216 @@+// Power guards for keep-awake: when holding the machine out of idle sleep stops being worth it.+//+// The tracker (keep-awake.ts) holds while a local agent is `working`. That is the right call on+// a charger and a cool machine, and the wrong one on a laptop at 8% battery or one the OS reports+// as critically hot — there, letting the machine sleep is the safer outcome for the user than a+// finished agent turn. Two rules, both RELEASE the assertion (never anything stronger):+// - battery: on battery power below KEEP_AWAKE_BATTERY_FLOOR_PCT. Plugging back in re-holds.+// - thermal: macOS reports `critical`. Latched until the state drops back to `fair`/`nominal`+// (or `unknown`), so a machine hovering on the serious/critical boundary does not flap the+// assertion on every notification.+//+// Fail-open, deliberately: an unreadable battery level (Windows, a reader that broke, no battery+// at all) or an unknown thermal state leaves today's behavior untouched. Keep-awake predates these+// guards and a broken reader must not silently switch the feature off. The stale-working sweep+// still caps the worst case, exactly as before.+//+// Electron-free: `onBattery` / `thermal` are injected (Electron's powerMonitor in+// src/main/keep-awake.ts); only the battery LEVEL is read here, because Electron's main process+// has no API for it.++import { execFile } from 'child_process'+import { promises as fsp } from 'fs'+import path from 'path'++/** On battery below this percent, keep-awake lets the machine sleep. */+export const KEEP_AWAKE_BATTERY_FLOOR_PCT = 20+/** How often the battery level is re-read while holding on battery. */+export const KEEP_AWAKE_BATTERY_POLL_MS = 60_000++export type ThermalState = 'unknown' | 'nominal' | 'fair' | 'serious' | 'critical'++export interface PowerGuardDeps {+ /** Live: is the machine running on battery right now? (powerMonitor.isOnBatteryPower) */+ onBattery(): boolean+ /** Live thermal state; 'unknown' where the platform reports none. */+ thermal(): ThermalState+ /** Battery level 0–100, or null when it cannot be read. */+ readPercent(): Promise<number | null>+ /** A guard input changed — the tracker should re-evaluate (tracker.refresh). */+ onChange(): void+ floorPct?: number+ pollMs?: number+ log?(msg: string): void+}++export interface PowerGuard {+ /** Does power allow holding the assertion right now? */+ allows(): boolean+ /** The reason it does not, for the log (null when it allows). */+ blockReason(): string | null+ /** Re-read the battery level, then notify. Call on on-battery / resume. */+ refreshBattery(): Promise<void>+ /** Thermal state or AC/battery changed — notify. */+ poke(): void+ /** The tracker started (true) / stopped (false) holding: polls the level only while holding. */+ setHolding(holding: boolean): void+ dispose(): void+}++export function createPowerGuard(deps: PowerGuardDeps): PowerGuard {+ const floor = deps.floorPct ?? KEEP_AWAKE_BATTERY_FLOOR_PCT+ const pollMs = deps.pollMs ?? KEEP_AWAKE_BATTERY_POLL_MS+ const log = deps.log ?? ((m: string): void => console.log(m))+ let percent: number | null = null+ let hot = false+ let poll: ReturnType<typeof setInterval> | undefined+ let disposed = false+ let lastReason: string | null = null++ const reason = (): string | null => {+ const t = deps.thermal()+ if (t === 'critical') hot = true+ else if (t !== 'serious') hot = false // nominal / fair / unknown clear the latch+ if (hot) return `thermal state ${t}`+ if (deps.onBattery() && percent !== null && percent < floor) {+ return `on battery at ${percent}% (below ${floor}%)`+ }+ return null+ }++ const notify = (): void => {+ if (disposed) return+ const r = reason()+ if (r !== lastReason) {+ if (r) log(`[keep-awake] power guard: letting the machine sleep — ${r}`)+ else if (lastReason) log(`[keep-awake] power guard cleared (was: ${lastReason})`)+ lastReason = r+ }+ deps.onChange()+ }++ const refreshBattery = async (): Promise<void> => {+ let next: number | null = null+ try {+ next = await deps.readPercent()+ } catch {+ next = null+ }+ if (disposed) return+ percent = next+ notify()+ }++ return {+ allows: () => reason() === null,+ blockReason: reason,+ refreshBattery,+ poke: notify,+ setHolding(holding: boolean): void {+ if (holding && !poll && !disposed) {+ // Read once now: the cached level may be hours old by the time a hold begins.+ void refreshBattery()+ poll = setInterval(() => {+ if (deps.onBattery()) void refreshBattery()+ }, pollMs)+ poll.unref?.()+ } else if (!holding && poll) {+ clearInterval(poll)+ poll = undefined+ }+ },+ dispose(): void {+ disposed = true+ if (poll) clearInterval(poll)+ poll = undefined+ }+ }+}++/** The internal battery's percent from `pmset -g batt`, or null. */+export function parsePmsetBatt(out: string): number | null {+ for (const line of out.split('\n')) {+ if (!line.includes('InternalBattery')) continue+ const m = /(\d{1,3})%/.exec(line)+ if (!m) return null+ const n = Number(m[1])+ return n >= 0 && n <= 100 ? n : null+ }+ return null+}++/** One `/sys/class/power_supply/<name>` entry, as the Linux reader needs it. */+export interface LinuxSupply {+ type?: string+ scope?: string+ capacity?: string+ energyNow?: string+ energyFull?: string+ chargeNow?: string+ chargeFull?: string+}++/**+ * The system battery level from Linux power_supply entries, or null. Peripheral batteries+ * (`scope` = Device: a mouse, a headset) are ignored. Several system batteries (ThinkPad+ * BAT0+BAT1) are combined by energy (or charge) when every one reports it, else averaged.+ */+export function linuxBatteryPercent(supplies: LinuxSupply[]): number | null {+ const bats = supplies.filter((s) => s.type?.trim() === 'Battery' && s.scope?.trim() !== 'Device')+ if (bats.length === 0) return null+ const num = (v?: string): number | null => {+ if (v === undefined) return null+ const n = Number(v.trim())+ return Number.isFinite(n) ? n : null+ }+ const pairs = bats.map((b) => {+ const now = num(b.energyNow) ?? num(b.chargeNow)+ const full = num(b.energyFull) ?? num(b.chargeFull)+ return now !== null && full !== null && full > 0 ? { now, full } : null+ })+ if (pairs.every((p) => p !== null)) {+ const now = pairs.reduce((a, p) => a + p!.now, 0)+ const full = pairs.reduce((a, p) => a + p!.full, 0)+ return Math.max(0, Math.min(100, Math.round((now / full) * 100)))+ }+ const caps = bats.map((b) => num(b.capacity)).filter((n): n is number => n !== null)+ if (caps.length === 0) return null+ return Math.max(0, Math.min(100, Math.round(caps.reduce((a, n) => a + n, 0) / caps.length)))+}++const SUPPLY_ROOT = '/sys/class/power_supply'++async function readLinuxSupplies(root = SUPPLY_ROOT): Promise<LinuxSupply[]> {+ const names = await fsp.readdir(root)+ const read = (dir: string, f: string): Promise<string | undefined> =>+ fsp.readFile(path.join(dir, f), 'utf8').catch(() => undefined)+ return Promise.all(+ names.map(async (n) => {+ const d = path.join(root, n)+ const [type, scope, capacity, energyNow, energyFull, chargeNow, chargeFull] = await Promise.all(+ ['type', 'scope', 'capacity', 'energy_now', 'energy_full', 'charge_now', 'charge_full'].map((f) =>+ read(d, f)+ )+ )+ return { type, scope, capacity, energyNow, energyFull, chargeNow, chargeFull }+ })+ )+}++/** Battery level on this machine, or null (unsupported platform, no battery, read failed). */+export async function readBatteryPercent(platform: NodeJS.Platform = process.platform): Promise<number | null> {+ try {+ if (platform === 'darwin') {+ const out = await new Promise<string>((resolve, reject) =>+ execFile('/usr/bin/pmset', ['-g', 'batt'], { timeout: 5000 }, (err, stdout) =>+ err ? reject(err) : resolve(String(stdout))+ )+ )+ return parsePmsetBatt(out)+ }+ if (platform === 'linux') return linuxBatteryPercent(await readLinuxSupplies())+ } catch {+ return null+ }+ return null+}diff --git a/src/core/keep-awake.ts b/src/core/keep-awake.tsindex be571054e..cce789efa 100644--- a/src/core/keep-awake.ts+++ b/src/core/keep-awake.ts@@ -46,13 +46,16 @@ export interface KeepAwakeOpts {enabled(): boolean/** True for nodes homed on an SSH project — their work isn't on this machine. */isRemoteNode(nodeId: string): boolean+ /** Power guards (keep-awake-power.ts): false = let the machine sleep even while agents work+ * (low battery, critical thermal state). Absent = always allowed. Read LIVE on every reconcile. */+ powerAllows?(): booleanlog?(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). */+ /** Re-evaluate after a settings change (live toggle) or a power-guard change. */refresh(): void/** Converge to the mirror's authoritative `working` node ids (boot seed + every flush).* Covers every reset the edge stream never reports — loadPersisted restores, the SessionStart@@ -78,7 +81,7 @@ export function createKeepAwake(opts: KeepAwakeOpts): KeepAwakeTracker {let held = falseconst reconcile = (): void => {- const want = opts.enabled() && working.size > 0+ const want = working.size > 0 && opts.enabled() && (opts.powerAllows?.() ?? true)if (want === held) returnheld = wantif (want) {diff --git a/src/main/keep-awake.ts b/src/main/keep-awake.tsindex d86f9460e..d486402e2 100644--- a/src/main/keep-awake.ts+++ b/src/main/keep-awake.ts@@ -2,9 +2,14 @@// 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.+//+// The power guards (core/keep-awake-power.ts) are fed from Electron's powerMonitor here: AC vs+// battery (`isOnBatteryPower` + on-battery/on-ac), the macOS thermal state (`thermal-state-change`;+// other platforms report 'unknown', which never blocks), and a battery-level re-read on resume.-import { powerSaveBlocker } from 'electron'+import { powerMonitor, powerSaveBlocker } from 'electron'import { createKeepAwake, type KeepAwakeTracker } from '../core/keep-awake'+import { createPowerGuard, readBatteryPercent, type ThermalState } from '../core/keep-awake-power'export interface KeepAwakeDeps {/** Reads settings.keepAwakeWhileAgentsWork live. */@@ -14,24 +19,78 @@ export interface KeepAwakeDeps {log?(msg: string): void}+function onBatteryNow(): boolean {+ try {+ return powerMonitor.isOnBatteryPower()+ } catch {+ return false+ }+}++function thermalNow(): ThermalState {+ if (process.platform !== 'darwin') return 'unknown'+ try {+ return powerMonitor.getCurrentThermalState()+ } catch {+ return 'unknown'+ }+}+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({+ let tracker: KeepAwakeTracker | undefined++ const guard = createPowerGuard({+ onBattery: onBatteryNow,+ thermal: thermalNow,+ readPercent: () => readBatteryPercent(),+ onChange: () => tracker?.refresh(),+ log: deps.log+ })++ tracker = createKeepAwake({blocker: {start(): void {+ guard.setHolding(true)if (blockerId !== undefined && powerSaveBlocker.isStarted(blockerId)) returnblockerId = powerSaveBlocker.start('prevent-app-suspension')},stop(): void {+ guard.setHolding(false)if (blockerId !== undefined && powerSaveBlocker.isStarted(blockerId)) {powerSaveBlocker.stop(blockerId)}blockerId = undefined}},+ powerAllows: () => guard.allows(),...deps})++ const onBattery = (): void => void guard.refreshBattery()+ const onAc = (): void => guard.poke()+ const onResume = (): void => void guard.refreshBattery()+ const onThermal = (): void => guard.poke()+ powerMonitor.on('on-battery', onBattery)+ powerMonitor.on('on-ac', onAc)+ powerMonitor.on('resume', onResume)+ if (process.platform === 'darwin') powerMonitor.on('thermal-state-change', onThermal)+ // Seed the level once so the first hold on battery is judged on a real number.+ void guard.refreshBattery()++ const t = tracker+ return {+ ...t,+ dispose(): void {+ powerMonitor.off('on-battery', onBattery)+ powerMonitor.off('on-ac', onAc)+ powerMonitor.off('resume', onResume)+ if (process.platform === 'darwin') powerMonitor.off('thermal-state-change', onThermal)+ guard.dispose()+ t.dispose()+ }+ }}diff --git a/src/renderer/components/onboarding/OnboardingFlow.tsx b/src/renderer/components/onboarding/OnboardingFlow.tsxindex 23ed272d3..c18fef137 100644--- a/src/renderer/components/onboarding/OnboardingFlow.tsx+++ b/src/renderer/components/onboarding/OnboardingFlow.tsx@@ -460,7 +460,9 @@ export function OnboardingFlow({ onClose }: { onClose: () => void }) {</p><p>Closing the lid still sleeps the machine — keep it open and plugged in for- overnight runs.+ overnight runs (on a Mac, a closed lid works when plugged in with an external+ display). On battery below 20%, or when the machine runs critically hot, it is+ allowed to sleep.</p><div className="onb-toggle-row"><Switchdiff --git a/src/renderer/components/settings/sections/BehaviorSection.tsx b/src/renderer/components/settings/sections/BehaviorSection.tsxindex 93462c681..3851ccc9d 100644--- a/src/renderer/components/settings/sections/BehaviorSection.tsx+++ b/src/renderer/components/settings/sections/BehaviorSection.tsx@@ -87,7 +87,7 @@ const ROWS = {},keepAwake: {title: 'Keep awake while agents work',- keywords: ['sleep', 'awake', 'power', 'battery', 'suspend', 'run']+ keywords: ['sleep', 'awake', 'power', 'battery', 'suspend', 'run', 'lid', 'thermal', 'heat']},confirmQuit: {title: 'Confirm before quitting',@@ -444,7 +444,7 @@ export function BehaviorSection({ isActive }: { isActive: boolean }): React.JSX.<SearchableRow {...ROWS.keepAwake}><FieldRowlabel="Keep awake while agents work"- description="Holds off idle sleep while a local agent is running. A closed lid still sleeps the machine."+ description="Holds off idle sleep while a local agent is running. Lets the machine sleep on battery below 20% or when it runs critically hot. A closed lid still sleeps the machine, except on macOS when plugged in with an external display connected."control={<Switchchecked={settings.keepAwakeWhileAgentsWork}