Repository navigation
Wake hibernated agent panes on reveal instead of leaving an inert ghost - #7145
Conversation
Agent hibernation (experimentalAgentHibernation) kills an idle agent's PTY while its tab is hidden and pre-suppresses the exit. The pane-level onExit consumed that suppression, latched handledExitPtyId, and returned — so the reveal-time reconciles bailed and nothing ever woke the pane. The user got a frozen alt-screen frame with mouse-tracking still armed: every click became mouse-report bytes to a dead PTY (no focus, no selection, no input). Fix: - onExit's suppressed branch now recognizes hibernation (a sleeping record exists for the pane), disarms the frozen frame's input-eating modes (POST_REPLAY_MODE_RESET, alt-screen preserved) and arms a one-shot wake. - noteVisibilityResume consumes the wake on reveal and relaunches the recorded agent session via the existing cold-restore resume path (falls back to a fresh shell when no resume argv can be built). A pane rebound by another flow (intentional restart) invalidates the wake. - shutdownCompletedAgentPaneForHibernation now aborts when the sleeping record capture produced nothing: killing without a resume record strands the pane unrecoverably (observed with a codex session in prod). Regression test drives the suppressed exit + reveal through connectPanePty and fails without the fix. Validated end-to-end in a dev build: hibernated claude pane auto-resumed its session on reveal with the conversation restored and input working. Co-authored-by: Orca <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThis change adds hibernation wake handling for terminal pane PTY connections. When a suppressed PTY exit occurs for a hidden pane with a sleeping agent session, the code records the PTY id, resets replay mode state, and resumes through a cold-restore path after visibility returns. The hibernation shutdown flow now throws if no sleeping session record is available and rolls back partial state on failures. Tests were added for suppressed-exit resume behavior, wake invalidation, rollback, and the missing-record failure case. ChangesRelated issues: None referenced in provided summaries. Related PRs: None referenced in provided summaries. Suggested labels: terminal, hibernation, bug-fix Suggested reviewers: None specified. Sequence Diagram(s)sequenceDiagram
participant PTY as PTY process
participant ConnectPanePty as connectPanePty
participant Resume as startFreshColdRestoreAgentResume
PTY->>ConnectPanePty: onExit (suppressed while hidden)
ConnectPanePty->>ConnectPanePty: replayIntoTerminal(POST_REPLAY_MODE_RESET)
ConnectPanePty->>ConnectPanePty: record hibernatedWakePtyId
ConnectPanePty->>ConnectPanePty: noteVisibilityResume()
ConnectPanePty->>ConnectPanePty: validate transport and PTY id
ConnectPanePty->>Resume: wakeHibernatedAgentPane()
Poem 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/renderer/src/store/slices/terminals.ts (1)
1799-2009: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftWrite the sleeping session record before issuing the kill.
pty:exitcan fire whilesleepingAgentSessionsByPaneKeyis still empty, so the hibernation exit handler misses the wake record and leaves the pane frozen. Persist the record withsuppressedPtyExitIdsbefore the kill/stop call, and roll both back on failure.
🧹 Nitpick comments (1)
src/renderer/src/store/slices/terminals.ts (1)
1836-1841: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider a regression test for
agent_hibernation_capture_missing.The new abort guard is a meaningful safety net (prevents killing a PTY with no resumable capture), but no test in the provided diff exercises it. Worth a small unit test asserting
shutdownCompletedAgentPaneForHibernationthrowsagent_hibernation_capture_missingand leaves the PTY/suppression state untouched whencollectSleepingAgentSessionRecordsForWorktreeyields no record for the pane.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 4bde6435-ef64-43ee-a32d-6c882a4895fc
📒 Files selected for processing (3)
src/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/store/slices/terminals.ts
…apture gate Review findings from Brennan's PR process: - If a reveal raced the hibernation kill, noteVisibilityResume ran before onExit armed the wake, leaving the pane dead until a second hide/reveal. Extract the guarded consume into consumeHibernatedAgentWake and, when the pane is visible at arm time, schedule it via queueMicrotask (re-checks disposed/transport/ptyId at run time; one-shot preserved). - Add regression coverage: visible-at-arm-time auto-resume (fails without the microtask), hidden-hibernation modeled with isVisibleRef=false, and a store test that a done agent without a resumable provider session rejects with agent_hibernation_capture_missing and leaks nothing (no kill, no suppression, no record). Co-authored-by: Orca <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: e0382d8d-1420-47e6-b679-a3662fc4890b
📒 Files selected for processing (3)
src/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/store/slices/store-cascades.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/components/terminal-pane/pty-connection.ts
CodeRabbit stabilization findings: - pty:exit can reach the renderer before the kill promise resolves, so the pane's exit handler could consult sleepingAgentSessionsByPaneKey while it was still empty — missing the hibernation branch entirely (no mode disarm, no wake armed: the original frozen pane, resurrected by a race). Write the record alongside the exit suppression BEFORE issuing the kill, and roll both back together on any kill/stop failure. The post-kill record merge is now redundant and removed. - Regression test: kill failure rolls back both the record and suppression. - Make the wake tests assert the attach-derived transport ptyId explicitly so the same-pty guard's coverage is self-evident. Co-authored-by: Orca <[email protected]>
Two hunks of the hibernation-wake fix had no failing test when reverted: writing the sleeping record after the kill (the pty:exit TOCTOU) and removing the different-ptyId invalidation in consumeHibernatedAgentWake both left all 412 focused tests green. The new store test observes sleepingAgentSessionsByPaneKey and the suppression at the moment pty.kill is invoked, so a post-kill record write fails even though every end-state assertion still passes; the new connection test arms the wake, rebinds the transport to a fresh ptyId, and asserts reveal spawns nothing then and nothing later once the rebound PTY dies. Co-authored-by: Orca <[email protected]>
…s alive (#8630) * fix(terminal): self-heal panes whose renderer dies while the PTY stays alive A pane's xterm write pipeline can die while its shell keeps running: a synchronous throw escaping an unguarded write callback wedges WriteBuffer (issue #2836), and write() on a disposed terminal silently drops its completion callback (verified against vendored xterm 6.1.0-beta.287 — it does NOT throw, falsifying the output scheduler's disposed-race catch). Every recovery path we have (dead-session reconcile #6514/#7002, hibernation wake #7145, the allDead activation generation bump) gates on the PTY being dead, so these panes stayed fossils: last frame painted, every keystroke and byte of output silently dropped, delivery ack credits leaking, until the user reloaded the window (issue #8104 class). Detection is probe-certified, mirroring replay-guard.ts: - a scheduler write whose completion stalls gets an empty probe write; a probe that never parses certifies the pipeline dead (catches both the wedged WriteBuffer and the disposed-terminal case) and credits the queued deliveries so main's in-flight window no longer leaks - the replay guard's existing wedged release ("pane likely needs recovery") now actually hands the pane to recovery - user input rejected by an unbound transport (detached during a remount/move and never rebound) arms recovery after confirming the PTY is alive via pty:hasPty Recovery reuses the proven remount seam: bump the tab's generation so TerminalPane unmounts, detach() preserves the live PTY, and the remounted pane builds a fresh xterm that reattaches and replays the daemon snapshot — no shell restart, capped per tab to prevent remount storms. The new e2e spec pins both phenotypes end-to-end (wedge → recover, dispose-under-live-bindings → recover); both fail on main and pass with the fix, and the same arc was validated live in a pnpm dev instance. * fix(terminal): make pane recovery strictly best-effort in timer contexts Recovery fires from stall-watch timers, replay-guard releases, and onData — contexts where a throw becomes an unhandled error (CI verify caught this: pty-connection.test.ts mocks a partial store, other tests advance fake timers past the stall window, and the certification path hit a missing remountTerminalTabForRecovery). Guard the store action call and the ptyIdsByTabId reads so a partial surface yields a false return, never a throw, and pin it with a regression test. * fix(terminal): guard pane recovery against in-flight reattach and remote liveness blind spots Review findings on the self-heal (adversarial pass): 1. HIGH: typing during an in-flight connect/reattach (startup restore, app-SSH) hits sendInput while the transport is legitimately unbound; an input-undeliverable remount there destroys the unbound transport (no ptyId yet, so unmount cannot detach), and pty-transport's destroyed check then kills the PTY the resolving reattach returns — the live shell recovery exists to preserve. Gate the input detector on a transport-connect-in-flight flag (set around all three connect sites) and on disposed, so "not deliverable YET" never remounts. The fossil case (detached and never rebound) has no pending connect and still recovers. 2. pty:hasPty answers null for ids the local registry does not own, which made the liveness gate inert for remote panes: a disconnected remote runtime would remount-churn on every cooldown window while typing. Remote panes (connection-tagged or remote:-prefixed) now require an authoritative true; local panes keep the lenient null-proceeds gate. Flagged for follow-up, not changed here: pty-transport's destroyed check kills reattached sessions without discriminating isReattach — a pre-existing hazard that tab-close covers by killing per id anyway. * fix(terminal): keep certification throw-proof end to end Guard the two remaining throw paths in the certification chain — the entry-discard callback and the recovery handler — so nothing can escape a timer as an unhandled error, and a throwing discard cannot suppress the recovery notification it exists to precede. Pinned by two new tests. * fix(terminal): breadcrumb swallowed recovery failures A store-action throw in recovery returns false without consuming budget, so the detector retries each cooldown — an invisible loop unless it leaves a trace. Breadcrumb it (the recorder is self-guarded and cannot throw where recovery runs). Also invoke transport.isConnected optionally so partial test transports fail the gate quietly instead of logging a contained TypeError. * fix(terminal): end the zombie-pane replay loop at its root Root-caused the production "wedged release drip" (1,302 breadcrumbs in one day on one machine, 4-write bursts on a fixed timer phase, idle-required): once a pane's xterm pipeline dies while its connection lives, the delivery watchdog's heal (60s cooldown, fires only while idle because a dead xterm never ACKs its in-flight bytes) re-delivers restore markers, the hidden output restore replays 3-4 chunks into the dead parser, each write arms a replay guard destined for another wedged release — and nothing ever learns. The loop runs forever and re-forms after app restart. Three fixes so the loop learns: - replayIntoTerminal/Async short-circuit on a probe-certified dead pipeline: no more futile writes, so no more guard drips, and awaited restore chains resolve instead of hanging. - requestHiddenOutputRestoreIfNeeded is gated the same way, so the watchdog heal stops refetching snapshots for a pane recovery owns. - a window-cap recovery decline now schedules one retry for when the budget window reopens (deduped per tab, cancelled by any successful remount). Without it, the certified-dead latch plus the new write silence made a capped pane a permanent zombie: nothing would ever re-request recovery. Cooldown declines deliberately do not retry — remounts are tab-scoped, so the just-made remount already replaced every pane's xterm in the tab. Still open (tracked separately): the deterministic wedge surface that creates the dead pipeline on the release build in the first place — an unguarded, unreported parse-path throw or silent disposed-write; zero guard breadcrumbs fired all day, so the trigger predates the guards' coverage. * feat(terminal): name the silent zombie producer in breadcrumbs The last unproven link in the zombie-pane chain is HOW a pane's xterm dies on the release build. Field discriminators eliminated every reporting channel: zero terminal guard breadcrumbs and zero xterm-stack renderer_error/unhandled_rejection events across days of logs, while the drip re-formed after a clean app restart. Every content-triggered wedge surface would have reported; the only fully silent mechanism left is a restore write into an already-disposed xterm instance (write() drops its completion callback without a throw — verified against the vendored 6.1.0-beta.287). Instrument that exact moment: a version-pinned disposal probe (its test runs against the real vendored build so an upgrade that moves the private field fails loudly), a terminal_restore_write_target_disposed breadcrumb where startup scrollback restore would write into a disposed instance, and a terminal_restore_write_failed breadcrumb replacing the fully silent restore catch. The next zombie formation logs its own root cause.
…st (stablyai#7145) Co-authored-by: Orca <[email protected]>
…s alive (stablyai#8630) * fix(terminal): self-heal panes whose renderer dies while the PTY stays alive A pane's xterm write pipeline can die while its shell keeps running: a synchronous throw escaping an unguarded write callback wedges WriteBuffer (issue stablyai#2836), and write() on a disposed terminal silently drops its completion callback (verified against vendored xterm 6.1.0-beta.287 — it does NOT throw, falsifying the output scheduler's disposed-race catch). Every recovery path we have (dead-session reconcile stablyai#6514/stablyai#7002, hibernation wake stablyai#7145, the allDead activation generation bump) gates on the PTY being dead, so these panes stayed fossils: last frame painted, every keystroke and byte of output silently dropped, delivery ack credits leaking, until the user reloaded the window (issue stablyai#8104 class). Detection is probe-certified, mirroring replay-guard.ts: - a scheduler write whose completion stalls gets an empty probe write; a probe that never parses certifies the pipeline dead (catches both the wedged WriteBuffer and the disposed-terminal case) and credits the queued deliveries so main's in-flight window no longer leaks - the replay guard's existing wedged release ("pane likely needs recovery") now actually hands the pane to recovery - user input rejected by an unbound transport (detached during a remount/move and never rebound) arms recovery after confirming the PTY is alive via pty:hasPty Recovery reuses the proven remount seam: bump the tab's generation so TerminalPane unmounts, detach() preserves the live PTY, and the remounted pane builds a fresh xterm that reattaches and replays the daemon snapshot — no shell restart, capped per tab to prevent remount storms. The new e2e spec pins both phenotypes end-to-end (wedge → recover, dispose-under-live-bindings → recover); both fail on main and pass with the fix, and the same arc was validated live in a pnpm dev instance. * fix(terminal): make pane recovery strictly best-effort in timer contexts Recovery fires from stall-watch timers, replay-guard releases, and onData — contexts where a throw becomes an unhandled error (CI verify caught this: pty-connection.test.ts mocks a partial store, other tests advance fake timers past the stall window, and the certification path hit a missing remountTerminalTabForRecovery). Guard the store action call and the ptyIdsByTabId reads so a partial surface yields a false return, never a throw, and pin it with a regression test. * fix(terminal): guard pane recovery against in-flight reattach and remote liveness blind spots Review findings on the self-heal (adversarial pass): 1. HIGH: typing during an in-flight connect/reattach (startup restore, app-SSH) hits sendInput while the transport is legitimately unbound; an input-undeliverable remount there destroys the unbound transport (no ptyId yet, so unmount cannot detach), and pty-transport's destroyed check then kills the PTY the resolving reattach returns — the live shell recovery exists to preserve. Gate the input detector on a transport-connect-in-flight flag (set around all three connect sites) and on disposed, so "not deliverable YET" never remounts. The fossil case (detached and never rebound) has no pending connect and still recovers. 2. pty:hasPty answers null for ids the local registry does not own, which made the liveness gate inert for remote panes: a disconnected remote runtime would remount-churn on every cooldown window while typing. Remote panes (connection-tagged or remote:-prefixed) now require an authoritative true; local panes keep the lenient null-proceeds gate. Flagged for follow-up, not changed here: pty-transport's destroyed check kills reattached sessions without discriminating isReattach — a pre-existing hazard that tab-close covers by killing per id anyway. * fix(terminal): keep certification throw-proof end to end Guard the two remaining throw paths in the certification chain — the entry-discard callback and the recovery handler — so nothing can escape a timer as an unhandled error, and a throwing discard cannot suppress the recovery notification it exists to precede. Pinned by two new tests. * fix(terminal): breadcrumb swallowed recovery failures A store-action throw in recovery returns false without consuming budget, so the detector retries each cooldown — an invisible loop unless it leaves a trace. Breadcrumb it (the recorder is self-guarded and cannot throw where recovery runs). Also invoke transport.isConnected optionally so partial test transports fail the gate quietly instead of logging a contained TypeError. * fix(terminal): end the zombie-pane replay loop at its root Root-caused the production "wedged release drip" (1,302 breadcrumbs in one day on one machine, 4-write bursts on a fixed timer phase, idle-required): once a pane's xterm pipeline dies while its connection lives, the delivery watchdog's heal (60s cooldown, fires only while idle because a dead xterm never ACKs its in-flight bytes) re-delivers restore markers, the hidden output restore replays 3-4 chunks into the dead parser, each write arms a replay guard destined for another wedged release — and nothing ever learns. The loop runs forever and re-forms after app restart. Three fixes so the loop learns: - replayIntoTerminal/Async short-circuit on a probe-certified dead pipeline: no more futile writes, so no more guard drips, and awaited restore chains resolve instead of hanging. - requestHiddenOutputRestoreIfNeeded is gated the same way, so the watchdog heal stops refetching snapshots for a pane recovery owns. - a window-cap recovery decline now schedules one retry for when the budget window reopens (deduped per tab, cancelled by any successful remount). Without it, the certified-dead latch plus the new write silence made a capped pane a permanent zombie: nothing would ever re-request recovery. Cooldown declines deliberately do not retry — remounts are tab-scoped, so the just-made remount already replaced every pane's xterm in the tab. Still open (tracked separately): the deterministic wedge surface that creates the dead pipeline on the release build in the first place — an unguarded, unreported parse-path throw or silent disposed-write; zero guard breadcrumbs fired all day, so the trigger predates the guards' coverage. * feat(terminal): name the silent zombie producer in breadcrumbs The last unproven link in the zombie-pane chain is HOW a pane's xterm dies on the release build. Field discriminators eliminated every reporting channel: zero terminal guard breadcrumbs and zero xterm-stack renderer_error/unhandled_rejection events across days of logs, while the drip re-formed after a clean app restart. Every content-triggered wedge surface would have reported; the only fully silent mechanism left is a restore write into an already-disposed xterm instance (write() drops its completion callback without a throw — verified against the vendored 6.1.0-beta.287). Instrument that exact moment: a version-pinned disposal probe (its test runs against the real vendored build so an upgrade that moves the private field fails loudly), a terminal_restore_write_target_disposed breadcrumb where startup scrollback restore would write into a disposed instance, and a terminal_restore_write_failed breadcrumb replacing the fully silent restore catch. The next zombie formation logs its own root cause.
Symptom
With
experimentalAgentHibernationenabled, an idle agent session in a hidden tab gets its PTY killed by the 30-minute hibernation timer. When the user later reveals that tab, the pane shows the frozen last frame and is completely uninteractable — no clicks, no focus, no selection, no typing, no resume. Three separate occurrences were forensically confirmed in production (claude and codex sessions; daemon metaexitCode: -1+endedAtset, sleeping records withorigin: worktree-sleep). All three kills happened while the machine was awake — machine sleep was a red herring; the trigger is idle + hidden. The exact frozen-ghost state was also reproduced live in a dev build (mounted hidden pane + hibernation kill + reveal) before the fix.What changes
onExit's suppressed branch recognizes hibernation (a sleeping record exists for the pane), disarms the frozen frame's input-eating terminal modes (POST_REPLAY_MODE_RESET; alt-screen content preserved), and arms a one-shot wake.noteVisibilityResumeconsumes it on the pane's own hidden→visible transition and relaunches the recorded session through the existing cold-restore resume path (claude --resume <session>etc., falling back to a fresh shell if no resume argv can be built). A pane rebound by another flow (intentional codex restart uses the same suppression mechanism) invalidates the wake instead.shutdownCompletedAgentPaneForHibernationaborts withagent_hibernation_capture_missingwhen the sleeping-record capture produced nothing for the pane, before any suppression or kill (one prod codex pane was killed record-less and was unrecoverable). The coordinator handles the throw (warn + retry next tick); planner and capture share the same eligibility predicate, so a miss is only a transient race, never a permanent warn-loop.What does not change
Hibernation's trigger policy (30-min idle timer, hidden-only eligibility) is untouched. There is intentionally no new UI in this PR: auto-resume on reveal is silent. Two design follow-ups surfaced during review for a separate decision: a visible "sleeping / resuming" placeholder state instead of a live-looking frame, and resume-then-deliver for programmatic input sent to a still-hidden sleeping pane.
Validation (Brennan's PR process)
connectPanePty-level test (suppressed exit + reveal) that fails without the fix; a second test pins the reveal-races-kill path (fails without the deferred wake); a store-level test pins the capture gate (no kill, no suppression, no record write on capture miss). Focused suites:pty-connection.test.ts+store-cascades.test.ts+agent-hibernation-coordinator.test.ts= 411 passed.pnpm run typecheckclean. (pnpm run lintfails only on a pre-existing localization-catalog key inWorktreeList.tsx, unrelated to this branch.)--- session restored ---,claude --resume <id>process confirmed, conversation restored, typing works). Re-validated after the review-loop changes landed.Residual risks / accepted gaps
terminal.stopExactordering was reviewed but not E2E-exercised — worth a follow-up only if remote-runtime ghosts are ever reported.