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(renderer): hibernation policy + eco settings + status flags
enesa905aa243082
diff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsxindex b07285fd3..26ace91b9 100644--- a/src/renderer/components/settings/sections/AgentsSection.tsx+++ b/src/renderer/components/settings/sections/AgentsSection.tsx@@ -27,6 +27,7 @@ import { SegmentedPill } from '@renderer/ui/SegmentedPill'import { Button } from '@renderer/ui/Button'import { Select } from '@renderer/ui/Select'import { Switch } from '@renderer/ui/Switch'+import { NumberField } from '@renderer/ui/NumberField'import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'import { FieldRow } from '../FieldRow'@@ -60,6 +61,21 @@ const ROWS = {title: 'One-click approvals',keywords: ['approve', 'deny', 'approval', 'permission', 'hook', 'phone', 'canvas', 'one click', 'claude']},+ hibernation: {+ title: 'Hibernate idle agents',+ keywords: [+ 'hibernate',+ 'eco',+ 'idle',+ 'memory',+ 'ram',+ 'exit',+ 'resume',+ 'offscreen',+ 'minutes',+ 'sleep'+ ]+ }}const ENTRIES = Object.values(ROWS)@@ -202,6 +218,38 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El}/></SearchableRow>+ <SearchableRow {...ROWS.hibernation}>+ <FieldRow+ label="Hibernate idle agents"+ description="Exit an agent CLI that has been idle and offscreen this long, freeing its memory; the conversation resumes automatically when you view the node. Scheduled, /loop and /cron agents — and sessions with subagents still running — are never touched."+ control={+ <div className="flex items-center gap-2">+ <Switch+ checked={settings.agentHibernationEnabled}+ ariaLabel="Hibernate idle agents"+ onChange={(on) => update({ agentHibernationEnabled: on })}+ />+ <NumberField+ value={settings.agentHibernationIdleMinutes}+ ariaLabel="Hibernate after minutes"+ disabled={!settings.agentHibernationEnabled}+ min={5}+ max={600}+ step={5}+ // A cleared/invalid field falls back to the default rather than 0: zero minutes+ // would exit every session the instant a turn ends. Never NaN — it does not+ // survive the JSON round-trip to settings.json (it lands as `null`).+ onChange={(v) =>+ update({+ agentHibernationIdleMinutes: Number.isFinite(v) && v > 0 ? Math.max(5, v) : 30+ })+ }+ />+ <span className="text-[13px] text-muted">min</span>+ </div>+ }+ />+ </SearchableRow></SettingsSection>)}diff --git a/src/renderer/state/agentStatus.persist.test.ts b/src/renderer/state/agentStatus.persist.test.tsindex 997f6bb8e..57ccd32b7 100644--- a/src/renderer/state/agentStatus.persist.test.ts+++ b/src/renderer/state/agentStatus.persist.test.ts@@ -48,6 +48,56 @@ describe('loop persistence (cron/schedule survive an app restart)', () => {})})+ it('persists `hibernated` and drops the key when the node wakes', async () => {+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setHibernated('n1', true)+ expect(JSON.parse(store.getItem('nodeterm.agentStatus')!).n1.hibernated).toBe(true)+ useAgentStatus.getState().setHibernated('n1', false)+ expect(JSON.parse(store.getItem('nodeterm.agentStatus') ?? '{}').n1?.hibernated).toBeUndefined()+ })++ it('restores `hibernated` on load (the CLI stays exited across an app restart)', async () => {+ vi.stubGlobal(+ 'localStorage',+ memStorage({+ 'nodeterm.agentStatus': JSON.stringify({ n4: { unread: false, sessionId: 's', hibernated: true } })+ })+ )+ const { useAgentStatus } = await import('./agentStatus')+ expect(useAgentStatus.getState().byId['n4']?.hibernated).toBe(true)+ })++ it('never persists `lastEventAt` — a stale idle clock would hibernate on relaunch', async () => {+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setState('n5', 'done', 'claude')+ // The live entry carries the idle clock…+ expect(useAgentStatus.getState().byId['n5'].lastEventAt).toBeTypeOf('number')+ // …but nothing durable happened yet, so nothing was written at all.+ useAgentStatus.getState().setSessionId('n5', 'sess-1')+ const saved = JSON.parse(store.getItem('nodeterm.agentStatus')!)+ expect(saved.n5.sessionId).toBe('sess-1')+ expect(saved.n5.lastEventAt).toBeUndefined()+ expect(saved.n5.stateAt).toBeUndefined()+ expect(saved.n5.state).toBeUndefined()+ })++ it('stamps `lastEventAt` on a state transition only (same-state refresh keeps the idle clock)', async () => {+ vi.stubGlobal('localStorage', memStorage())+ const { useAgentStatus } = await import('./agentStatus')+ const st = useAgentStatus.getState()+ st.setState('n6', 'working', 'claude')+ st.setState('n6', 'done', 'claude')+ const first = useAgentStatus.getState().byId['n6'].lastEventAt!+ expect(first).toBeTypeOf('number')+ // A same-state event refreshes freshness, not the idle clock.+ st.setState('n6', 'done', 'claude')+ expect(useAgentStatus.getState().byId['n6'].lastEventAt).toBe(first)+ })+it('tolerates a persisted entry without loop (older format)', async () => {vi.stubGlobal('localStorage',diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex d25fb064d..2620dff31 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -42,6 +42,22 @@ export interface AgentNodeStatus {* interrupt-inference baseline. Same-state events refresh it in place (no re-render).*/stateAt?: number+ /**+ * When this node last CHANGED state — the idle clock the hibernation policy reads+ * (`terminal/hibernation-policy.ts`). Deliberately not `stateAt`: that one is refreshed by+ * every same-state event (freshness), while "how long has this session been idle" means "how+ * long since the turn ended". TRANSIENT — never persisted: a relaunch has seen no events yet,+ * and a stale stamp read as "idle since before the restart" would hibernate a session the+ * moment the app came back. Absent ⇒ unknown idle ⇒ never a hibernation candidate.+ */+ lastEventAt?: number+ /**+ * The agent CLI was exited to reclaim its RAM ("Eco" mode) and its conversation is waiting to be+ * resumed when the node is next viewed. PERSISTED beside unread/session/sessionId: the tmux+ * session outlives the app, so after a relaunch this flag is the only thing that knows the pane+ * holds a shell rather than a live CLI.+ */+ hibernated?: boolean/** Which agent this node is running (claude/codex/gemini/…), when known. */agentId?: AgentId/** A turn finished / needs attention while the user wasn't looking. */@@ -89,6 +105,8 @@ export interface AgentStatusStore {sweepStaleWorking(staleMs?: number): voidsetSession(id: string, session: string): voidsetSessionId(id: string, sessionId: string): void+ /** Mark the node's agent CLI as exited-for-RAM (true) or live again (false). Persisted. */+ setHibernated(id: string, on: boolean): voidmarkUnread(id: string): void/*** Drop a node's unread flag. By default a clear of a FINISHED (done) node also ACKs the read@@ -178,6 +196,9 @@ export function createAgentStatusSession(const out: Record<string, AgentNodeStatus> = {}for (const [id, v] of Object.entries(data)) {out[id] = { unread: !!v.unread, session: v.session, sessionId: v.sessionId, agentId: v.agentId }+ // Only when set: an absent flag stays absent, so an entry saved before this field+ // existed hydrates byte-identically (and `hibernated: false` never grows in the file).+ if (v.hibernated) out[id].hibernated = true// A recurring job (cron/schedule — and tmux keeps in-session loops alive too) outlives// the app: restore its card. Minimal shape check so a corrupt entry can't break load.if (v.loop && typeof v.loop === 'object' && v.loop.kind) {@@ -202,13 +223,14 @@ export function createAgentStatusSession(try {const out: Record<string, Partial<AgentNodeStatus>> = {}for (const [id, v] of Object.entries(byId)) {- if (v.unread || v.session || v.sessionId || v.loop || v.agentId) {+ if (v.unread || v.session || v.sessionId || v.loop || v.agentId || v.hibernated) {out[id] = {unread: v.unread,session: v.session,sessionId: v.sessionId,agentId: v.agentId,- loop: v.loop+ loop: v.loop,+ hibernated: v.hibernated}}}@@ -258,7 +280,10 @@ export function createAgentStatusSession(if (s.byId[id]) s.byId[id].stateAt = nowreturn s}- const next = { ...prev, state, stateAt: now }+ // The ONE place a state transition is recorded, so it is also the one place the idle+ // clock is stamped (the same-state fast path above deliberately does not touch it —+ // see `lastEventAt`).+ const next = { ...prev, state, stateAt: now, lastEventAt: now }if (agentId !== undefined) next.agentId = agentId// Retain the approval ticket only while blocked; any other state clears it (transient).next.pendingId = state === 'blocked' ? (pendingId ?? prev.pendingId) : undefined@@ -297,6 +322,18 @@ export function createAgentStatusSession(return { byId }}),+ setHibernated: (id, on) =>+ set((s) => {+ const prev = s.byId[id] ?? EMPTY+ if (!!prev.hibernated === on) return s+ // Cleared by dropping the key, not by storing `false`: `save` skips entries that carry+ // nothing durable, so a woken node leaves no residue behind in localStorage.+ const next = { ...prev, hibernated: on ? true : undefined }+ const byId = { ...s.byId, [id]: next }+ save(byId)+ return { byId }+ }),+markUnread: (id) =>set((s) => {const prev = s.byId[id] ?? EMPTYdiff --git a/src/renderer/terminal/hibernation-policy.test.ts b/src/renderer/terminal/hibernation-policy.test.tsnew file mode 100644index 000000000..9cd7cbc46--- /dev/null+++ b/src/renderer/terminal/hibernation-policy.test.ts@@ -0,0 +1,88 @@+import { describe, it, expect } from 'vitest'+import { planHibernation, HIBERNATE_BATCH_MAX } from './hibernation-policy'++const base = (id: string, over: object = {}) => ({+ id,+ agentId: 'claude',+ state: 'done',+ sessionId: 's-' + id,+ wired: true,+ offscreen: true,+ hibernated: false,+ recurring: false,+ liveSubagents: false,+ lastEventAt: 0,+ ...over+})+const cfg = { enabled: true, idleMinutes: 30 }+const NOW = 100 * 60_000++describe('planHibernation', () => {+ it('takes only done, offscreen, wired, long-idle nodes; oldest first; max 2', () => {+ const out = planHibernation(+ [+ base('a', { lastEventAt: 10 * 60_000 }),+ base('b', { lastEventAt: 5 * 60_000 }),+ base('c', { lastEventAt: 1 * 60_000 }),+ base('d', { state: 'working' }),+ base('e', { offscreen: false }),+ base('f', { lastEventAt: undefined }),+ base('g', { hibernated: true }),+ base('h', { wired: false }),+ base('i', { state: 'waiting' }),+ base('j', { recurring: true }),+ base('k', { liveSubagents: true })+ ],+ NOW,+ cfg+ )+ expect(out).toEqual(['c', 'b'])+ expect(HIBERNATE_BATCH_MAX).toBe(2)+ })++ it('never hibernates a recurring (loop/cron/schedule) node, however idle', () => {+ expect(planHibernation([base('a', { recurring: true, lastEventAt: 0 })], NOW, cfg)).toEqual([])+ })++ it('never hibernates a node with a live subagent, however idle', () => {+ expect(planHibernation([base('a', { liveSubagents: true, lastEventAt: 0 })], NOW, cfg)).toEqual(+ []+ )+ })++ it('never hibernates a waiting node — the question would be swallowed', () => {+ expect(planHibernation([base('a', { state: 'waiting' })], NOW, cfg)).toEqual([])+ expect(planHibernation([base('a', { state: 'blocked' })], NOW, cfg)).toEqual([])+ expect(planHibernation([base('a', { state: undefined })], NOW, cfg)).toEqual([])+ })++ it('never hibernates a node with no lastEventAt — unknown idle is not idle', () => {+ expect(planHibernation([base('a', { lastEventAt: undefined })], NOW, cfg)).toEqual([])+ })++ it('disabled → empty', () => {+ expect(planHibernation([base('a')], NOW, { ...cfg, enabled: false })).toEqual([])+ })++ it('idle window respected', () => {+ expect(planHibernation([base('a', { lastEventAt: NOW - 29 * 60_000 })], NOW, cfg)).toEqual([])+ // Exactly at the window is eligible (>=, not >).+ expect(planHibernation([base('a', { lastEventAt: NOW - 30 * 60_000 })], NOW, cfg)).toEqual(['a'])+ })++ it('refuses a node the restart gate itself refuses (no session id / not resumable)', () => {+ expect(planHibernation([base('a', { sessionId: undefined })], NOW, cfg)).toEqual([])+ expect(planHibernation([base('a', { agentId: 'opencode' })], NOW, cfg)).toEqual([])+ expect(planHibernation([base('a', { agentId: undefined })], NOW, cfg)).toEqual([])+ })++ it('excludes unwired, onscreen and already-hibernated nodes', () => {+ expect(planHibernation([base('a', { wired: false })], NOW, cfg)).toEqual([])+ expect(planHibernation([base('a', { offscreen: false })], NOW, cfg)).toEqual([])+ expect(planHibernation([base('a', { hibernated: true })], NOW, cfg)).toEqual([])+ })++ it('empty candidate list → empty', () => {+ expect(planHibernation([], NOW, cfg)).toEqual([])+ })+})diff --git a/src/renderer/terminal/hibernation-policy.ts b/src/renderer/terminal/hibernation-policy.tsnew file mode 100644index 000000000..7057a687b--- /dev/null+++ b/src/renderer/terminal/hibernation-policy.ts@@ -0,0 +1,88 @@+/**+ * Which idle agent sessions may be HIBERNATED — the pure decision half of "Eco" mode+ * (`settings.agentHibernationEnabled`). Hibernating means the agent CLI is asked to `/exit` and+ * the conversation is resumed (`--resume`) the next time the user looks at the node: the tmux+ * session, its pane and its scrollback are untouched; what is reclaimed is the CLI process's RAM.+ * The wiring that acts on this plan lives elsewhere — this module only decides.+ *+ * WHY EACH EXCLUSION EXISTS (each one is a way to lose the user's work or their attention):+ *+ * - **Only `done`, never `waiting`** (nor `blocked`, nor an unknown state). `waiting`/`blocked`+ * mean the CLI is holding a question or a permission request open for the user. Exiting there+ * would SILENTLY SWALLOW A NEEDS-YOU QUESTION — the badge is exactly the thing the user is+ * being asked to come back for, and the exit line typed into a permission prompt would ANSWER+ * it rather than quit. `working` is refused for the obvious reason (a turn in flight), and an+ * unknown state is not evidence of idleness.+ * - **Never a `recurring` node** (`/loop`, `/schedule`, `/cron`, any kind). `/exit` kills the CLI+ * PROCESS, and a loop's `ScheduleWakeup` / an in-session cron wakeup dies with it — the job+ * would simply never fire again. Between iterations such a node looks EXACTLY like the target+ * profile (`done`, offscreen, long idle), so this guard is the only thing standing between Eco+ * mode and a silently cancelled recurring job.+ * - **Never a node with live subagents.** Claude launches subagents async: the completion of an+ * async-launched subagent is queued into the PARENT's transcript, and a dead parent CLI never+ * reads it. Hibernating the parent orphans every subagent still running under it.+ * - **Unknown idle is NOT idle.** A candidate with no `lastEventAt` (no hook event has ever been+ * seen for it in this run) is never eligible — the same rule as pendingLaunch's "an unknown+ * dependency state is not satisfied". Guessing here costs the user a live session.+ * - **`restartEligibility` is the shared gate.** Hibernation is exit + resume, so a node this+ * module picks must be one the restart machinery could actually bring back: a CLI we cannot+ * quit or resume, or a session with no provider session id, has nothing to resume INTO.+ *+ * The batch cap keeps a sweep from stopping a canvas full of agents at once (each exit + resume+ * is real work in a real pane): the oldest-idle nodes go first, at most `HIBERNATE_BATCH_MAX` per+ * pass, so a long-idle backlog drains over several sweeps instead of in one storm.+ */+import { restartEligibility } from './agent-restart'++/** How many sessions one hibernation pass may take. */+export const HIBERNATE_BATCH_MAX = 2++export interface HibernationCandidate {+ id: string+ agentId?: string+ state?: string+ sessionId?: string+ /** The node has a live terminal/PTY wired up (an unwired node has nothing to exit). */+ wired: boolean+ /** The node is out of view. */+ offscreen: boolean+ /** Already hibernated — nothing left to reclaim. */+ hibernated: boolean+ /** Any `/loop`, `/schedule` or `/cron` indicator on this node (from `agentStatus.loop`). */+ recurring: boolean+ /** Any non-done subagent card whose parent is this node (from `state/agentNodes.ts`). */+ liveSubagents: boolean+ /** When this node's last hook event landed. Absent = never seen ⇒ never eligible. */+ lastEventAt?: number+}++export interface HibernationConfig {+ enabled: boolean+ idleMinutes: number+}++/** The node ids to hibernate now: oldest-idle first, at most `HIBERNATE_BATCH_MAX`. */+export function planHibernation(+ candidates: HibernationCandidate[],+ nowMs: number,+ cfg: HibernationConfig+): string[] {+ if (!cfg.enabled) return []+ const idleMs = cfg.idleMinutes * 60_000+ return candidates+ .filter(+ (c) =>+ !c.hibernated &&+ c.wired &&+ c.offscreen &&+ c.state === 'done' &&+ !c.recurring &&+ !c.liveSubagents &&+ restartEligibility(c.agentId, c.state, c.sessionId).ok &&+ // `?? Infinity`: no event ever seen ⇒ the difference is -Infinity ⇒ never eligible.+ nowMs - (c.lastEventAt ?? Infinity) >= idleMs+ )+ .sort((a, b) => (a.lastEventAt ?? 0) - (b.lastEventAt ?? 0))+ .slice(0, HIBERNATE_BATCH_MAX)+ .map((c) => c.id)+}diff --git a/src/renderer/ui/NumberField.tsx b/src/renderer/ui/NumberField.tsxindex dbed52607..ef2816b5b 100644--- a/src/renderer/ui/NumberField.tsx+++ b/src/renderer/ui/NumberField.tsx@@ -6,7 +6,9 @@ export function NumberField({min,max,step,- className+ className,+ disabled,+ ariaLabel}: {value: numberonChange: (v: number) => void@@ -14,6 +16,8 @@ export function NumberField({max?: numberstep?: numberclassName?: string+ disabled?: boolean+ ariaLabel?: string}): React.JSX.Element {return (<input@@ -22,9 +26,12 @@ export function NumberField({min={min}max={max}step={step}+ disabled={disabled}+ aria-label={ariaLabel}onChange={(e) => onChange(Number(e.target.value))}className={cn('h-8 w-24 rounded-md border border-border bg-bg px-2.5 text-[13px] text-text outline-none focus:border-accent',+ disabled && 'opacity-40',className)}/>diff --git a/src/shared/types.ts b/src/shared/types.tsindex 7206ce1cd..86cd446c2 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -907,6 +907,14 @@ export interface Settings {* driver runs in `default`). Overridable per project via Project.defaultPermissionMode.* `auto` is version-gated: CLIs below 2.1.71 reject the value, so it degrades to no flag. */claudePermissionMode: AgentPermissionMode+ /** "Eco": exit the agent CLI of a session that has been idle AND offscreen for+ * `agentHibernationIdleMinutes`, reclaiming its RAM; the conversation is resumed automatically+ * when the node is viewed again. Default OFF — opt-in, because it stops a real process.+ * Scheduled/loop agents and sessions with live subagents are never touched+ * (renderer/terminal/hibernation-policy.ts explains why). */+ agentHibernationEnabled: boolean+ /** How long a session must be idle + offscreen before "Eco" hibernates it (minutes). */+ agentHibernationIdleMinutes: number/** Send anonymous usage data (version/OS) to the telemetry backend. Opt-OUT (default on):* version/OS only, nothing personal, client IP never stored. Turn it off in Settings → Privacy* (or hard-disable with DO_NOT_TRACK / NODETERM_TELEMETRY_DISABLED). Note: a lighter anonymous@@ -1017,6 +1025,10 @@ export const DEFAULT_SETTINGS: Settings = {// Sessions start in auto mode out of the box. Existing users pick this up on hydrate// (settings hydrate merges over DEFAULT_SETTINGS) — a deliberate behavior change.claudePermissionMode: 'auto',+ // Opt-in: hibernation exits a live CLI, so nobody gets it without asking. The 30-minute floor+ // is deliberately long — shorter windows exit sessions the user is between turns on.+ agentHibernationEnabled: false,+ agentHibernationIdleMinutes: 30,// Opt-out (default on). Existing users pick this up on hydrate ONLY if their settings.json has// no telemetryEnabled key yet; anyone who already saved settings keeps their stored value.telemetryEnabled: true,