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
refactor(renderer): hibernate registry beside the restart one
enese0e11625eeae
diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.tsindex 88abe63c4..519a74ba3 100644--- a/src/renderer/terminal/agent-restart.test.ts+++ b/src/renderer/terminal/agent-restart.test.ts@@ -3,6 +3,7 @@ import { resumeCommand } from '../../shared/agents/config'import { withPermissionMode } from '../../shared/agents/approval-mode'import {__resetAgentRestartForTests,+ agentHibernateFns,agentRestartFn,exitSequence,guardConcurrentRestart,@@ -11,12 +12,15 @@ import {performRestartResume,performResumePhase,planBulkRestart,+ registerAgentHibernate,registerAgentRestart,restartEligibility,settleRestart,summarizeBulkRestart,summarizeOutcomes,+ type AgentHibernateFns,type BulkRestartCandidate,+ type ExitPhaseOutcome,type RestartOutcome} from './agent-restart'@@ -539,6 +543,29 @@ describe('performExitPhase', () => {expect(written).toEqual([])})+ it('needs the changed reading TWICE before it calls an unlisted shell an exit', async () => {+ // The allowlist cannot know `nu` / `xonsh` / a hand-set defaultShell, so "the foreground+ // command is no longer what it was" is the other exit signal — and it is required on two+ // CONSECUTIVE polls, because a single changed reading can be a momentary foreground CHILD of a+ // still-running CLI. Typing the resume line into a live CLI would send it as a message.+ const { io } = fakeIo()+ const panes = ['claude', 'git', 'claude', 'nu', 'nu']+ let i = 0+ const p = performExitPhase({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ // The pre-flight consumes the first reading, so `before` is 'claude'.+ paneCommand: async () => panes[Math.min(i++, panes.length - 1)] ?? null,+ timeoutMs: 5000,+ pollMs: 100+ })+ await vi.advanceTimersByTimeAsync(150) // poll 1 → 'git': changed, but not yet twice+ await vi.advanceTimersByTimeAsync(100) // poll 2 → 'claude': the CLI is still there+ await vi.advanceTimersByTimeAsync(250) // polls 3+4 → 'nu' twice in a row+ expect(await p).toBe('exited')+ })+it('stops polling a pane that dies under the wait', async () => {const { io } = fakeIo()let live = true@@ -630,6 +657,24 @@ describe('performResumePhase', () => {expect(await p).toBe('resumed')})+ it('rejects when the transport throws after the delivery announced itself', async () => {+ // The delivery can announce its end from INSIDE deliverCommand's synchronous body and THEN+ // throw (a transport that rejects the very first write ends the delivery, then reports). A+ // promise resolved on that announcement could no longer be rejected, and the caller would+ // record a resume — a woken node, with a dead pane and nothing typed into it.+ const io = {+ write() {+ throw new Error('socket CONNECTING')+ },+ onData() {+ return () => {}+ }+ }+ await expect(+ performResumePhase({ agentId: 'claude', sessionId: 'sid-1', io })+ ).rejects.toThrow('socket CONNECTING')+ })+it('respects isLive: a session that died under the delivery is not a resume', async () => {const { io } = fakeIo()let live = true@@ -934,6 +979,53 @@ describe('agent restart registry', () => {})})+describe('agent hibernate registry', () => {+ beforeEach(() => __resetAgentRestartForTests())++ const pair = (tag: 'a' | 'b'): AgentHibernateFns => ({+ exit: async () => (tag === 'a' ? 'exited' : 'exit-timeout'),+ resume: async () => 'resumed'+ })++ it('registers, resolves and unregisters; re-register supersedes', () => {+ const a = pair('a')+ const un = registerAgentHibernate('n1', a)+ expect(agentHibernateFns('n1')).toBe(a)+ const b = pair('b')+ registerAgentHibernate('n1', b)+ un() // stale unregister from the superseded registration must be inert+ expect(agentHibernateFns('n1')).toBe(b)+ })++ it('drops a live registration on unregister (node unmount)', () => {+ registerAgentHibernate('n2', pair('a'))()+ expect(agentHibernateFns('n2')).toBeUndefined()+ })++ it('is cleared by the test reset, like the restart registry', () => {+ registerAgentHibernate('n3', pair('a'))+ __resetAgentRestartForTests()+ expect(agentHibernateFns('n3')).toBeUndefined()+ })++ it('shares one in-flight guard with restarts: a sweep cannot quit a pane mid-restart', async () => {+ // Both halves go through `guardConcurrentRestart` with the NODE id, so the hibernation sweep,+ // the wake and a user restart serialize against each other — two `/exit` lines into one pane+ // is the exact accident the guard exists for.+ let release: (o: RestartOutcome) => void = () => {}+ const restart = guardConcurrentRestart(+ 'n-shared',+ () => new Promise<RestartOutcome>((r) => (release = r))+ )+ const hibernateExit = guardConcurrentRestart('n-shared', async (): Promise<ExitPhaseOutcome> => 'exited')+ const running = restart()+ expect(await hibernateExit()).toBe('not-eligible')+ release('restarted')+ expect(await running).toBe('restarted')+ expect(await hibernateExit()).toBe('exited') // pane free again+ })+})+describe('summarizeOutcomes', () => {it('counts restarted / timeout / pre-skips into the toast line', () => {expect(diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex c402f42f3..3ac3881f7 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -197,6 +197,12 @@ export async function performExitPhase(d: {/*** PHASE 2 — echo-deliver the resume command into a pane the CLI has already let go of.*+ * Deliberately NOT gated on `exitSequence`: this half only types a launch line into a pane that is+ * already free, so a CLI we have no way to ASK to quit is still perfectly resumable here (the exit+ * half owns that question). What gates this half is the bare `resumeCommand` below — the session id+ * has to be one this app would put on a command line. Hibernation's wake path relies on the split:+ * it drives this half alone, hours after the exit.+ ** Resolves only once the resume line has actually LEFT the pane (deliverCommand's echo-verify* retries run for up to DELIVERY_ATTEMPTS × VERIFY_TIMEOUT_MS after the first write). The* un-submitted line is the pane's most fragile moment — anything typed into it during that window@@ -287,9 +293,10 @@ export async function performResumePhase(d: {* function's four outcomes are unchanged: `'exited'` continues, anything else from the exit half* is passed through as-is, and a `'resumed'` is what the caller reads as `'restarted'`.*- * The eligibility gate is repeated here so a refusal costs no phase call at all; both halves- * re-check it themselves, since either can be driven directly (hibernation quits a pane in one- * phase and resumes it much later in the other).+ * No gate of its own: `performExitPhase` refuses (writing nothing) on exactly the same two facts —+ * no exit sequence, or a session id `resumeCommand` would not put on a command line — and it runs+ * first, so a copy here could only drift. Both halves re-check for themselves because either can be+ * driven directly: hibernation quits a pane in one phase and resumes it much later in the other.*/export async function performRestartResume(d: {agentId: string@@ -312,9 +319,6 @@ export async function performRestartResume(d: {*/isLive?: () => boolean}): Promise<RestartOutcome> {- // The BARE command is the gate even when the caller overrides it: `resumeCommand` is what- // validates the session id before it reaches a command line.- if (!exitSequence(d.agentId) || !resumeCommand(d.agentId, d.sessionId)) return 'not-eligible'const exited = await performExitPhase({agentId: d.agentId,sessionId: d.sessionId,@@ -347,7 +351,13 @@ const inFlight = new Set<string>()* reach the same node, and two runs against one pane would write two `/exit` lines (the second* typed INTO the CLI the first is resuming) and two resume commands.*- * The node is held for the WHOLE run, delivery included (see performRestartResume's header): a+ * ONE set for every kind of run: a hibernation exit, a wake resume and a user restart all pass+ * through here, so a sweep cannot quit the pane a menu restart is already resuming, and vice versa.+ * Generic in the outcome so the two halves can be guarded on their own (`ExitPhaseOutcome` /+ * `ResumePhaseOutcome`), which is what hibernation drives — the refusal is `'not-eligible'`, a+ * member of every one of those unions.+ *+ * The node is held for the WHOLE run, delivery included (see performResumePhase's header): a* second `/exit` arriving while the resume line sits un-submitted in the pane would be spliced* into it and submit `claude --resume <sid>/exit` — the exact mangled line command-delivery.ts* exists to prevent, and likeliest precisely when echo verification is being slow.@@ -357,10 +367,10 @@ const inFlight = new Set<string>()* does not count — so a doubled request is neither counted twice as restarted nor reported as a* failure the user could act on. (The alternative, a fifth outcome, would break that frozen line.)*/-export function guardConcurrentRestart(+export function guardConcurrentRestart<T extends string>(nodeId: string,- fn: () => Promise<RestartOutcome>-): () => Promise<RestartOutcome> {+ fn: () => Promise<T>+): () => Promise<T | 'not-eligible'> {return async () => {if (inFlight.has(nodeId)) return 'not-eligible'inFlight.add(nodeId)@@ -389,12 +399,44 @@ export function agentRestartFn(nodeId: string): (() => Promise<RestartOutcome>)return restartFns.get(nodeId)}-/** TEST ONLY (house pattern: webgl-budget's `__resetWebglBudgetForTests`): both maps above are+/**+ * A node's two HIBERNATION halves, registered together because they are useless apart: the sweep+ * quits the CLI now, and the wake resumes the same conversation minutes or hours later.+ *+ * Separate from `restartFns` on purpose — a restart is one indivisible action, hibernation is two+ * that are deliberately far apart in time — but both are built by the SAME node from the same+ * `io` / `paneCommand` / `isLive`, and both go through `guardConcurrentRestart`, so the sweep, the+ * wake and a user restart can never write into one pane at once.+ */+export interface AgentHibernateFns {+ /** Ask the CLI to quit and wait for the pane. `'exited'` is the only outcome that may be+ * recorded as hibernated — anything else leaves the node exactly as it was. */+ exit: () => Promise<ExitPhaseOutcome>+ /** Re-launch the conversation with the provider's own `--resume`. */+ resume: () => Promise<ResumePhaseOutcome>+}++const hibernateFns = new Map<string, AgentHibernateFns>()++/** Register a node's hibernate/wake pair; returns an unregister that is inert if superseded. */+export function registerAgentHibernate(nodeId: string, fns: AgentHibernateFns): () => void {+ hibernateFns.set(nodeId, fns)+ return () => {+ if (hibernateFns.get(nodeId) === fns) hibernateFns.delete(nodeId)+ }+}++export function agentHibernateFns(nodeId: string): AgentHibernateFns | undefined {+ return hibernateFns.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. */export function __resetAgentRestartForTests(): void {inFlight.clear()restartFns.clear()+ hibernateFns.clear()}// ── Bulk run: who gets restarted, and how the run is summed up ──────────────────────────