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
fix(renderer): hibernation review round 1 — the second dismiss path, stale verdicts, self-heal
enesed568600ae25
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 11e9c3fc2..bbda37d44 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -28,7 +28,8 @@ import {disposeTerminalOnUnmount,disposeParkedTerminal,disposeAllParkedTerminals,- isNodeOffscreen+ isNodeOffscreen,+ wakeHibernatedNode} from '../nodes/TerminalNode'import { solveFitPadding } from './fit-view'import {@@ -169,6 +170,7 @@ import {} from '../terminal/agent-restart'import { planHibernation, HIBERNATE_SWEEP_MS } from '../terminal/hibernation-policy'import { buildHibernationCandidates } from '../lib/hibernationCandidates'+import { applyLoopDismiss } from '../lib/loopCard'import { prepareQuickOpenFiles, type QuickOpenIndexedFile } from '../lib/quickOpenSearch'import { opensInEditor } from '../lib/openTarget'import { newEntryPath, parentDir } from '../lib/explorerCreate'@@ -5016,15 +5018,15 @@ export function Canvas() {...(isLoop? ([{- // Same as the card's own ×: drops the CARD, never the cron/schedule job itself.+ // Same as the card's own ×: drops the CARD, never the cron/schedule job itself —+ // and literally the same code path (`applyLoopDismiss`), because these two surfaces+ // are one user action and had already drifted apart once: this one cleared the+ // durable `loop` entry, which is the only thing keeping Eco mode from quitting the+ // CLI a live cron was going to fire in.label: 'Dismiss card',icon: <IconTrash />,danger: true,- onClick: () => {- const pid = id.slice('loop-'.length)- useAgentStatus.getState().setLoop(pid, false)- useAgentNodes.getState().clearLoop(pid)- }+ onClick: () => applyLoopDismiss(id.slice('loop-'.length))}] as MenuItem[]): [])@@ -5439,6 +5441,12 @@ export function Canvas() {// whole board on every Canvas render.const setKanbanModalNode = useCallback((id: string | null) => {kanbanModalNodeRef.current = 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)}, [])const onPaletteQuery = useCallback((q: string) => {@@ -7098,7 +7106,14 @@ export function Canvas() {})),// 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,+ //+ // …with ONE override the observers structurally cannot know about: a kanban card modal+ // co-attaches the same tmux session over a canvas nobody can see, so its node is+ // off-screen by every measurement and yet is the one session the user is looking at.+ // Quitting the CLI under an open modal is the same intrusion as quitting it under the+ // node itself.+ isOffscreen: (nodeId) =>+ nodeId !== kanbanModalNodeRef.current && isNodeOffscreen(nodeId),// 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.@@ -7117,6 +7132,15 @@ export function Canvas() {try {if ((await fns.exit()) === 'exited') {useAgentStatus.getState().setHibernated(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 (!isNodeOffscreen(nodeId) || nodeId === kanbanModalNodeRef.current) {+ 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/lib/loopCard.test.ts b/src/renderer/lib/loopCard.test.tsnew file mode 100644index 000000000..a66764af6--- /dev/null+++ b/src/renderer/lib/loopCard.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it, beforeEach } from 'vitest'+import { applyLoopDismiss, loopDismissAction } from './loopCard'+import { useAgentStatus } from '../state/agentStatus'++describe('loopDismissAction', () => {+ it('keeps the fact for jobs that outlive the session, clears the in-session loop', () => {+ expect(loopDismissAction('cron')).toBe('mark-dismissed')+ expect(loopDismissAction('schedule')).toBe('mark-dismissed')+ expect(loopDismissAction('loop')).toBe('clear')+ expect(loopDismissAction(undefined)).toBe('clear')+ })+})++describe('applyLoopDismiss — one path for BOTH dismiss surfaces', () => {+ beforeEach(() => {+ useAgentStatus.setState({ byId: {} })+ })++ it('marks a cron card dismissed and KEEPS the entry (the job is still out there)', () => {+ useAgentStatus.getState().setLoop('n1', true, 'cron', { schedule: '0 9 * * *' })+ applyLoopDismiss('n1')+ // The card is gone from every render site; the guard Eco mode reads is not.+ expect(useAgentStatus.getState().byId['n1'].loop).toMatchObject({+ kind: 'cron',+ dismissed: true+ })+ })++ it('marks a schedule card the same way', () => {+ useAgentStatus.getState().setLoop('n2', true, 'schedule')+ applyLoopDismiss('n2')+ expect(useAgentStatus.getState().byId['n2'].loop?.dismissed).toBe(true)+ })++ it('clears an in-session /loop outright — it dies with its session anyway', () => {+ useAgentStatus.getState().setLoop('n3', true, 'loop')+ applyLoopDismiss('n3')+ expect(useAgentStatus.getState().byId['n3'].loop).toBeUndefined()+ })++ it('is a no-op for a node with no card', () => {+ applyLoopDismiss('n4')+ expect(useAgentStatus.getState().byId['n4']).toBeUndefined()+ })+})diff --git a/src/renderer/lib/loopCard.ts b/src/renderer/lib/loopCard.tsnew file mode 100644index 000000000..d0e156985--- /dev/null+++ b/src/renderer/lib/loopCard.ts@@ -0,0 +1,40 @@+/**+ * Dismissing a /loop · /schedule · /cron CARD — the ONE place that knows what a dismiss owes.+ *+ * There are two dismiss surfaces for the same user action (the card's own × and the card's+ * right-click menu), and they drifted: one kept the durable recurring fact and the other destroyed+ * it. What is at stake is not the card. `agentStatus.loop` is the only record that this node has a+ * wakeup pending, and it is what stops Eco mode from asking the CLI to `/exit` — a `cron` whose+ * entry has been cleared looks EXACTLY like an idle session (done, offscreen, long silent), so the+ * next sweep quits the process the job was going to fire in. The card's own tooltip has always+ * promised the opposite: "does not remove the job".+ *+ * So: a `cron`/`schedule` dismiss MARKS the entry (`loop.dismissed` — every render site filters on+ * it, nothing else reads it), while an in-session `/loop` still clears outright, because that one+ * dies with its session and there is no fact left to keep. A real end (CronDelete) is a real clear,+ * and goes through `setLoop(id, false)` as it always has.+ */+import { useAgentStatus } from '../state/agentStatus'+import { useAgentNodes } from '../state/agentNodes'++/** What dismissing a card of this kind must do to the durable entry. Pure — the whole decision. */+export function loopDismissAction(+ kind: string | undefined+): 'mark-dismissed' | 'clear' {+ // Unknown kinds clear, matching the historical behavior of every non-cron card.+ return kind === 'cron' || kind === 'schedule' ? 'mark-dismissed' : 'clear'+}++/**+ * Apply a dismiss to the parent terminal's card. The KIND is read from the store, not passed in:+ * that entry is where the card's own data came from, and a second source is how the two surfaces+ * disagreed in the first place.+ */+export function applyLoopDismiss(parentNodeId: string): void {+ const status = useAgentStatus.getState()+ const kind = status.byId[parentNodeId]?.loop?.kind+ if (loopDismissAction(kind) === 'mark-dismissed') status.dismissLoopCard(parentNodeId)+ else status.setLoop(parentNodeId, false)+ // The card's dragged position/size go either way — the card is gone from the screen.+ useAgentNodes.getState().clearLoop(parentNodeId)+}diff --git a/src/renderer/nodes/LoopNode.tsx b/src/renderer/nodes/LoopNode.tsxindex c252de015..81101b77d 100644--- a/src/renderer/nodes/LoopNode.tsx+++ b/src/renderer/nodes/LoopNode.tsx@@ -2,7 +2,7 @@ import { useEffect, useRef } from 'react'import { Handle, NodeResizer, Position, type NodeProps } from '@xyflow/react'import type { CanvasNode } from '../state/workspace'import { useAgentNodes } from '../state/agentNodes'-import { useAgentStatus } from '../state/agentStatus'+import { applyLoopDismiss } from '../lib/loopCard'import { useSession } from '../session/session'/**@@ -37,19 +37,13 @@ export function LoopNode({ id, data, selected }: NodeProps<CanvasNode>) {// 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.+ // …which is why the whole decision lives in `lib/loopCard.ts`, shared with the card's+ // right-click "Dismiss card": a cron/schedule dismiss MARKS the entry rather than clearing it,+ // because that entry is the only record that a wakeup is pending — and the guard that keeps Eco+ // mode from `/exit`ing the CLI it lives in.const dismiss = (e: React.MouseEvent) => {e.stopPropagation()- const parentId = id.replace(/^loop-/, '')- const cs = useAgentStatus.getState()- if (kind === 'cron' || kind === 'schedule') cs.dismissLoopCard(parentId)- else cs.setLoop(parentId, false)- useAgentNodes.getState().clearLoop(parentId)+ applyLoopDismiss(id.replace(/^loop-/, ''))}// The cards are `selectable: false` in React Flow (a rubber band must not sweep a fan-outdiff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 6f69101d7..0ef5a3e7d 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -85,7 +85,7 @@ import {validCellSize,type Vec2} from '../lib/glyphGridNode'-import { deliverCommand, type DeliveryIo } from '../terminal/command-delivery'+import { deliverCommand, KILL_LINE, type DeliveryIo } from '../terminal/command-delivery'import {agentHibernateFns,guardConcurrentRestart,@@ -668,6 +668,23 @@ export function isNodeOffscreen(nodeId: string): boolean {return offscreenNodes.has(nodeId)}+/**+ * Each mounted node publishes its wake trigger here, so anything that means "the user is looking+ * at this session now" can ask for the conversation back without owning the machinery: the sweep+ * itself (a node hibernated in the same tick the user panned back to it), and the kanban card+ * modal (a second, equally real way of opening a session — the canvas visibility observer says+ * nothing about it).+ *+ * Same park-surviving reason as `restartSubs`: no entry = nobody is mounted = nothing to wake.+ */+const wakeSubs = new Map<string, () => void>()++/** Ask a node to resume its hibernated CLI. No-op if it is not mounted, or not hibernated (the+ * node re-reads the flag itself — this is a nudge, never an assertion). */+export function wakeHibernatedNode(nodeId: string): void {+ wakeSubs.get(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@@ -1091,11 +1108,16 @@ export function TerminalNode({// 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(() => {+ // Published for the two askers that are not this node: the sweep (a node hibernated in the+ // very tick the user panned back to it) and the kanban card modal.+ const trigger = (): void => wakeRef.current()+ wakeSubs.set(id, trigger)const t = setTimeout(() => {if (!isNodeOffscreen(id)) wakeRef.current()}, WAKE_MOUNT_DELAY_MS)return () => {clearTimeout(t)+ if (wakeSubs.get(id) === trigger) wakeSubs.delete(id)if (wakeTimerRef.current) {clearTimeout(wakeTimerRef.current)wakeTimerRef.current = null@@ -2585,6 +2607,15 @@ export function TerminalNode({// (parked → remounted) terminal never reaches the spawn continuation.const unregisterHibernate = registerAgentHibernate(id, {exit: guardConcurrentRestart(id, async (): Promise<ExitPhaseOutcome> => {+ // "Is this node STILL out of view?" — re-asked at FIRE time, never trusted from the plan,+ // the same discipline as `mayDisposeOffscreen`. A sweep can spend ~12 s working through+ // its batch, and the node whose turn comes last may be one the user panned back to and is+ // now typing in: KILL_LINE + `/exit` would land in a pane they are watching, taking their+ // half-written prompt with it. Worse, the visible EDGE has already passed by then, so no+ // wake trigger is left and the node would sit SLEEPING on screen until clicked.+ // (`isNodeOffscreen` and this node's own `wasVisibleRef` are the same observer's verdict;+ // the map is used here so the sweep and the node cannot disagree.)+ if (!isNodeOffscreen(id)) return 'not-eligible'// 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.@@ -2609,14 +2640,10 @@ export function TerminalNode({const st = useAgentStatus.getState().byId[id]const agentSessionId = st?.sessionIdif (!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'+ // Command FIRST, pane check LAST. Both of these awaits can take a moment (the claude+ // version probe behind `ensureActivePermissionMode` most of all), and whatever is asked+ // first is stale by the time the delivery runs — so the fact that must be freshest is the+ // one asked last: what owns the pane we are about to type into.// 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).@@ -2624,6 +2651,21 @@ export function TerminalNode({const command = base? withPermissionMode(base, agentId, await ensureActivePermissionMode(agentId)): undefined+ // 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 — and a launch line typed into a live+ // program is sent to that program, as a message 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'+ // Clear the line before the launch line goes in. The shell above is the one WE exited to,+ // hours ago — nothing stops a passer-by (or a stray paste, or the user's own aborted+ // command) from having left a half-typed line at its prompt, and `deliverCommand`'s first+ // write is not preceded by a Ctrl-U. The exit half clears the line for exactly this+ // reason; the wake half owes the same. Deliberately HERE and not inside+ // `performResumePhase`: that function's output is pinned byte-for-byte by Task 8's tests,+ // and the restart path (which just cleared the line itself) must not clear it twice.+ restartIo.write(KILL_LINE)return performResumePhase({agentId,sessionId: agentSessionId,diff --git a/src/renderer/state/agentStatus.persist.test.ts b/src/renderer/state/agentStatus.persist.test.tsindex 5f4fe38d8..9e1f4a28a 100644--- a/src/renderer/state/agentStatus.persist.test.ts+++ b/src/renderer/state/agentStatus.persist.test.ts@@ -58,6 +58,44 @@ describe('loop persistence (cron/schedule survive an app restart)', () => {expect(JSON.parse(store.getItem('nodeterm.agentStatus') ?? '{}').n1?.hibernated).toBeUndefined()})+ it('clears `hibernated` on a LIVE state — a hook event is proof the CLI is running', async () => {+ // Left standing, the flag renders RUNNING and SLEEPING at once AND exempts the session from+ // Eco for good (the sweep skips hibernated nodes). The three ways it goes stale are all real:+ // the user relaunched the agent by hand, a wake landed, or a resume we could not confirm+ // actually worked.+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ for (const state of ['working', 'blocked', 'waiting'] as const) {+ useAgentStatus.getState().setHibernated('n10', true)+ useAgentStatus.getState().setState('n10', state, 'claude')+ expect(useAgentStatus.getState().byId['n10'].hibernated, state).toBeUndefined()+ // …and it reaches disk, or a relaunch would restore a flag we have disproved.+ expect(JSON.parse(store.getItem('nodeterm.agentStatus')!).n10?.hibernated, state).toBeUndefined()+ useAgentStatus.getState().setState('n10', undefined)+ }+ })++ it('keeps `hibernated` through a `done` event — a late Stop must not undo the exit', async () => {+ vi.stubGlobal('localStorage', memStorage())+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setHibernated('n11', true)+ useAgentStatus.getState().setState('n11', 'done', 'claude')+ expect(useAgentStatus.getState().byId['n11'].hibernated).toBe(true)+ })++ it('waking restarts the idle clock, so a quiet resumed session is not re-hibernated', async () => {+ vi.stubGlobal('localStorage', memStorage())+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.setState({+ byId: { n12: { unread: false, state: 'done', lastEventAt: Date.now() - 6 * 3600_000, hibernated: true } }+ })+ useAgentStatus.getState().setHibernated('n12', false)+ const st = useAgentStatus.getState().byId['n12']+ expect(st.hibernated).toBeUndefined()+ expect(Date.now() - st.lastEventAt!).toBeLessThan(5000) // hours-old clock replaced+ })+it('restores `hibernated` on load (the CLI stays exited across an app restart)', async () => {vi.stubGlobal('localStorage',diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex aa932e8a1..a111171d4 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -120,7 +120,9 @@ 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. */+ /** Mark the node's agent CLI as exited-for-RAM (true) or live again (false). Persisted.+ * Waking also restarts the idle clock (`lastEventAt`), so a quiet resumed session is not+ * re-hibernated on the next sweep. */setHibernated(id: string, on: boolean): voidmarkUnread(id: string): void/**@@ -308,7 +310,23 @@ export function createAgentStatusSession(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- return { byId: { ...s.byId, [id]: next } }+ // A LIVE state is proof the CLI is running, so the hibernated flag is simply wrong and is+ // dropped here — the one self-heal this flag has. It is set by a controller that watched+ // the CLI let go of the pane, but the world moves on without us: the user relaunches the+ // agent by hand, a wake lands and its `--resume` starts reporting, or a resume we could+ // not confirm turns out to have worked. Left standing, the flag is not cosmetic: it+ // renders RUNNING and SLEEPING side by side, and (because a hibernated node is skipped by+ // the sweep) exempts that session from Eco for good.+ // `done` deliberately does NOT clear it — a hibernated node's last known state IS done,+ // and a late Stop POST arriving after the exit would undo the hibernation we just did.+ const alive = state === 'working' || state === 'blocked' || state === 'waiting'+ if (alive && prev.hibernated) next.hibernated = undefined+ const 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)+ return { byId }}),sweepStaleWorking: (staleMs = STALE_WORKING_MS) =>@@ -350,6 +368,13 @@ export function createAgentStatusSession(// 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 }+ // Waking RESTARTS the idle clock. Without this, a node whose conversation was resumed but+ // whose CLI then sits quiet (an agent that fires no hook until you talk to it) still+ // carries the `lastEventAt` from before it was hibernated — hours old — so the very next+ // sweep, 60 s later, would quit the session the user just came back to. Hibernating does+ // not touch the clock: nothing happened in that session, and the flag itself is what keeps+ // the sweep off it.+ if (!on) next.lastEventAt = Date.now()const byId = { ...s.byId, [id]: next }save(byId)return { byId }