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(renderer): opt-in agent hibernation — exit idle offscreen CLIs, resume on view

enesb1186251a2ed
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 4faedd7de..11e9c3fc2 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -27,7 +27,8 @@ import {
setSshRetryHandler,
disposeTerminalOnUnmount,
disposeParkedTerminal,
- disposeAllParkedTerminals
+ disposeAllParkedTerminals,
+ isNodeOffscreen
} from '../nodes/TerminalNode'
import { solveFitPadding } from './fit-view'
import {
@@ -157,6 +158,7 @@ import { SshPassphrasePrompt } from '../components/SshPassphrasePrompt'
import { transport } from '../terminal/local-transport'
import { sshFs } from '../terminal/ssh-fs'
import {
+ agentHibernateFns,
agentRestartFn,
planBulkRestart,
restartEligibility,
@@ -165,6 +167,8 @@ import {
type BulkRestartPlan,
type RestartOutcome
} from '../terminal/agent-restart'
+import { planHibernation, HIBERNATE_SWEEP_MS } from '../terminal/hibernation-policy'
+import { buildHibernationCandidates } from '../lib/hibernationCandidates'
import { prepareQuickOpenFiles, type QuickOpenIndexedFile } from '../lib/quickOpenSearch'
import { opensInEditor } from '../lib/openTarget'
import { newEntryPath, parentDir } from '../lib/explorerCreate'
@@ -1137,7 +1141,9 @@ export function Canvas() {
let sig = ''
for (const [id, st] of Object.entries(s.byId)) {
if (!st.loop) continue
- sig += `${id}|${st.loop.kind ?? ''}|${st.loop.count}|${st.loop.items?.length ?? 0}|${st.loop.task ?? ''}|${st.loop.schedule ?? ''}|${st.state === 'working' ? 1 : 0}|`
+ // `dismissed` rides the signature (it is what the card derivation filters on), so the ×
+ // removes the card on the next render rather than waiting for some other loop change.
+ sig += `${id}|${st.loop.kind ?? ''}|${st.loop.count}|${st.loop.items?.length ?? 0}|${st.loop.task ?? ''}|${st.loop.schedule ?? ''}|${st.state === 'working' ? 1 : 0}|${st.loop.dismissed ? 1 : 0}|`
}
return sig
})
@@ -1222,7 +1228,10 @@ export function Canvas() {
const eEdges: Edge[] = []
// Loop nodes: one per terminal node currently running a /loop, placed below-left.
for (const [pid, st] of Object.entries(claudeById)) {
- if (!st.loop) continue
+ // A DISMISSED cron/schedule entry is kept on purpose (it is the hibernation guard's only
+ // evidence that a wakeup is pending — see agentStatus's `loop.dismissed`), so the filter
+ // lives here, in the render layer, and nowhere else.
+ if (!st.loop || st.loop.dismissed) continue
const parent = nodes.find((n) => n.id === pid)
if (!parent) continue
const ph = parent.measured?.height ?? (parent.height as number) ?? 400
@@ -7049,6 +7058,86 @@ export function Canvas() {
return () => clearInterval(t)
}, [])
+ /**
+ * ECO — hibernate idle, offscreen agent CLIs (`settings.agentHibernationEnabled`, off by
+ * default). The CLI is asked to `/exit` and its conversation is resumed (`--resume`) the next
+ * time the node is looked at; the tmux session, its pane and its scrollback are untouched. What
+ * is reclaimed is the agent process's RAM, which on a canvas of a dozen sessions is most of it.
+ *
+ * Every DECISION is in the pure `planHibernation`, and every FACT it reads is assembled by the
+ * pure `buildHibernationCandidates` — deliberately not inline here, because two of those facts
+ * (a dismissed cron card is still recurring; an unfinished subagent pins its parent) are the
+ * difference between Eco mode and a silently cancelled job, and an inline `.map()` is where a
+ * rule like that rots untested.
+ *
+ * Nothing is retried and nothing is remembered: an outcome other than `'exited'` simply leaves
+ * the node alone, and the next sweep re-asks with fresh facts. The batch cap lives in the policy.
+ */
+ const hibernationEnabled = useSettings((s) => s.settings.agentHibernationEnabled)
+ useEffect(() => {
+ if (!hibernationEnabled) return
+ let stopped = false
+ let sweeping = false
+ const sweep = async (): Promise<void> => {
+ // One sweep at a time. Each exit waits on a real pane (up to RESTART_EXIT_TIMEOUT_MS), so a
+ // slow pass can outlive its interval; overlapping passes would only be refused by the
+ // per-node guard, but re-planning against half-applied state is noise nobody needs.
+ if (sweeping) return
+ sweeping = true
+ try {
+ const s = useSettings.getState().settings
+ const candidates = buildHibernationCandidates({
+ nodes: nodesRef.current
+ .filter((n) => n.type === 'terminal')
+ .map((n) => ({ id: n.id, agentId: createdAgentId(n.data) })),
+ statusById: useAgentStatus.getState().byId,
+ // Any card that has not finished pins its parent — see the adapter's header.
+ subagents: Object.values(useAgentNodes.getState().byId).map((v) => ({
+ parentNodeId: v.parentNodeId,
+ status: v.state
+ })),
+ // The nodes' own visibility observers (Phase 2's) are the authority — never a second
+ // observer here, and "we have not heard" is never read as "nobody is looking".
+ isOffscreen: isNodeOffscreen,
+ // Wired = mounted with a live terminal that registered its hibernate pair. An
+ // offscreen-DISPOSED node (Phase 2) has already given its buffer back and has no pane
+ // to quit, so it drops out here.
+ isWired: (nodeId) => !!agentHibernateFns(nodeId)
+ })
+ const ids = planHibernation(candidates, Date.now(), {
+ enabled: s.agentHibernationEnabled,
+ idleMinutes: s.agentHibernationIdleMinutes
+ })
+ // Sequential, like the bulk restart: each exit is a real conversation being asked to quit
+ // in a real pane, and the cap keeps the pass short.
+ for (const nodeId of ids) {
+ if (stopped) return
+ const fns = agentHibernateFns(nodeId)
+ if (!fns) continue // unmounted between the plan and its turn
+ try {
+ if ((await fns.exit()) === 'exited') {
+ useAgentStatus.getState().setHibernated(nodeId, true)
+ }
+ // 'exit-timeout' / 'not-eligible': the CLI is still running and NOTHING is recorded —
+ // marking it hibernated would put a SLEEPING chip on a live session and suppress the
+ // wake's only trigger. The next sweep re-evaluates.
+ } catch (err) {
+ // The writes go unguarded down to the socket; one node's throw must not abandon the
+ // rest of the pass (nor the interval).
+ console.warn('[hibernate] exit failed for', nodeId, err)
+ }
+ }
+ } finally {
+ sweeping = false
+ }
+ }
+ const t = setInterval(() => void sweep(), HIBERNATE_SWEEP_MS)
+ return () => {
+ stopped = true
+ clearInterval(t)
+ }
+ }, [hibernationEnabled])
+
// When the palette opens, capture each terminal's visible buffer (cached ~3s) so the
// search can match text shown in terminals/Claude sessions.
useEffect(() => {
diff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsx
index fe64d5111..f15cc82ef 100644
--- a/src/renderer/components/kanban/SessionCard.tsx
+++ b/src/renderer/components/kanban/SessionCard.tsx
@@ -47,12 +47,18 @@ export const SessionCard = memo(function SessionCard({
const r = (e.currentTarget as HTMLElement).getBoundingClientRect()
return e.clientY < r.top + r.height / 2 ? 'before' : 'after'
}
+ // The board is the canvas's other view of the same sessions, and it reads the same store — so
+ // SLEEPING (Eco: the agent CLI was exited to reclaim its RAM) is one more branch here, not a
+ // follow-up. Ranked last: a hibernated node is idle by definition, so `working`/`waiting` can
+ // only mean the wake already landed and the hooks are ahead of the flag.
const badge =
session.kind !== 'sticky' && status?.state === 'working'
? 'running'
: session.kind !== 'sticky' && (status?.state === 'waiting' || status?.state === 'blocked')
? 'needs'
- : null
+ : session.kind !== 'sticky' && status?.hibernated
+ ? 'sleeping'
+ : null
const stickyPreview = session.kind === 'sticky' ? (session.text ?? '').trim() : ''
const assignees = meta?.assignees ?? []
const due = meta?.dueAt
@@ -102,6 +108,14 @@ export const SessionCard = memo(function SessionCard({
{session.kind === 'browser' && <span className="kanban-card__kind">web</span>}
{badge === 'running' && <span className="kanban-badge kanban-badge--running">RUNNING</span>}
{badge === 'needs' && <span className="kanban-badge kanban-badge--needs">NEEDS YOU</span>}
+ {badge === 'sleeping' && (
+ <span
+ className="kanban-badge kanban-badge--sleeping"
+ title="Agent hibernated to save memory — resumes when you open the session"
+ >
+ SLEEPING
+ </span>
+ )}
{status?.unread && <span className="kanban-card__unread" />}
</div>
{(labels.length > 0 || assignees.length > 0 || due !== undefined || priority !== undefined) && (
diff --git a/src/renderer/lib/hibernationCandidates.test.ts b/src/renderer/lib/hibernationCandidates.test.ts
new file mode 100644
index 000000000..61920f0bb
--- /dev/null
+++ b/src/renderer/lib/hibernationCandidates.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from 'vitest'
+import { buildHibernationCandidates, type HibernationCandidateInputs } from './hibernationCandidates'
+import { planHibernation } from '../terminal/hibernation-policy'
+
+const NOW = 1_800_000_000_000
+const IDLE = NOW - 60 * 60_000 // an hour of silence: past any window used below
+
+function inputs(over: Partial<HibernationCandidateInputs> = {}): HibernationCandidateInputs {
+ return {
+ nodes: [{ id: 'a', agentId: 'claude' }],
+ statusById: { a: { state: 'done', sessionId: 'sid-a', lastEventAt: IDLE } },
+ subagents: [],
+ isOffscreen: () => true,
+ isWired: () => true,
+ ...over
+ }
+}
+
+describe('buildHibernationCandidates', () => {
+ it('lifts the live facts onto the policy row', () => {
+ expect(buildHibernationCandidates(inputs())).toEqual([
+ {
+ id: 'a',
+ agentId: 'claude',
+ state: 'done',
+ sessionId: 'sid-a',
+ wired: true,
+ offscreen: true,
+ hibernated: false,
+ recurring: false,
+ liveSubagents: false,
+ lastEventAt: IDLE
+ }
+ ])
+ })
+
+ it('reads a DISMISSED cron entry as recurring — the card is hidden, the job is not gone', () => {
+ // The exact hole this adapter exists to close: dismissing a cron card used to CLEAR the entry,
+ // which dropped the only guard between Eco mode and a silently cancelled job. The entry is now
+ // retained with `dismissed: true`, and this row must not read that flag.
+ const rows = buildHibernationCandidates(
+ inputs({
+ statusById: {
+ a: {
+ state: 'done',
+ sessionId: 'sid-a',
+ lastEventAt: IDLE,
+ loop: { kind: 'cron', count: 0, items: [], dismissed: true }
+ }
+ }
+ })
+ )
+ expect(rows[0].recurring).toBe(true)
+ // …and end to end: the policy refuses it, however idle and offscreen it looks.
+ expect(planHibernation(rows, NOW, { enabled: true, idleMinutes: 30 })).toEqual([])
+ })
+
+ it('reads a visible loop entry as recurring too', () => {
+ const rows = buildHibernationCandidates(
+ inputs({
+ statusById: { a: { state: 'done', sessionId: 'sid-a', lastEventAt: IDLE, loop: { kind: 'loop' } } }
+ })
+ )
+ expect(rows[0].recurring).toBe(true)
+ })
+
+ it('counts any non-done subagent card of THIS parent as live', () => {
+ const withCards = (subagents: HibernationCandidateInputs['subagents']) =>
+ buildHibernationCandidates(inputs({ subagents }))[0].liveSubagents
+ expect(withCards([{ parentNodeId: 'a', status: 'working' }])).toBe(true)
+ // Unknown state is not evidence that it finished — conservative, like pendingLaunch's deps.
+ expect(withCards([{ parentNodeId: 'a', status: undefined }])).toBe(true)
+ expect(withCards([{ parentNodeId: 'a', status: 'done' }])).toBe(false)
+ // …and a sibling node's running subagent must never pin THIS node.
+ expect(withCards([{ parentNodeId: 'b', status: 'working' }])).toBe(false)
+ // A done card beside a live one still leaves the parent pinned.
+ expect(
+ withCards([
+ { parentNodeId: 'a', status: 'done' },
+ { parentNodeId: 'a', status: 'working' }
+ ])
+ ).toBe(true)
+ })
+
+ it('carries wiring and visibility from the callbacks, per node', () => {
+ const rows = buildHibernationCandidates(
+ inputs({
+ nodes: [
+ { id: 'a', agentId: 'claude' },
+ { id: 'b', agentId: 'claude' }
+ ],
+ statusById: { a: { state: 'done' }, b: { state: 'done' } },
+ isOffscreen: (id) => id === 'a',
+ isWired: (id) => id === 'b'
+ })
+ )
+ expect(rows.map((r) => [r.id, r.offscreen, r.wired])).toEqual([
+ ['a', true, false],
+ ['b', false, true]
+ ])
+ })
+
+ it('emits a row for a node with no status at all — the policy refuses it, this does not filter', () => {
+ const rows = buildHibernationCandidates(inputs({ statusById: {} }))
+ expect(rows).toHaveLength(1)
+ expect(rows[0]).toMatchObject({ state: undefined, lastEventAt: undefined, hibernated: false })
+ expect(planHibernation(rows, NOW, { enabled: true, idleMinutes: 30 })).toEqual([])
+ })
+
+ it('marks an already-hibernated node so the sweep cannot pick it twice', () => {
+ const rows = buildHibernationCandidates(
+ inputs({ statusById: { a: { state: 'done', sessionId: 'sid-a', lastEventAt: IDLE, hibernated: true } } })
+ )
+ expect(rows[0].hibernated).toBe(true)
+ expect(planHibernation(rows, NOW, { enabled: true, idleMinutes: 30 })).toEqual([])
+ })
+
+ it('an idle, offscreen, wired agent node with none of the guards IS planned', () => {
+ // The positive control: without it, every refusal above could be passing for the wrong reason.
+ expect(planHibernation(buildHibernationCandidates(inputs()), NOW, { enabled: true, idleMinutes: 30 })).toEqual(['a'])
+ })
+})
diff --git a/src/renderer/lib/hibernationCandidates.ts b/src/renderer/lib/hibernationCandidates.ts
new file mode 100644
index 000000000..33e9fecf7
--- /dev/null
+++ b/src/renderer/lib/hibernationCandidates.ts
@@ -0,0 +1,83 @@
+/**
+ * Assemble the rows `planHibernation` decides on — the ADAPTER between four live sources (the
+ * canvas nodes, the agent-status table, the subagent cards, and the node's own wiring/visibility)
+ * and the pure policy in `terminal/hibernation-policy.ts`.
+ *
+ * It exists as its own tested function rather than as a `.map()` inside the sweep because two of
+ * the four facts are SAFETY facts, and an untested inline expression is exactly where they rot:
+ *
+ * - **`recurring` is `!!loop`, dismissed or not.** A dismissed cron/schedule card keeps its entry
+ * precisely so this row stays true (see `agentStatus`'s `loop.dismissed`): the card is hidden,
+ * the job is not gone, and `/exit` would kill the CLI its wakeup lives in. Reading the render
+ * filter here — "no card, so nothing recurring" — silently cancels the job Eco mode was never
+ * allowed to touch. That hole is the reason this file has a test.
+ * - **`liveSubagents` is "any card for this parent that is NOT done".** Claude launches subagents
+ * async and their completion is queued into the PARENT's transcript, which a dead parent CLI
+ * never reads. An unknown/absent state counts as LIVE — the conservative direction, and the
+ * same rule as pendingLaunch's "an unknown dependency state is not satisfied".
+ *
+ * Everything else is a straight lift, and the policy owns every actual decision: this function
+ * never filters, so a node that is ineligible arrives as a row that `planHibernation` refuses.
+ */
+import type { HibernationCandidate } from '../terminal/hibernation-policy'
+
+/** One canvas node as the sweep sees it: its id and the agent it was CREATED as (`data.agentId`,
+ * legacy `tags` fallback — resolved by the caller through the same `createdAgentId` helper the
+ * node's own registration uses, so the filter and the closure agree on what is an agent). */
+export interface HibernationNodeInput {
+ id: string
+ agentId?: string
+}
+
+/** One agent-status entry, narrowed to what the plan reads. */
+export interface HibernationStatusInput {
+ state?: string
+ sessionId?: string
+ hibernated?: boolean
+ lastEventAt?: number
+ /** Present = this node has a `/loop`, `/schedule` or `/cron` on it. Its `dismissed` flag is
+ * deliberately NOT consulted — see the header. */
+ loop?: unknown
+}
+
+/** One subagent card, narrowed: whose it is, and whether it has finished. */
+export interface HibernationSubagentInput {
+ parentNodeId: string
+ status?: string
+}
+
+export interface HibernationCandidateInputs {
+ nodes: HibernationNodeInput[]
+ statusById: Record<string, HibernationStatusInput | undefined>
+ subagents: HibernationSubagentInput[]
+ /** Is this node out of the viewport right now? (The Phase 2 visibility observer's own verdict —
+ * never a second observer.) */
+ isOffscreen: (nodeId: string) => boolean
+ /** Does this node have a live terminal with a registered hibernate pair? */
+ isWired: (nodeId: string) => boolean
+}
+
+export function buildHibernationCandidates(
+ inputs: HibernationCandidateInputs
+): HibernationCandidate[] {
+ // One pass over the cards, so a canvas with a large fan-out doesn't cost nodes × cards.
+ const liveParents = new Set<string>()
+ for (const s of inputs.subagents) {
+ if (s.status !== 'done') liveParents.add(s.parentNodeId)
+ }
+ return inputs.nodes.map((n) => {
+ const st = inputs.statusById[n.id]
+ return {
+ id: n.id,
+ agentId: n.agentId,
+ state: st?.state,
+ sessionId: st?.sessionId,
+ wired: inputs.isWired(n.id),
+ offscreen: inputs.isOffscreen(n.id),
+ hibernated: !!st?.hibernated,
+ recurring: !!st?.loop,
+ liveSubagents: liveParents.has(n.id),
+ lastEventAt: st?.lastEventAt
+ }
+ })
+}
diff --git a/src/renderer/lib/sessionList.ts b/src/renderer/lib/sessionList.ts
index 6d9d27d83..78f86b9e1 100644
--- a/src/renderer/lib/sessionList.ts
+++ b/src/renderer/lib/sessionList.ts
@@ -129,7 +129,12 @@ function toRow(n: SessionNodeInput, status: AgentNodeStatus | undefined): Sessio
stateLabel: STATE_LABEL[statusKind],
unread: !!status?.unread,
session: status?.session,
- loop: status?.loop ? { kind: status.loop.kind, count: status.loop.count } : undefined,
+ // A dismissed cron/schedule entry is retained as a fact (the hibernation guard reads it) but
+ // shows nowhere it did not show before — this chip included.
+ loop:
+ status?.loop && !status.loop.dismissed
+ ? { kind: status.loop.kind, count: status.loop.count }
+ : undefined,
cwd: n.cwd,
sshHost: n.ssh?.host,
sessionId: status?.sessionId,
diff --git a/src/renderer/nodes/LoopNode.tsx b/src/renderer/nodes/LoopNode.tsx
index 9670870df..c252de015 100644
--- a/src/renderer/nodes/LoopNode.tsx
+++ b/src/renderer/nodes/LoopNode.tsx
@@ -36,10 +36,19 @@ export function LoopNode({ id, data, selected }: NodeProps<CanvasNode>) {
// Manual dismiss: cron/schedule cards persist across turns/sessions/restarts, so a job
// removed while the app wasn't watching (or one the user just wants gone) needs an ×.
// Dismissing only drops the CARD — it does not touch the cron job itself.
+ //
+ // …which is why a cron/schedule card is dismissed by MARKING it, not by clearing the entry.
+ // That entry is the only record that this node has a wakeup pending, and it is what keeps Eco
+ // mode from hibernating the node (`/exit` kills the CLI, and the scheduled wakeup dies with it).
+ // Clearing it dropped that guard while the job kept running — the card's own tooltip promises
+ // the opposite. An in-session `/loop` still clears outright: it dies with its session anyway,
+ // so there is no fact left to keep.
const dismiss = (e: React.MouseEvent) => {
e.stopPropagation()
const parentId = id.replace(/^loop-/, '')
- useAgentStatus.getState().setLoop(parentId, false)
+ const cs = useAgentStatus.getState()
+ if (kind === 'cron' || kind === 'schedule') cs.dismissLoopCard(parentId)
+ else cs.setLoop(parentId, false)
useAgentNodes.getState().clearLoop(parentId)
}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index dfc002339..6f69101d7 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -87,10 +87,19 @@ import {
} from '../lib/glyphGridNode'
import { deliverCommand, type DeliveryIo } from '../terminal/command-delivery'
import {
+ agentHibernateFns,
guardConcurrentRestart,
+ isShellCommand,
+ performExitPhase,
performRestartResume,
+ performResumePhase,
+ queryPaneWithin,
+ registerAgentHibernate,
registerAgentRestart,
- restartEligibility
+ restartEligibility,
+ RESTART_EXIT_TIMEOUT_MS,
+ type ExitPhaseOutcome,
+ type ResumePhaseOutcome
} from '../terminal/agent-restart'
import { FindBar } from '../components/FindBar'
import { IconSearch, IconChat, IconMic, IconReload } from '../components/icons'
@@ -627,6 +636,38 @@ const coSubs = new Map<string, (s: CoState) => void>()
*/
const restartSubs = new Map<string, () => void>()
+/**
+ * Which mounted terminals are currently OUT of the viewport, published by the one visibility
+ * observer each node already runs (Phase 2's) — never a second observer, and never a second
+ * verdict: this map only mirrors what that callback decided.
+ *
+ * Read by Canvas's hibernation sweep, which asks about nodes it does not render itself. Keyed by
+ * NODE id (like `restartFns`, not like the session-scoped `termKey` maps) because that is the id
+ * the sweep, the plan and the registry all speak.
+ *
+ * ABSENT = not offscreen. A node that has not reported yet (its observer's first delivery is
+ * queued, or the environment has no IntersectionObserver at all) must never be read as "nobody is
+ * looking at it" — that is the direction that hibernates a session the user is staring at.
+ */
+const offscreenNodes = new Set<string>()
+
+/** How long a freshly mounted node waits before asking to be woken: the spawn its resume line is
+ * written into is still in flight at mount (no session id, no pane). */
+const WAKE_MOUNT_DELAY_MS = 2000
+/** Bounded retries for a wake that came back `'not-eligible'` — timing, not a standing refusal. */
+const WAKE_ATTEMPTS = 3
+const WAKE_RETRY_MS = 4000
+
+function setNodeOffscreen(nodeId: string, offscreen: boolean): void {
+ if (offscreen) offscreenNodes.add(nodeId)
+ else offscreenNodes.delete(nodeId)
+}
+
+/** Is this node out of the viewport? Unknown answers `false` — see `offscreenNodes`. */
+export function isNodeOffscreen(nodeId: string): boolean {
+ return offscreenNodes.has(nodeId)
+}
+
/**
* The mounted instance publishes its copy-feedback sink here, for the same reason as
* `restartSubs`: the OSC 52 handler is registered ONCE per xterm instance and that instance
@@ -994,6 +1035,76 @@ export function TerminalNode({
!remoteSession &&
(data.cwd as string | undefined) !== parentWtPath
const status = useAgentStatus((s) => s.byId[id])
+ // --- Eco / hibernation wake (see terminal/hibernation-policy.ts) ---
+ // A hibernated node's CLI was asked to `/exit` while nobody was looking; its tmux session, pane
+ // and scrollback are untouched, and the conversation comes back with the provider's own
+ // `--resume`. THREE things ask for that here, all through one function:
+ // 1. the visibility observer, on the offscreen→visible edge (the everyday path);
+ // 2. mount-while-already-visible — a node the canvas opens ON SCREEN never transitions, so
+ // after a relaunch (the flag is persisted) nothing would ever ask;
+ // 3. the SLEEPING chip's own click, which is also the escape hatch when the two above have
+ // given up.
+ // Never fired more than once at a time (`wakeInFlightRef`, plus `guardConcurrentRestart` inside
+ // the registered closure), and always re-reads the flag: a wake that raced another one, or a
+ // sweep that landed in between, must not deliver a second launch line into the same pane.
+ const wakeInFlightRef = useRef(false)
+ const wakeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const wakeRef = useRef<(attempt?: number) => void>(() => {})
+ wakeRef.current = (attempt = 0): void => {
+ // A wake that could not run YET is retried a couple of times: at mount the spawn is still in
+ // flight, and a node coming back from an offscreen DISPOSE re-registers its pair one render
+ // later than the visibility edge that asked. Past the attempts it is a standing refusal (the
+ // pane belongs to something else now) and the chip's click is the way forward — nothing keeps
+ // typing into a pane on a timer.
+ const retryLater = (): void => {
+ if (attempt + 1 >= WAKE_ATTEMPTS) return
+ if (wakeTimerRef.current) clearTimeout(wakeTimerRef.current)
+ wakeTimerRef.current = setTimeout(() => wakeRef.current(attempt + 1), WAKE_RETRY_MS)
+ }
+ if (wakeInFlightRef.current) return
+ if (!useAgentStatus.getState().byId[id]?.hibernated) return
+ const fns = agentHibernateFns(id)
+ if (!fns) return retryLater() // no terminal here yet (mid-spawn, or an offscreen revive)
+ wakeInFlightRef.current = true
+ void fns
+ .resume()
+ .then((outcome) => {
+ if (outcome === 'resumed') {
+ useAgentStatus.getState().setHibernated(id, false)
+ return
+ }
+ // 'not-eligible' — usually timing, not a refusal that will stand: at mount the spawn is
+ // still in flight (no session id yet), and right after a reveal tmux may not have answered
+ // `paneCommand` yet. See `retryLater`.
+ retryLater()
+ })
+ .catch(() => {
+ // A transport that threw leaves the node hibernated (and the chip clickable). Reporting a
+ // wake here would clear the badge over a pane nothing was typed into.
+ })
+ .finally(() => {
+ wakeInFlightRef.current = false
+ })
+ }
+ // Ask once shortly after mount, for the node that is ALREADY visible: its observer reports
+ // `visible` with no preceding hidden verdict, and an environment without IntersectionObserver
+ // reports nothing at all. Delayed because the spawn this wake writes into is still in flight at
+ // mount. Skipped while the node is known-offscreen — the reveal edge owns that case.
+ useEffect(() => {
+ const t = setTimeout(() => {
+ if (!isNodeOffscreen(id)) wakeRef.current()
+ }, WAKE_MOUNT_DELAY_MS)
+ return () => {
+ clearTimeout(t)
+ if (wakeTimerRef.current) {
+ clearTimeout(wakeTimerRef.current)
+ wakeTimerRef.current = null
+ }
+ // This node is leaving the canvas: it is nobody's hibernation candidate until it reports
+ // again. (Absent = not offscreen; see `offscreenNodes`.)
+ setNodeOffscreen(id, false)
+ }
+ }, [id])
// Held launch (canvas-control `--after`). Canvas owns firing it; the node only surfaces that
// it is armed, and by WHAT it is blocked — dep titles read straight off the live canvas, since
// "waits for term-17" tells the user nothing.
@@ -2330,6 +2441,20 @@ export function TerminalNode({
unsub()
})
}
+ // Hibernation × cold restore. `hibernated` is PERSISTED, so it can outlive the very thing
+ // it describes:
+ // - `fresh` (the tmux session is GONE — a reboot, a reaped server, a first open): the CLI
+ // it refers to died with the session. The node is not hibernated, it is simply gone, so
+ // the flag is dropped and the ORDINARY cold-restore auto-resume below brings the
+ // conversation back exactly as it does for any other node. Leaving the flag set would
+ // park a SLEEPING chip over a dead pane and hand the resume to the wake path, which
+ // (rightly) refuses a pane it cannot see a shell in.
+ // - warm attach (`!fresh`): the shell we exited to is still sitting in the pane, by
+ // design. Nothing auto-resumes here — the branch below is `fresh`-only — and the wake
+ // path owns the relaunch. That is the whole feature.
+ if (fresh && useAgentStatus.getState().byId[id]?.hibernated) {
+ useAgentStatus.getState().setHibernated(id, false)
+ }
// Run a one-shot command on first open (e.g. "gh auth login" or the agent CLI), then
// forget it.
if (data.initialCommand) {
@@ -2451,6 +2576,68 @@ export function TerminalNode({
})
)
+ // Eco / hibernation (`settings.agentHibernationEnabled`): the same two halves as the restart
+ // above, registered as a PAIR because they are driven far apart in time — Canvas's sweep quits
+ // an idle, offscreen CLI to reclaim its RAM, and the node's own wake resumes the conversation
+ // when the user comes back to it. Same `io`, same `paneCommand`, same `isLive`, same
+ // `guardConcurrentRestart` node id, so a sweep and a menu restart can never write into one pane
+ // at once. Registered in the effect BODY for the same reason as the restart closure: an adopted
+ // (parked → remounted) terminal never reaches the spawn continuation.
+ const unregisterHibernate = registerAgentHibernate(id, {
+ exit: guardConcurrentRestart(id, async (): Promise<ExitPhaseOutcome> => {
+ // SSH / relay sessions are excluded in v1, exactly as the offscreen dispose excludes them
+ // (offscreen-policy.ts): the exit and its much later resume would race the ControlMaster /
+ // relay lifecycle, and a wake that cannot reach the host leaves a dead conversation behind.
+ // Read at CALL time — a local project can BECOME an SSH project long after this mount.
+ if (offscreenRemoteRef.current) return 'not-eligible'
+ const st = useAgentStatus.getState().byId[id]
+ const agentSessionId = st?.sessionId
+ // Re-asked here, not trusted from the plan: a node that started working between the sweep's
+ // decision and its turn must keep its turn (BUSY_STATES — an exit line typed into a
+ // permission prompt ANSWERS it).
+ const gate = restartEligibility(agentId, st?.state, agentSessionId)
+ if (!gate.ok || !agentId || !agentSessionId || !restartTarget()) return 'not-eligible'
+ return performExitPhase({
+ agentId,
+ sessionId: agentSessionId,
+ io: restartIo,
+ paneCommand: () => api.pty.paneCommand(id),
+ isLive: restartTarget
+ })
+ }),
+ resume: guardConcurrentRestart(id, async (): Promise<ResumePhaseOutcome> => {
+ const st = useAgentStatus.getState().byId[id]
+ const agentSessionId = st?.sessionId
+ if (!agentId || !agentSessionId || !restartTarget()) return 'not-eligible'
+ // THE load-bearing gate of the wake half. Hours can pass between the exit and this
+ // resume, and the pane is a REPL the user can type into: by now it may belong to vim, to
+ // `top`, or to a claude the user launched by hand. `deliverCommand`'s first write is NOT
+ // preceded by a Ctrl-U (the exit half is where that lives), so a launch line typed into a
+ // live program is sent to that program — a message to somebody's session, or a mangled
+ // command. A pane we cannot READ answers null and is refused for the same reason.
+ const pane = await queryPaneWithin(() => api.pty.paneCommand(id), RESTART_EXIT_TIMEOUT_MS)
+ if (!isShellCommand(pane)) return 'not-eligible'
+ // Same funnel, same await, same reasoning as the restart closure above: the permission
+ // mode is a property of how a session is LAUNCHED, so it is re-resolved now (a wake can be
+ // hours after the exit, and days after the node was created).
+ const base = resumeCommand(agentId, agentSessionId)
+ const command = base
+ ? withPermissionMode(base, agentId, await ensureActivePermissionMode(agentId))
+ : undefined
+ return performResumePhase({
+ agentId,
+ sessionId: agentSessionId,
+ io: restartIo,
+ command,
+ isLive: restartTarget,
+ onDelivery: (cancel) => {
+ if (life.dead) cancel()
+ else cleanups.push(cancel)
+ }
+ })
+ })
+ })
+
// Coalesce observer bursts: dragging the NodeResizer fires per animation frame, and every
// call is a full cell-geometry measure + a resize IPC → node-pty → tmux (which redraws the
// whole pane). One trailing fit per settle is enough — the canvas node frame itself still
@@ -2629,6 +2816,9 @@ export function TerminalNode({
// Nothing may restart a node that is no longer mounted — park, respawn and real teardown all
// pass through here. A remount re-registers (superseding, so a stale unregister is inert).
unregisterRestart()
+ // …and nothing may hibernate or wake one either: with no registration the sweep reads this
+ // node as unwired (`planHibernation` refuses it) and the wake finds nothing to resume into.
+ unregisterHibernate()
observer.disconnect()
rootObserver.disconnect()
// The visibility observer is NOT disconnected here — it is mount-stable and must outlive an
@@ -2784,7 +2974,16 @@ export function TerminalNode({
// The renderer half first: it reads `wasVisibleRef` as the PREVIOUS verdict for its
// hidden→visible edge test, so the write below must come after it.
visibilityReportRef.current?.(visible)
+ const wasVisible = wasVisibleRef.current
wasVisibleRef.current = visible
+ // Publish the same verdict for the hibernation sweep, which runs in Canvas and cannot see
+ // this node's box. One observer, two consumers — a second observer would be a second
+ // opinion about the same rectangle.
+ setNodeOffscreen(id, !visible)
+ // …and the wake edge: a hibernated node the user has just panned back to gets its
+ // conversation resumed before they can reach for the chip. No-op (one map lookup) for a
+ // node that is not hibernated, which is every node in the default case.
+ if (visible && !wasVisible) wakeRef.current()
// …and the offscreen-dispose state machine. Every decision is the pure
// `planOffscreenVisibility`; this block only executes the plan.
const disposeMs = offscreenDisposeMs(
@@ -3458,7 +3657,28 @@ export function TerminalNode({
RUNNING
</span>
)}
- {showLoop && status?.loop && (
+ {/* Eco: this node's CLI was exited to reclaim its RAM while nobody was looking. The tmux
+ session, the pane and the scrollback are untouched — only the process is gone — and
+ revealing the node resumes the conversation. Clickable because the automatic wake can
+ refuse (a pane that now belongs to something else, a spawn that is still coming up),
+ and a badge with no way forward is a dead end. Muted on purpose: nothing is wrong. */}
+ {status?.hibernated && (
+ <button
+ className="term-node__status term-node__status--sleeping nodrag"
+ title="Agent hibernated to save memory — click to resume"
+ onClick={(e) => {
+ e.stopPropagation()
+ wakeRef.current()
+ }}
+ >
+ <span className="term-node__status-dot" />
+ SLEEPING
+ </button>
+ )}
+ {/* Dismissed (cron/schedule) entries are retained as a fact but hidden everywhere they
+ were shown before — chip included, so the × still does exactly what it always did to
+ the screen. See agentStatus's `loop.dismissed`. */}
+ {showLoop && status?.loop && !status.loop.dismissed && (
<span
className="term-node__status term-node__status--loop"
title={`Running /${status.loop.kind}`}
diff --git a/src/renderer/state/agentStatus.persist.test.ts b/src/renderer/state/agentStatus.persist.test.ts
index 57ccd32b7..5f4fe38d8 100644
--- a/src/renderer/state/agentStatus.persist.test.ts
+++ b/src/renderer/state/agentStatus.persist.test.ts
@@ -98,6 +98,46 @@ describe('loop persistence (cron/schedule survive an app restart)', () => {
expect(useAgentStatus.getState().byId['n6'].lastEventAt).toBe(first)
})
+ it('dismissLoopCard hides the card but KEEPS the entry — the job is still out there', async () => {
+ // The card's × has always promised "does not remove the job", but clearing the entry dropped
+ // the only record that a wakeup is pending — which is what stops Eco mode from `/exit`ing the
+ // CLI the wakeup lives in. So a dismiss now MARKS, and only the render filters on the mark.
+ const store = memStorage()
+ vi.stubGlobal('localStorage', store)
+ const { useAgentStatus } = await import('./agentStatus')
+ useAgentStatus.getState().setLoop('n7', true, 'cron', { schedule: '0 9 * * *' })
+ useAgentStatus.getState().dismissLoopCard('n7')
+ expect(useAgentStatus.getState().byId['n7'].loop).toMatchObject({ kind: 'cron', dismissed: true })
+ const saved = JSON.parse(store.getItem('nodeterm.agentStatus')!)
+ expect(saved.n7.loop).toMatchObject({ kind: 'cron', dismissed: true })
+ // A real end (CronDelete) is still a real clear.
+ useAgentStatus.getState().setLoop('n7', false)
+ expect(useAgentStatus.getState().byId['n7'].loop).toBeUndefined()
+ })
+
+ it('restores `loop.dismissed` on load, and a new recurring event un-dismisses', async () => {
+ vi.stubGlobal(
+ 'localStorage',
+ memStorage({
+ 'nodeterm.agentStatus': JSON.stringify({
+ n8: { unread: false, loop: { count: 1, kind: 'schedule', items: [], dismissed: true } }
+ })
+ })
+ )
+ const { useAgentStatus } = await import('./agentStatus')
+ expect(useAgentStatus.getState().byId['n8'].loop).toMatchObject({ kind: 'schedule', dismissed: true })
+ // setLoop(active) rebuilds the entry from scratch — a freshly created job shows its card again.
+ useAgentStatus.getState().setLoop('n8', true, 'cron')
+ expect(useAgentStatus.getState().byId['n8'].loop?.dismissed).toBeUndefined()
+ })
+
+ it('is a no-op for a node with no loop entry', async () => {
+ vi.stubGlobal('localStorage', memStorage())
+ const { useAgentStatus } = await import('./agentStatus')
+ useAgentStatus.getState().dismissLoopCard('n9')
+ expect(useAgentStatus.getState().byId['n9']).toBeUndefined()
+ })
+
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.ts
index 02de44d62..aa932e8a1 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -78,6 +78,20 @@ export interface AgentNodeStatus {
loop?: {
count: number
kind: 'loop' | 'schedule' | 'cron'
+ /**
+ * The user dismissed the CARD, but the job itself is still out there. Only `cron`/`schedule`
+ * ever carry this: those outlive turns, sessions and app restarts, so "I don't want to look at
+ * this card" and "this job is gone" are different statements — and the card's × has always
+ * said so ("does not remove the job"). An in-session `/loop` still clears outright; it dies
+ * with its session anyway.
+ *
+ * It matters beyond the card: `loop` is the ONLY record that this node has a wakeup pending,
+ * and it is what stops Eco mode from hibernating it (`/exit` kills the CLI process, and the
+ * scheduled wakeup dies with it — a silently cancelled job). Clearing the entry on dismiss
+ * dropped that guard while the job lived on, so the fact is now retained and only the RENDER
+ * filters on it. A real end (CronDelete) still clears the entry.
+ */
+ dismissed?: boolean
/** Schedule expression (cron) shown as a sub-label. */
schedule?: string
/** The task/prompt — shown in full and re-issued by the node's Play button. */
@@ -123,6 +137,9 @@ export interface AgentStatusStore {
kind?: 'loop' | 'schedule' | 'cron',
opts?: { schedule?: string; task?: string }
): void
+ /** Hide a cron/schedule CARD while keeping the fact that the job exists (see `loop.dismissed`).
+ * No-op if the node has no loop entry. */
+ dismissLoopCard(id: string): void
/** Record a /loop iteration (count++ and append its summary). No-op if not looping. */
bumpLoop(id: string, message?: string): void
remove(id: string): void
@@ -210,6 +227,9 @@ export function createAgentStatusSession(
task: v.loop.task,
items: Array.isArray(v.loop.items) ? v.loop.items : []
}
+ // A dismissed card must STAY dismissed across a restart — and the fact it hides
+ // (a live cron/schedule job) must stay readable to the hibernation guard.
+ if (v.loop.dismissed) out[id].loop.dismissed = true
}
}
return out
@@ -392,6 +412,15 @@ export function createAgentStatusSession(
return { byId }
}),
+ dismissLoopCard: (id) =>
+ set((s) => {
+ const prev = s.byId[id]
+ if (!prev?.loop || prev.loop.dismissed) return s
+ const byId = { ...s.byId, [id]: { ...prev, loop: { ...prev.loop, dismissed: true } } }
+ save(byId)
+ return { byId }
+ }),
+
bumpLoop: (id, message) =>
set((s) => {
const prev = s.byId[id]
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 88b0011af..cc37bbd76 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -1396,6 +1396,25 @@ body,
color: #bf7af0;
}
+/* SLEEPING: the agent CLI was exited to reclaim its RAM (Eco); the session itself is fine, so
+ this is the quietest chip on the header — grey, no pulse. It is a <button> (click = resume),
+ which the base chip's styling does not cover. */
+.term-node__status--sleeping {
+ color: var(--muted);
+ background: none;
+ border: none;
+ padding: 0;
+ font: inherit;
+ font-size: 9.5px;
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ cursor: pointer;
+}
+
+.term-node__status--sleeping:hover {
+ color: var(--text);
+}
+
.term-node__status--attention .term-node__status-dot {
animation: nt-pulse 1.1s ease-in-out infinite;
}
@@ -7607,6 +7626,11 @@ body,
color: var(--warn);
background: rgba(255, 159, 10, 0.12);
}
+/* Eco: the agent CLI was exited to reclaim RAM. Quiet — the session is fine. */
+.kanban-badge--sleeping {
+ color: var(--muted);
+ background: rgba(var(--tint-rgb), 0.08);
+}
.kanban-card__unread {
width: 7px;
height: 7px;
diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.ts
index 3ac3881f7..0bd74e854 100644
--- a/src/renderer/terminal/agent-restart.ts
+++ b/src/renderer/terminal/agent-restart.ts
@@ -88,8 +88,17 @@ export const RESTART_DELIVERY_TIMEOUT_MS = DELIVERY_ATTEMPTS * VERIFY_TIMEOUT_MS
* One bounded pane query. Unbounded, a wedged tmux server (or a relay whose IPC never answers)
* would hang the restart — and with it the bulk run's summary — forever. A lapsed, failed or
* empty query reads as `null`: "we cannot see this pane right now".
+ *
+ * Exported for hibernation's WAKE, which asks the same question for a sharper reason: hours pass
+ * between the exit and the resume, so the pane may since have been given to vim, to `top`, or to a
+ * CLI the user launched by hand — and the resume's first write is un-KILL_LINE'd, so it would be
+ * spliced into whatever is there. One definition, not a second copy in the node (a duplicated rule
+ * drifts; see CLAUDE.md's "Adding a new agent" rule 10).
*/
-async function queryPane(fn: () => Promise<string | null>, ms: number): Promise<string | null> {
+export async function queryPaneWithin(
+ fn: () => Promise<string | null>,
+ ms: number
+): Promise<string | null> {
let lapse: ReturnType<typeof setTimeout> | undefined
try {
return await Promise.race([
@@ -159,7 +168,7 @@ export async function performExitPhase(d: {
// ── Pre-flight: prove we can SEE this pane before quitting anything in it (see the header).
// Reported as `'not-eligible'`, the outcome that means "not a target right now" and is the one
// the menu and the notice already have wording for. Nothing has been written at this point.
- const before = await queryPane(d.paneCommand, timeoutMs)
+ const before = await queryPaneWithin(d.paneCommand, timeoutMs)
if (before === null || gone()) return 'not-eligible'
// Clear the prompt before typing the exit command. The pane is a REPL the user types into: a
// half-written prompt left in it would otherwise be submitted as `…refactor the/exit` — the
@@ -178,7 +187,7 @@ export async function performExitPhase(d: {
let last: string | null = null
for (;;) {
await new Promise((r) => setTimeout(r, pollMs))
- const pane = await queryPane(d.paneCommand, Math.max(0, deadline - Date.now()))
+ const pane = await queryPaneWithin(d.paneCommand, Math.max(0, deadline - Date.now()))
if (gone()) return 'not-eligible' // stop polling a pane that no longer exists
// Two ways to know the CLI let go of the pane. The allowlist is the confident one and is
// taken immediately. The other — "the foreground command is no longer what it was before the
diff --git a/src/renderer/terminal/hibernation-policy.ts b/src/renderer/terminal/hibernation-policy.ts
index ecfff6900..9465b0055 100644
--- a/src/renderer/terminal/hibernation-policy.ts
+++ b/src/renderer/terminal/hibernation-policy.ts
@@ -37,6 +37,10 @@ import { restartEligibility } from './agent-restart'
/** How many sessions one hibernation pass may take. */
export const HIBERNATE_BATCH_MAX = 2
+/** How often the canvas re-asks. Coarse on purpose: the shortest window the setting offers is
+ * measured in minutes, so a faster sweep would only pay for a plan that cannot have changed. */
+export const HIBERNATE_SWEEP_MS = 60_000
+
export interface HibernationCandidate {
id: string
agentId?: string