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(agents): pause a session so it does not auto-resume on reopen
Mina Sameh4037a1202659
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex e1836b311..46c576882 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -264,6 +264,7 @@ import { transport } from '../terminal/local-transport'import { sshFs } from '../terminal/ssh-fs'import {agentHibernateFns,+ agentPauseFns,agentRestartFn,guardConcurrentRestart,planBulkRestart,@@ -5545,6 +5546,74 @@ export function Canvas() {)}, [setNodes, markDirty])+ // Manual "Pause session" (node context menu — canvas right-click and the sessions sidebar row+ // menu, which reuses the same `selectionItems` builder; no command palette entry or kanban-card+ // button yet, deliberately deferred): quit the CLI+ // (and, when `deep`, also recycle the tmux session) and mark the node PAUSED — see+ // `registerAgentPause` for why this is its own closure rather than `agentHibernateFns.exit()`.+ const pauseAgentNode = useCallback(async (nodeId: string, deep: boolean) => {+ const fns = agentPauseFns(nodeId)+ if (!fns) return // node unmounted between opening the menu and clicking+ let outcome: Awaited<ReturnType<typeof fns.pause>>+ try {+ outcome = await fns.pause(deep)+ } catch {+ setNotice({+ kind: 'error',+ text: 'Pause failed: this session could not be reached. Check the pane before retrying.'+ })+ return+ }+ setNotice(+ outcome === 'paused'+ ? {+ kind: 'info',+ text: deep+ ? 'Session paused and ended — reopen or click Resume to bring it back.'+ : 'Session paused — click Resume to bring it back.'+ }+ : outcome === 'exit-timeout'+ ? {+ kind: 'error',+ text:+ 'Pause failed: the pane did not return to a shell in time, so nothing was paused. ' ++ 'Nothing was killed — check the pane.'+ }+ : {+ kind: 'error',+ text:+ 'Pause skipped: this session is busy, already restarting, not attached, or has ' ++ 'nothing to resume. Nothing was written to the pane.'+ }+ )+ }, [])++ // Bring a paused (or ordinarily hibernated) node's conversation back. Routed through the SAME+ // `wakeHibernatedNode` trigger the SLEEPING/PAUSED chip and the mount/visibility auto-wakes use+ // — NOT a direct `agentHibernateFns(id).resume()` call — because that trigger is what brackets+ // the delivery with `WakeInputBuffer` (holds/flushes whatever the user types during the+ // echo-verified delivery, so it can't splice into `claude --resume <sid>`) and retries a timing+ // `'not-eligible'` a few times (`WAKE_ATTEMPTS`) instead of giving up on the first ask. A menu+ // click reaching straight into the closure got neither, and the node is typically ON SCREEN and+ // focusable at exactly the moment the user chooses Resume — the worst possible pane to miss that+ // protection on.+ const resumeAgentNode = useCallback((nodeId: string) => {+ if (!agentHibernateFns(nodeId)) {+ // Same "not attached" case the Restart row's `why` covers via `agentRestartFn` — an+ // offscreen-RELEASED node (lifecycle torn down in place, still listed in the sidebar) has no+ // registration to wake, and silently doing nothing here reads as a broken button.+ setNotice({+ kind: 'error',+ text: 'Resume skipped: this terminal is not attached right now.'+ })+ return+ }+ wakeHibernatedNode(nodeId)+ // The trigger is fire-and-forget (it owns its own retries and clears `hibernated`/`paused` on+ // a confirmed resume), so this is deliberately a status line, not a result.+ setNotice({ kind: 'info', text: 'Resuming…' })+ }, [])+// S6 §3.5 — originate an owner-authorized Codex account SWITCH for a running node, then recycle// its pane onto the target account. The renderer is NOT the security boundary: PR 5's three-phase// handler is owner-authorized (only the WebContents that reserved may commit/finish) and refuses a@@ -6853,6 +6922,21 @@ export function Canvas() {// not run per menu RENDER. Both reach the user through `restartAgentNode`'s skip// notice, which names them, rather than through a hint this row cannot compute.undefined+ // Pause/Resume have their OWN eligibility, computed on `st?.sessionId` alone — NOT+ // `sessionId` above, which also falls back to `n?.data.agentSessionId` (the id+ // nodeterm minted at node creation, for a node whose hooks never landed). The `pause`/+ // `resume` closures registered on the node gate on the live `st?.sessionId` only (see+ // `registerAgentPause` / the hibernate `resume` closure), so a menu row lit by the+ // fallback would enable here and then refuse in the closure with a generic "busy /+ // not attached" notice about a node that is actually just idle with no reported id+ // yet. Using the same narrower fact keeps what the row PROMISES in sync with what the+ // closure can actually do.+ const pauseGate = restartEligibility(sourceAgentId, st?.state, st?.sessionId)+ const pauseWhy = !pauseGate.ok+ ? pauseGate.reason === 'working'+ ? 'This session is busy — try again once its turn (or permission prompt) is done.'+ : 'Nothing to resume yet — this session has not reported an id.'+ : undefinedreturn [{label: 'Restart agent',@@ -6989,7 +7073,46 @@ export function Canvas() {}] as MenuItem[]})()- : [])+ : []),+ // Pause session: quit the CLI (and, for the deeper choice, also end the tmux+ // session) so it does NOT auto-resume on the next reveal or reopen — only an+ // explicit Resume brings it back. Same eligibility as Restart above (`why`): a node+ // this app cannot quit-and-resume has nothing for pause to do either. Already-paused+ // shows Resume instead — the two never appear together.+ ...(st?.paused+ ? ([+ {+ label: 'Resume session',+ icon: <IconPower />,+ hint: 'Brings the conversation back.',+ onClick: () => void resumeAgentNode(ids[0])+ }+ ] as MenuItem[])+ : ([+ {+ type: 'submenu',+ label: 'Pause session',+ icon: <IconPower />,+ children: [+ {+ label: 'Pause',+ disabled: !!pauseWhy,+ hint:+ pauseWhy ??+ 'Quits the CLI; the tmux session stays so Resume is fast. Frees most of the memory.',+ onClick: () => void pauseAgentNode(ids[0], false)+ },+ {+ label: 'Pause & end session',+ disabled: !!pauseWhy,+ hint:+ pauseWhy ??+ 'Quits the CLI and ends its tmux session too, for a fuller memory reclaim. Resume starts a fresh session with the same conversation.',+ onClick: () => void pauseAgentNode(ids[0], true)+ }+ ]+ }+ ] as MenuItem[]))] as MenuItem[]})(): []),@@ -7009,6 +7132,8 @@ export function Canvas() {toggleMarkdown,reloadTerminals,restartAgentNode,+ pauseAgentNode,+ resumeAgentNode,switchCodexAccountNode,connectedProjectIdForHost,deleteNodes,@@ -7730,11 +7855,15 @@ export function Canvas() {// `isNodeWatched`, so the modal clause cannot go missing from one of them.setWatchedNode(id)// Opening a card IS opening the session — the second way in, and the one the canvas- // visibility observer says nothing about. A hibernated node reached this way resumes its- // conversation just as it would on a pan-back, instead of showing the bare shell it was- // exited to with nothing on screen to explain it. No-op for every node that is not- // hibernated (the node re-reads the flag itself).- if (id) wakeHibernatedNode(id)+ // visibility observer says nothing about. A hibernated (but NOT paused) node reached this+ // way resumes its conversation just as it would on a pan-back, instead of showing the bare+ // shell it was exited to with nothing on screen to explain it. No-op for every node that is+ // not hibernated (the node re-reads the flag itself). `paused` is excluded — same rule as+ // the mount-timer and visibility-edge auto-triggers: a paused node must not auto-resume on+ // ANY reveal, the card modal included, or "only an explicit Resume brings it back" would be+ // false the moment the user opens the card. The modal shows the PAUSED chip; Resume is still+ // reachable from the node menu.+ if (id && !useAgentStatus.getState().byId[id]?.paused) wakeHibernatedNode(id)}, [])const onPaletteQuery = useCallback((q: string) => {@@ -10128,6 +10257,11 @@ export function Canvas() {// which would let a late Stop POST undo a hibernation we just performed. The setter// bails when the flag is already unset, so this is free for every other session start.cs.setHibernated(e.nodeId, false)+ // Same self-heal, same reason, for the deep "pause & end session" case: that depth+ // recycles the tmux session instead of leaving `hibernated` set, so this SessionStart+ // (the cold-restore's own resume, or a hand-launched relaunch) is the only live proof+ // that node was watching for.+ cs.setPaused(e.nodeId, false)}if (e.sessionPhase === 'end') {cs.setState(e.nodeId, undefined, e.agentId)@@ -10210,6 +10344,11 @@ export function Canvas() {enabled: s.agentHibernationEnabled,idleMinutes: s.agentHibernationIdleMinutes})+ // "Keep paused after closing" (settings.agentHibernationPersistAcrossRestart): an Eco+ // exit ALSO marks the node paused, so it survives a project/app reopen instead of the+ // ordinary auto-resume-on-reveal. Read once per pass, not per node — a mid-pass toggle+ // should not split one batch across two behaviors.+ const persistAcrossRestart = s.agentHibernationPersistAcrossRestart// 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) {@@ -10219,13 +10358,16 @@ export function Canvas() {try {if ((await fns.exit()) === 'exited') {useAgentStatus.getState().setHibernated(nodeId, true)+ if (persistAcrossRestart) useAgentStatus.getState().setPaused(nodeId, true)// A batch can take ~12 s, and the user may have arrived during it. The node's own// exit closure re-checks visibility before writing anything, but the pan can also// land in the window between that check and this line — and by then the visible// EDGE has passed, so no wake trigger is left and the node would sit SLEEPING in// front of the user. Nudge it: the node re-reads the flag itself, so this is a- // no-op wherever the user did not arrive.- if (isNodeWatched(nodeId)) wakeHibernatedNode(nodeId)+ // no-op wherever the user did not arrive. Skipped when this pass just paused the+ // node — the setting's whole point is "no auto-resume", live-arrival edge case+ // included; the SLEEPING/PAUSED chip is still right there to click.+ if (!persistAcrossRestart && isNodeWatched(nodeId)) wakeHibernatedNode(nodeId)}// '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 thediff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsxindex f15cc82ef..48a571809 100644--- a/src/renderer/components/kanban/SessionCard.tsx+++ b/src/renderer/components/kanban/SessionCard.tsx@@ -56,9 +56,11 @@ export const SessionCard = memo(function SessionCard({? 'running': session.kind !== 'sticky' && (status?.state === 'waiting' || status?.state === 'blocked')? 'needs'- : session.kind !== 'sticky' && status?.hibernated- ? 'sleeping'- : null+ : session.kind !== 'sticky' && status?.paused+ ? 'paused'+ : session.kind !== 'sticky' && status?.hibernated+ ? 'sleeping'+ : nullconst stickyPreview = session.kind === 'sticky' ? (session.text ?? '').trim() : ''const assignees = meta?.assignees ?? []const due = meta?.dueAt@@ -108,6 +110,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 === 'paused' && (+ <span+ className="kanban-badge kanban-badge--sleeping"+ title="Session paused — use Resume session from the node menu to bring it back"+ >+ PAUSED+ </span>+ )}{badge === 'sleeping' && (<spanclassName="kanban-badge kanban-badge--sleeping"diff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsxindex a8357520a..db877137f 100644--- a/src/renderer/components/settings/sections/AgentsSection.tsx+++ b/src/renderer/components/settings/sections/AgentsSection.tsx@@ -134,7 +134,11 @@ const ROWS = {'resume','offscreen','minutes',- 'sleep'+ 'sleep',+ 'pause',+ 'paused',+ 'restart',+ 'reopen']}}@@ -513,6 +517,18 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El</div>}/>+ <FieldRow+ label="Keep paused after closing"+ description="When Eco hibernates a session, also keep it paused across a project/app reopen instead of auto-resuming — only an explicit Resume brings it back. Manual “Pause session” always persists this way, whatever this is set to."+ control={+ <Switch+ checked={settings.agentHibernationPersistAcrossRestart}+ ariaLabel="Keep paused after closing"+ disabled={!settings.agentHibernationEnabled}+ onChange={(on) => update({ agentHibernationPersistAcrossRestart: on })}+ />+ }+ /></SearchableRow></SettingsSection>)diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 4318c8a5d..0a8c50101 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -115,11 +115,13 @@ import {performResumePhase,queryPaneWithin,registerAgentHibernate,+ registerAgentPause,registerAgentRestart,restartEligibility,restartSessionId,RESTART_EXIT_TIMEOUT_MS,type ExitPhaseOutcome,+ type PauseOutcome,type ResumePhaseOutcome} from '../terminal/agent-restart'import { WakeInputBuffer } from '../terminal/wake-input-buffer'@@ -1476,7 +1478,12 @@ export function TerminalNode({wakeTimerRef.current = setTimeout(() => wakeRef.current(attempt + 1), WAKE_RETRY_MS)}if (wakeInFlightRef.current) return- if (!useAgentStatus.getState().byId[id]?.hibernated) return+ // Answers a manual Resume for BOTH pause depths, not only ordinary hibernation: a `paused`+ // node may or may not also be `hibernated` (the deep "pause & end session" recycles the tmux+ // session instead, leaving `hibernated` unset), but either flag means there is a conversation+ // this closure knows how to bring back.+ const stNow = useAgentStatus.getState().byId[id]+ if (!stNow?.hibernated && !stNow?.paused) returnconst fns = agentHibernateFns(id)if (!fns) return retryLater() // no terminal here yet (mid-spawn, or an offscreen revive)wakeInFlightRef.current = true@@ -1491,6 +1498,7 @@ export function TerminalNode({wakeInputBufferRef.current.endWake(outcome === 'resumed', paneWriteRef.current)if (outcome === 'resumed') {useAgentStatus.getState().setHibernated(id, false)+ useAgentStatus.getState().setPaused(id, false)return}// 'not-eligible' — usually timing, not a refusal that will stand: at mount the spawn is@@ -1518,7 +1526,10 @@ export function TerminalNode({const trigger = (): void => wakeRef.current()wakeSubs.set(id, trigger)const t = setTimeout(() => {- if (isNodeWatched(id)) wakeRef.current()+ // A `paused` node never auto-wakes, mount included — the trigger published above (and the+ // chip's own click) remain the explicit way back. `hibernated`-only nodes are unaffected:+ // this is the everyday Eco auto-resume-on-view path.+ if (isNodeWatched(id) && !useAgentStatus.getState().byId[id]?.paused) wakeRef.current()}, WAKE_MOUNT_DELAY_MS)return () => {clearTimeout(t)@@ -3051,12 +3062,17 @@ export function TerminalNode({if (fresh && useAgentStatus.getState().byId[id]?.hibernated) {useAgentStatus.getState().setHibernated(id, false)}+ // Paused (see agentStatus.paused) is the ONE exception to the "fresh always resumes" rule+ // above: it exists precisely to survive a cold restart, so it must NOT be dropped here, and+ // the auto-resume branch below must be skipped — only an explicit Resume (which reuses the+ // same command-building path through the registered hibernate/wake pair) may relaunch it.+ const pausedNow = !!useAgentStatus.getState().byId[id]?.paused// Run a one-shot command on first open (e.g. "gh auth login" or the agent CLI), then// forget it.if (data.initialCommand) {writeWhenShellReady(data.initialCommand)updateNodeData(id, { initialCommand: undefined })- } else if (fresh && agentId && canResume(agentId)) {+ } else if (fresh && agentId && canResume(agentId) && !pausedNow) {// Cold restart of an agent node: the live agent is gone, so re-launch it. Resume the// prior conversation by its session id when we have one; otherwise start the agent// fresh. Plain terminals get nothing here — just the restored shell.@@ -3116,6 +3132,19 @@ export function TerminalNode({agentEnvSnapshot())if (cmd) writeWhenShellReady(cmd) // same shell-startup race as initialCommand+ } else if (fresh && pausedNow) {+ // The auto-resume above was skipped (that's the feature), but this mount's PANE is+ // brand new either way — tmux respawned it, whether from the deep "pause & end session"+ // recycle or from a genuine reboot that took a shallow-paused session's tmux with it.+ // The later Resume's pane-recognition (`isShellCommand(pane)` OR the recorded+ // `hibernatedPane` — see performExitPhase's wake half) would otherwise refuse a user+ // whose default shell sits outside the `isShellCommand` allowlist (nu/xonsh/pwsh)+ // forever: a PAUSED chip that can never resume, with a live conversation on disk. Record+ // what this fresh pane actually is, the same way the exit half does — replacing any+ // stale value a pre-reboot shallow pause left behind, which described a pane that no+ // longer exists.+ const settled = await queryPaneWithin(() => api.pty.paneCommand(id), RESTART_EXIT_TIMEOUT_MS)+ useAgentStatus.getState().setHibernatedPane(id, settled)}}).catch((err: unknown) => {@@ -3441,6 +3470,67 @@ export function TerminalNode({})})+ // Manual "Pause session" (node context menu — shared by the canvas right-click and the+ // sessions sidebar row menu, which reuses this same `selectionItems` builder; no command+ // palette entry or kanban-card-modal button yet, deliberately deferred): quit the CLI+ // and mark the node PAUSED so it does NOT auto-resume on the next reveal or cold restart — an+ // explicit Resume (which reuses `agentHibernateFns(id).resume()` above, unchanged) is the only+ // way back. Deliberately its OWN closure rather than a call into `agentHibernateFns(id).exit()`:+ // that one refuses a node the user is currently WATCHING (`isNodeWatched`) — exactly right for+ // Eco's own sweep, exactly wrong for a manual pause of the node the user is looking at right now.+ const unregisterPause = registerAgentPause(id, {+ pause: guardConcurrentRestart(id, async (deep: boolean): Promise<PauseOutcome> => {+ // Deep pause recycles the tmux session, which — like `restartShell`'s recycle — must not+ // run on a relay session's core (its shell env belongs to the HOST, not this one). Shallow+ // pause touches no shell env and is allowed over SSH/relay, same as ordinary Restart/exit.+ if (deep && session.source === 'relay') return 'not-eligible'+ const st = useAgentStatus.getState().byId[id]+ const agentSessionId = st?.sessionId+ const gate = restartEligibility(agentId, st?.state, agentSessionId)+ if (!gate.ok || !agentId || !agentSessionId || !restartTarget()) return 'not-eligible'+ // Already hibernated (Eco already exited this CLI, or a prior shallow pause): the pane is+ // ALREADY a bare shell, so asking it to quit again would type `/exit` into that shell as a+ // real command — junk output, and it would eat any half-typed line the user left there.+ // Skip straight to marking (and, if deep, recycling) — there is nothing left to exit.+ const alreadyExited = !!st?.hibernated+ const outcome = alreadyExited+ ? 'exited'+ : await performExitPhase({+ agentId,+ sessionId: agentSessionId,+ io: restartIo,+ paneCommand: () => api.pty.paneCommand(id),+ isLive: restartTarget+ })+ if (outcome !== 'exited') return outcome+ if (deep) {+ // "Pause & end session": also recycle the tmux session for a fuller memory reclaim — the+ // exact mechanism `restartAgentNode(…, restartShell: true)` uses, minus the auto-relaunch:+ // the next mount is `fresh`, and `paused` (set below, before the recycle takes effect)+ // is what keeps that mount's cold-restore auto-resume from firing.+ useAgentStatus.getState().setPaused(id, true)+ transport.recycle(id)+ updateNodeData(id, (node) => ({+ respawnNonce: ((node.data.respawnNonce as number | undefined) ?? 0) + 1+ }))+ } else if (alreadyExited) {+ // The pane and its recorded `hibernatedPane` are already correct (Eco/a prior pause set+ // them); only the durability changes.+ useAgentStatus.getState().setPaused(id, true)+ } else {+ // Shallow "Pause": identical to an Eco exit — tmux/pane untouched, `hibernated` records+ // it so the SLEEPING machinery (pane-recognition on wake) still applies — plus `paused`,+ // which is the only thing that changes: no auto-wake on reveal, and no auto-resume should+ // the tmux session itself later die and come back `fresh` (a reboot, e.g.).+ const settled = await queryPaneWithin(() => api.pty.paneCommand(id), RESTART_EXIT_TIMEOUT_MS)+ useAgentStatus.getState().setHibernatedPane(id, settled)+ useAgentStatus.getState().setHibernated(id, true)+ useAgentStatus.getState().setPaused(id, true)+ }+ return 'paused'+ })+ })+// 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@@ -3622,6 +3712,7 @@ export function TerminalNode({// …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()+ unregisterPause()observer.disconnect()rootObserver.disconnect()// The visibility observer is NOT disconnected here — it is mount-stable and must outlive an@@ -3801,8 +3892,9 @@ export function TerminalNode({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()+ // node that is not hibernated, which is every node in the default case. A `paused` node is+ // excluded — see the mount-timer trigger above for why.+ if (visible && !wasVisible && !useAgentStatus.getState().byId[id]?.paused) wakeRef.current()// A visible node is not in an offscreen stretch at all — the next hidden edge starts a// fresh clock for the Eco deferral's cap.if (visible) offscreenSinceRef.current = null@@ -4572,18 +4664,32 @@ export function TerminalNode({revealing the node resumes the conversation. Clickable because the automatic wake canrefuse (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 && (+ {status?.paused ? (<button- className="term-node__status term-node__status--sleeping nodrag"- title="Agent hibernated to save memory — click to resume"+ className="term-node__status term-node__status--paused nodrag"+ title="Session paused — click to resume"onClick={(e) => {e.stopPropagation()wakeRef.current()}}><span className="term-node__status-dot" />- SLEEPING+ PAUSED</button>+ ) : (+ 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 theywere shown before — chip included, so the × still does exactly what it always did todiff --git a/src/renderer/state/agentStatus.persist.test.ts b/src/renderer/state/agentStatus.persist.test.tsindex 9d82df980..e3cd8f646 100644--- a/src/renderer/state/agentStatus.persist.test.ts+++ b/src/renderer/state/agentStatus.persist.test.ts@@ -173,6 +173,111 @@ describe('loop persistence (cron/schedule survive an app restart)', () => {expect(useAgentStatus.getState().byId['n4']?.hibernated).toBe(true)})+ it('persists `paused` and drops the key on resume', async () => {+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setPaused('n20', true)+ expect(JSON.parse(store.getItem('nodeterm.agentStatus')!).n20.paused).toBe(true)+ useAgentStatus.getState().setPaused('n20', false)+ expect(JSON.parse(store.getItem('nodeterm.agentStatus') ?? '{}').n20?.paused).toBeUndefined()+ })++ it('`paused` persists INDEPENDENTLY of `hibernated` — the deep pause recycles tmux, so a paused node can carry no hibernated flag at all', async () => {+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setPaused('n21', true)+ const saved = JSON.parse(store.getItem('nodeterm.agentStatus')!).n21+ expect(saved.paused).toBe(true)+ expect(saved.hibernated).toBeUndefined()+ })++ it('persists `hibernatedPane` for a PAUSED node even with `hibernated` unset — the deep pause records what its recycled pane settled to, and needs the record to survive a restart just as `paused` does', async () => {+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setPaused('n26', true)+ useAgentStatus.getState().setHibernatedPane('n26', 'nu')+ const saved = JSON.parse(store.getItem('nodeterm.agentStatus')!).n26+ expect(saved).toMatchObject({ paused: true, hibernatedPane: 'nu' })+ expect(saved.hibernated).toBeUndefined()+ })++ it('restores `hibernatedPane` on load for a paused (not hibernated) node', async () => {+ vi.stubGlobal(+ 'localStorage',+ memStorage({+ 'nodeterm.agentStatus': JSON.stringify({+ n27: { unread: false, sessionId: 's', paused: true, hibernatedPane: 'nu' }+ })+ })+ )+ const { useAgentStatus } = await import('./agentStatus')+ expect(useAgentStatus.getState().byId['n27']).toMatchObject({ paused: true, hibernatedPane: 'nu' })+ })++ it('setPaused(false) drops `hibernatedPane` when it was the only owner, but leaves it standing for `hibernated`', async () => {+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ // paused-only: resuming drops the pane record too.+ useAgentStatus.getState().setPaused('n28', true)+ useAgentStatus.getState().setHibernatedPane('n28', 'nu')+ useAgentStatus.getState().setPaused('n28', false)+ expect(useAgentStatus.getState().byId['n28'].hibernatedPane).toBeUndefined()+ // hibernated AND paused together: resuming `paused` alone leaves `hibernated`'s copy intact.+ useAgentStatus.getState().setHibernated('n29', true)+ useAgentStatus.getState().setHibernatedPane('n29', 'nu')+ useAgentStatus.getState().setPaused('n29', true)+ useAgentStatus.getState().setPaused('n29', false)+ expect(useAgentStatus.getState().byId['n29'].hibernatedPane).toBe('nu')+ })++ it('clears `paused` on a LIVE state — same self-heal as `hibernated`', async () => {+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ for (const state of ['working', 'blocked', 'waiting'] as const) {+ useAgentStatus.getState().setPaused('n22', true)+ useAgentStatus.getState().setState('n22', state, 'claude')+ expect(useAgentStatus.getState().byId['n22'].paused, state).toBeUndefined()+ expect(JSON.parse(store.getItem('nodeterm.agentStatus')!).n22?.paused, state).toBeUndefined()+ useAgentStatus.getState().setState('n22', undefined)+ }+ })++ it('keeps `paused` through a `done` event — same as `hibernated`, and through a cold restart (this store never clears it on its own)', async () => {+ vi.stubGlobal('localStorage', memStorage())+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setPaused('n23', true)+ useAgentStatus.getState().setState('n23', 'done', 'claude')+ expect(useAgentStatus.getState().byId['n23'].paused).toBe(true)+ })++ it('resuming restarts the idle clock, so a long-paused session is not immediately re-eligible for Eco', async () => {+ vi.stubGlobal('localStorage', memStorage())+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.setState({+ byId: { n24: { unread: false, state: 'done', lastEventAt: Date.now() - 6 * 3600_000, paused: true } }+ })+ useAgentStatus.getState().setPaused('n24', false)+ const st = useAgentStatus.getState().byId['n24']+ expect(st.paused).toBeUndefined()+ expect(Date.now() - st.lastEventAt!).toBeLessThan(5000)+ })++ it('restores `paused` on load', async () => {+ vi.stubGlobal(+ 'localStorage',+ memStorage({+ 'nodeterm.agentStatus': JSON.stringify({ n25: { unread: false, sessionId: 's', paused: true } })+ })+ )+ const { useAgentStatus } = await import('./agentStatus')+ expect(useAgentStatus.getState().byId['n25']?.paused).toBe(true)+ })+it('never persists `lastEventAt` — a stale idle clock would hibernate on relaunch', async () => {const store = memStorage()vi.stubGlobal('localStorage', store)diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex 85970d5fa..655a14feb 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -91,6 +91,18 @@ export interface AgentNodeStatus {* one specific string, on one specific node, recorded by us.*/hibernatedPane?: string+ /**+ * The user (or Eco's idle sweep, when `settings.agentHibernationPersistAcrossRestart` is on)+ * explicitly PAUSED this node: its CLI was exited (and, for the deeper "pause & end session"+ * choice, its tmux session recycled too) and it must NOT auto-resume on the next reveal or on+ * a cold restart — only an explicit Resume brings it back. PERSISTED, and — unlike `hibernated`+ * — deliberately NOT cleared by a `fresh` cold restore: that self-heal is what lets Eco's+ * ordinary hibernation "come back automatically when reopened", which is exactly the behavior+ * this flag exists to opt a node OUT of. Cleared only by an explicit resume or by a genuine+ * live hook event (see `setState`'s self-heal) — the same self-heal `hibernated` gets, for the+ * same reason: a live state is proof the CLI is running, so a standing `paused` would be wrong.+ */+ paused?: 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. */@@ -162,6 +174,10 @@ export interface AgentStatusStore {/** Record what the pane settled to when this node's CLI let go of it (`null` = forget: a stale* value must never permit a wake into a pane we did not measure). See `hibernatedPane`. */setHibernatedPane(id: string, pane: string | null): void+ /** Mark the node explicitly paused (true) or resumed (false). Persisted; see `paused`. Waking+ * restarts the idle clock, same as `setHibernated` — a resumed session must not read as having+ * been idle since before the pause. */+ setPaused(id: string, on: boolean): void/** Record that this node just launched a background shell task (see `backgroundTaskAt`).* Transient — nothing is written to localStorage. */markBackgroundTask(id: string): void@@ -260,10 +276,18 @@ export function createAgentStatusSession(// 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- // Only alongside the flag: the pane we exited TO is meaningless (and, as a wake- // permission, unwanted) once the node is not hibernated any more.- if (v.hibernated && typeof v.hibernatedPane === 'string')+ // Alongside EITHER flag: `hibernated` is the ordinary case (the pane we exited TO), but a+ // `paused` node with `hibernated` unset needs it just as much — the deep "pause & end+ // session" choice, and a shallow pause whose tmux session died in a reboot (`fresh` clears+ // `hibernated` but not `paused`), both leave the wake with a brand-new pane to recognize,+ // and this is the only record of what that pane turned out to be (see the cold-restore+ // gate in TerminalNode.tsx). Meaningless (and, as a wake permission, unwanted) once+ // NEITHER flag holds.+ if ((v.hibernated || v.paused) && typeof v.hibernatedPane === 'string')out[id].hibernatedPane = v.hibernatedPane+ // Independent of `hibernated`: the deep "pause & end session" choice recycles the tmux+ // session, so a paused node can perfectly well hydrate with `hibernated` unset.+ if (v.paused) out[id].paused = 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) {@@ -291,7 +315,7 @@ 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 || v.hibernated) {+ if (v.unread || v.session || v.sessionId || v.loop || v.agentId || v.hibernated || v.paused) {out[id] = {unread: v.unread,session: v.session,@@ -299,8 +323,9 @@ export function createAgentStatusSession(agentId: v.agentId,loop: v.loop,hibernated: v.hibernated,- // Never written without the flag it belongs to (see `hibernatedPane`).- hibernatedPane: v.hibernated ? v.hibernatedPane : undefined+ // Never written without a flag it belongs to (see `hibernatedPane`'s load comment).+ hibernatedPane: v.hibernated || v.paused ? v.hibernatedPane : undefined,+ paused: v.paused}}}@@ -408,11 +433,15 @@ export function createAgentStatusSession(next.hibernated = undefinednext.hibernatedPane = undefined // goes with the flag, always}+ // Same self-heal, same reasoning: a live hook event is proof the CLI is running, whatever+ // brought it back (our own resume, or the user typing the launch line by hand) — a standing+ // `paused` would be wrong, and (unlike a cold restart) this IS evidence, not a guess.+ if (alive && prev.paused) next.paused = undefinedconst byId = { ...s.byId, [id]: next }// `state` itself is transient, so a plain transition writes nothing — but dropping a- // PERSISTED flag has to reach disk, or a relaunch would restore a hibernated node that- // has been demonstrably running since.- if (alive && prev.hibernated) save(byId)+ // PERSISTED flag has to reach disk, or a relaunch would restore a hibernated/paused node+ // that has been demonstrably running since.+ if (alive && (prev.hibernated || prev.paused)) save(byId)return { byId }}),@@ -487,6 +516,28 @@ export function createAgentStatusSession(return { byId }}),+ setPaused: (id, on) =>+ set((s) => {+ const prev = s.byId[id] ?? EMPTY+ if (!!prev.paused === on) return s+ // Cleared by dropping the key, not by storing `false` — same reasoning as `setHibernated`:+ // `save` skips entries with nothing durable, so a resumed node leaves no residue.+ const next: AgentNodeStatus = { ...prev, paused: on ? true : undefined }+ // Resuming restarts the idle clock — a session that sat paused for hours must not read as+ // having been idle that whole time on the very next Eco sweep.+ if (!on) {+ next.lastEventAt = Date.now()+ // Drop the recorded pane too, UNLESS `hibernated` still owns it (a resume normally clears+ // both flags together, in which case `setHibernated(id, false)` already dropped this —+ // but `setPaused` must be correct standing alone, for the deep-pause case where+ // `hibernated` was never set and this is the only owner).+ if (!prev.hibernated) next.hibernatedPane = undefined+ }+ const byId = { ...s.byId, [id]: next }+ save(byId)+ return { byId }+ }),+markBackgroundTask: (id) =>set((s) => {const prev = s.byId[id] ?? EMPTYdiff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 7859f558e..ca1250b05 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -1561,6 +1561,24 @@ body,color: var(--text);}+/* PAUSED: same quiet treatment as SLEEPING (a click resumes) — distinct label because a paused+ node will NOT auto-resume when reopened, which SLEEPING does. */+.term-node__status--paused {+ 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--paused:hover {+ color: var(--text);+}+.term-node__status--attention .term-node__status-dot {animation: nt-pulse 1.1s ease-in-out infinite;}diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex 1970d4fa5..999950730 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -485,6 +485,36 @@ export function agentHibernateFns(nodeId: string): AgentHibernateFns | undefinedreturn hibernateFns.get(nodeId)}+/** The exit half's outcome, plus `'paused'` for a manual pause that actually took. Registered+ * separately from `hibernateFns.exit`: Eco's exit refuses a node the user is currently watching+ * (`isNodeWatched`) — the whole point of the sweep — but a MANUAL pause is the user acting on the+ * node they are looking at right now, so it must not carry that refusal. The resume half is+ * intentionally NOT duplicated here: `agentHibernateFns(id).resume()` already works for a paused+ * node whichever depth paused it (a warm hibernated pane, or a freshly recycled shell after the+ * deeper "pause & end session") — it only asks whether the pane is a shell right now, not why. */+export type PauseOutcome = ExitPhaseOutcome | 'paused'++export interface AgentPauseFns {+ /** Ask the CLI to quit and mark the node PAUSED (see `agentStatus.paused`) so it does not+ * auto-resume on the next reveal or cold restart. `deep` additionally recycles the tmux session+ * for a fuller memory reclaim — the caller decides per node, at pause time. */+ pause: (deep: boolean) => Promise<PauseOutcome>+}++const pauseFns = new Map<string, AgentPauseFns>()++/** Register a node's pause closure; returns an unregister that is inert if superseded. */+export function registerAgentPause(nodeId: string, fns: AgentPauseFns): () => void {+ pauseFns.set(nodeId, fns)+ return () => {+ if (pauseFns.get(nodeId) === fns) pauseFns.delete(nodeId)+ }+}++export function agentPauseFns(nodeId: string): AgentPauseFns | undefined {+ return pauseFns.get(nodeId)+}+/** TEST ONLY (house pattern: webgl-budget's `__resetWebglBudgetForTests`): the maps above are* module-global, so a test that leaves a restart in flight would otherwise refuse the next* test's restart of the same node id. */@@ -492,6 +522,7 @@ export function __resetAgentRestartForTests(): void {inFlight.clear()restartFns.clear()hibernateFns.clear()+ pauseFns.clear()}// ── Bulk run: who gets restarted, and how the run is summed up ──────────────────────────diff --git a/src/shared/types.ts b/src/shared/types.tsindex 4ccd6b1b0..21ddf7eed 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1396,6 +1396,13 @@ export interface Settings {agentHibernationEnabled: boolean/** How long a session must be idle + offscreen before "Eco" hibernates it (minutes). */agentHibernationIdleMinutes: number+ /** When Eco hibernates a session, also mark it PAUSED (see `AgentNodeStatus.paused`) so it does+ * NOT auto-resume the next time the project or app reopens — only an explicit Resume brings it+ * back. Off by default: ordinary Eco already resumes automatically on the next reveal, and this+ * opts a hibernated session OUT of that for good, trading convenience for a colder, smaller+ * footprint across restarts. Independent of manual "Pause session", which always persists this+ * way regardless of this setting. */+ agentHibernationPersistAcrossRestart: boolean/** 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@@ -1567,6 +1574,7 @@ export const DEFAULT_SETTINGS: Settings = {// is deliberately long — shorter windows exit sessions the user is between turns on.agentHibernationEnabled: false,agentHibernationIdleMinutes: 30,+ agentHibernationPersistAcrossRestart: false,// 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,