Repository navigation
fix(sleep): restore agent auto-hibernation for non-Pi agents - #16430
Conversation
…tting the idle clock Auto-hibernation could never fire for claude, codex, gemini, opencode, grok, or any other resumable TUI agent — only pi/omp/prime-agent. #10238 broadened the `origin: 'live'` resume anchor so every resumable agent keeps its `--resume` handle when a turn ends. The planner rejects any pane that already has a sleeping record, and its exemption was still Pi-only. Since the planner's eligibility conditions are the same conditions that write the anchor, that rejection covered every otherwise-eligible non-Pi pane. - Split the conflated predicate. `isLiveResumeAnchorForCompletedAgent` answers "is this record just this pane's own live anchor?" with no vendor gate; the Pi-gated wrapper keeps today's exact semantics for the manual-sleep and quit capture call sites; `isAutomaticHibernationAllowed` carries the `automaticResumeBlockedBy` fence on its own. - Fence automatic hibernation. A fenced worker must not be auto-relaunched, and the capture does not copy the flag — so hibernating one would erase it. Checked in the planner and again inside the shutdown action against freshest state, re-evaluated after the synchronous capture callback that could itself fence it. - Anchor the idle clock on `stateStartedAt`, not `updatedAt`. Same-state repaints (OSC 9999, reconnect replays) advance `updatedAt`, restarting the 30-minute countdown and invalidating the two-tick confirmation. - Floor that anchor on PTY-binding age and a boundary-resolution stamp, so a wake or app restart still gets a full idle window instead of sleeping the whole backlog on the ancient timing main replays. The boundary stamp is written synchronously where the flag clears; sampling it per tick would miss a boundary written and cleared between two samples. - Signature drops `updatedAt` and gains agent kind plus full resume identity, which is the change detection `updatedAt` was providing by accident. Splits the planner into planner / pane-eligibility / snapshot to stay under the file length limit.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review. 📝 WalkthroughWalkthroughThe change modularizes agent hibernation pane eligibility and planner snapshot types. It tracks PTY binding age and completion-boundary timestamps to enforce lifecycle timing. It adds live-resume anchor guards and automatic-resume fences during shutdown. Planner signatures now use stable agent state and resume identity fields instead of repaint timestamps. The coordinator now revalidates and shuts down candidates sequentially. Tests cover eligibility, timing floors, live anchors, fences, PTY rebinding, transient layout gaps, boundary resolution, runtime scoping, and teardown ordering. Merge Risk: ⚪ Minimal · up to The change is merge-ready after normal checks and review; no actionable merge-blocking risk remains. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives a detailed problem statement, root cause, implementation summary, expected behavior, and test results. However, it omits required template content, including a linked issue, visual proof or an explicit N/A explanation, the testing checklist and platform coverage, AI disclosure, review sections, notes, and the final checklist. Resolution Add the missing required sections. Include a valid issue reference under Linked Issue, attach before-and-after visual proof or write N/A with a reason, complete the Testing checklist with platforms tested, complete AI Disclosure as applicable, address Review, Agent skill upstream boundary, Notes, and Checklist items. ✨ Finishing Touches 💡 1📝 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 |
`runAgentHibernationTick` launched every confirmed shutdown unawaited, so a backlog fanned all of them out at once. Each shutdown re-runs a full runtime-liveness sweep (one `terminal.list` per runtime-owned worktree, 10s timeout) and then a `terminal.stopExact` (15s timeout) — so ~100 overdue panes meant ~100 concurrent sweeps plus ~100 concurrent stops plus interleaved persistence writes. On an SSH runtime that is hundreds of near-simultaneous RPCs at the relay. The fanout predates this branch, but auto-hibernation could not fire for non-Pi agents, so it never ran at scale. Restoring eligibility is what exposes it. Awaiting each teardown also makes `tickInFlight` real: it was cleared in the `finally` as soon as the promises were launched, so it never covered the drains it was meant to guard. Each candidate still re-validates against a fresh plan at its own turn, so a slow drain cannot act on stale confirmation, and per-candidate failures are already caught so one stuck teardown cannot abort the rest.
|
Review status (final branch Verdict: land after CI completes; no further code changes recommended.
The user-owned untracked |
AttachmentsElectron validation screenshots for PR #16430
|
|
Update: CI failure is confirmed unrelated to this PR: Node 24 shard 2/16 fails only (p95 231.9ms vs 220ms budget); 15 other Node 24 shards passed and all other required checks are green. The required gate is red solely because that test aggregate failed. Please rerun/investigate that flaky performance-budget shard before merge. |
|
Correction: CI failure is confirmed unrelated to this PR. Node 24 shard 2/16 fails only at src/renderer/src/lib/palette-match/palette-match-performance.test.ts:128 (p95 231.9ms vs 220ms budget). The other 15 Node 24 shards passed and all other required checks are green. The required verify gate is red solely because that test aggregate failed. Please rerun/investigate that performance-budget shard before merge. |
|
Validation clarification: the attached Electron screenshots do not prove that real Claude/Codex agents sleep. The orchestrated worker launched the exact PR worktree and validated the Agent sleep setting UI, but its isolated profile contained only a live shell: The worker report records this explicitly. The lifecycle behavior is covered by focused tests; live non-Pi agent sleep remains an Electron validation gap. |
|
Real-agent Electron validation completed on PR #16430 (isolated profile, exact PR worktree, Playwright CDP via Passed
Evidence Explicit gaps
No product source changes were made during this review. |
|
Correction to the evidence link above: |
…i#16430) * fix(sleep): let non-Pi agents hibernate again, and stop repaints resetting the idle clock Auto-hibernation could never fire for claude, codex, gemini, opencode, grok, or any other resumable TUI agent — only pi/omp/prime-agent. stablyai#10238 broadened the `origin: 'live'` resume anchor so every resumable agent keeps its `--resume` handle when a turn ends. The planner rejects any pane that already has a sleeping record, and its exemption was still Pi-only. Since the planner's eligibility conditions are the same conditions that write the anchor, that rejection covered every otherwise-eligible non-Pi pane. - Split the conflated predicate. `isLiveResumeAnchorForCompletedAgent` answers "is this record just this pane's own live anchor?" with no vendor gate; the Pi-gated wrapper keeps today's exact semantics for the manual-sleep and quit capture call sites; `isAutomaticHibernationAllowed` carries the `automaticResumeBlockedBy` fence on its own. - Fence automatic hibernation. A fenced worker must not be auto-relaunched, and the capture does not copy the flag — so hibernating one would erase it. Checked in the planner and again inside the shutdown action against freshest state, re-evaluated after the synchronous capture callback that could itself fence it. - Anchor the idle clock on `stateStartedAt`, not `updatedAt`. Same-state repaints (OSC 9999, reconnect replays) advance `updatedAt`, restarting the 30-minute countdown and invalidating the two-tick confirmation. - Floor that anchor on PTY-binding age and a boundary-resolution stamp, so a wake or app restart still gets a full idle window instead of sleeping the whole backlog on the ancient timing main replays. The boundary stamp is written synchronously where the flag clears; sampling it per tick would miss a boundary written and cleared between two samples. - Signature drops `updatedAt` and gains agent kind plus full resume identity, which is the change detection `updatedAt` was providing by accident. Splits the planner into planner / pane-eligibility / snapshot to stay under the file length limit. * fix(sleep): drain pane teardowns sequentially `runAgentHibernationTick` launched every confirmed shutdown unawaited, so a backlog fanned all of them out at once. Each shutdown re-runs a full runtime-liveness sweep (one `terminal.list` per runtime-owned worktree, 10s timeout) and then a `terminal.stopExact` (15s timeout) — so ~100 overdue panes meant ~100 concurrent sweeps plus ~100 concurrent stops plus interleaved persistence writes. On an SSH runtime that is hundreds of near-simultaneous RPCs at the relay. The fanout predates this branch, but auto-hibernation could not fire for non-Pi agents, so it never ran at scale. Restoring eligibility is what exposes it. Awaiting each teardown also makes `tickInFlight` real: it was cleared in the `finally` as soon as the promises were launched, so it never covered the drains it was meant to guard. Each candidate still re-validates against a fresh plan at its own turn, so a slow drain cannot act on stale confirmation, and per-candidate failures are already caught so one stuck teardown cannot abort the rest. * perf(sleep): scope hibernation rechecks to pane owner
…i#16430) * fix(sleep): let non-Pi agents hibernate again, and stop repaints resetting the idle clock Auto-hibernation could never fire for claude, codex, gemini, opencode, grok, or any other resumable TUI agent — only pi/omp/prime-agent. stablyai#10238 broadened the `origin: 'live'` resume anchor so every resumable agent keeps its `--resume` handle when a turn ends. The planner rejects any pane that already has a sleeping record, and its exemption was still Pi-only. Since the planner's eligibility conditions are the same conditions that write the anchor, that rejection covered every otherwise-eligible non-Pi pane. - Split the conflated predicate. `isLiveResumeAnchorForCompletedAgent` answers "is this record just this pane's own live anchor?" with no vendor gate; the Pi-gated wrapper keeps today's exact semantics for the manual-sleep and quit capture call sites; `isAutomaticHibernationAllowed` carries the `automaticResumeBlockedBy` fence on its own. - Fence automatic hibernation. A fenced worker must not be auto-relaunched, and the capture does not copy the flag — so hibernating one would erase it. Checked in the planner and again inside the shutdown action against freshest state, re-evaluated after the synchronous capture callback that could itself fence it. - Anchor the idle clock on `stateStartedAt`, not `updatedAt`. Same-state repaints (OSC 9999, reconnect replays) advance `updatedAt`, restarting the 30-minute countdown and invalidating the two-tick confirmation. - Floor that anchor on PTY-binding age and a boundary-resolution stamp, so a wake or app restart still gets a full idle window instead of sleeping the whole backlog on the ancient timing main replays. The boundary stamp is written synchronously where the flag clears; sampling it per tick would miss a boundary written and cleared between two samples. - Signature drops `updatedAt` and gains agent kind plus full resume identity, which is the change detection `updatedAt` was providing by accident. Splits the planner into planner / pane-eligibility / snapshot to stay under the file length limit. * fix(sleep): drain pane teardowns sequentially `runAgentHibernationTick` launched every confirmed shutdown unawaited, so a backlog fanned all of them out at once. Each shutdown re-runs a full runtime-liveness sweep (one `terminal.list` per runtime-owned worktree, 10s timeout) and then a `terminal.stopExact` (15s timeout) — so ~100 overdue panes meant ~100 concurrent sweeps plus ~100 concurrent stops plus interleaved persistence writes. On an SSH runtime that is hundreds of near-simultaneous RPCs at the relay. The fanout predates this branch, but auto-hibernation could not fire for non-Pi agents, so it never ran at scale. Restoring eligibility is what exposes it. Awaiting each teardown also makes `tickInFlight` real: it was cleared in the `finally` as soon as the promises were launched, so it never covered the drains it was meant to guard. Each candidate still re-validates against a fresh plan at its own turn, so a slow drain cannot act on stale confirmation, and per-candidate failures are already caught so one stuck teardown cannot abort the rest. * perf(sleep): scope hibernation rechecks to pane owner (cherry picked from commit 630b717)
…i#16430) * fix(sleep): let non-Pi agents hibernate again, and stop repaints resetting the idle clock Auto-hibernation could never fire for claude, codex, gemini, opencode, grok, or any other resumable TUI agent — only pi/omp/prime-agent. stablyai#10238 broadened the `origin: 'live'` resume anchor so every resumable agent keeps its `--resume` handle when a turn ends. The planner rejects any pane that already has a sleeping record, and its exemption was still Pi-only. Since the planner's eligibility conditions are the same conditions that write the anchor, that rejection covered every otherwise-eligible non-Pi pane. - Split the conflated predicate. `isLiveResumeAnchorForCompletedAgent` answers "is this record just this pane's own live anchor?" with no vendor gate; the Pi-gated wrapper keeps today's exact semantics for the manual-sleep and quit capture call sites; `isAutomaticHibernationAllowed` carries the `automaticResumeBlockedBy` fence on its own. - Fence automatic hibernation. A fenced worker must not be auto-relaunched, and the capture does not copy the flag — so hibernating one would erase it. Checked in the planner and again inside the shutdown action against freshest state, re-evaluated after the synchronous capture callback that could itself fence it. - Anchor the idle clock on `stateStartedAt`, not `updatedAt`. Same-state repaints (OSC 9999, reconnect replays) advance `updatedAt`, restarting the 30-minute countdown and invalidating the two-tick confirmation. - Floor that anchor on PTY-binding age and a boundary-resolution stamp, so a wake or app restart still gets a full idle window instead of sleeping the whole backlog on the ancient timing main replays. The boundary stamp is written synchronously where the flag clears; sampling it per tick would miss a boundary written and cleared between two samples. - Signature drops `updatedAt` and gains agent kind plus full resume identity, which is the change detection `updatedAt` was providing by accident. Splits the planner into planner / pane-eligibility / snapshot to stay under the file length limit. * fix(sleep): drain pane teardowns sequentially `runAgentHibernationTick` launched every confirmed shutdown unawaited, so a backlog fanned all of them out at once. Each shutdown re-runs a full runtime-liveness sweep (one `terminal.list` per runtime-owned worktree, 10s timeout) and then a `terminal.stopExact` (15s timeout) — so ~100 overdue panes meant ~100 concurrent sweeps plus ~100 concurrent stops plus interleaved persistence writes. On an SSH runtime that is hundreds of near-simultaneous RPCs at the relay. The fanout predates this branch, but auto-hibernation could not fire for non-Pi agents, so it never ran at scale. Restoring eligibility is what exposes it. Awaiting each teardown also makes `tickInFlight` real: it was cleared in the `finally` as soon as the promises were launched, so it never covered the drains it was meant to guard. Each candidate still re-validates against a fresh plan at its own turn, so a slow drain cannot act on stale confirmation, and per-candidate failures are already caught so one stuck teardown cannot abort the rest. * perf(sleep): scope hibernation rechecks to pane owner







Problem
Agent auto-sleep never fired for
claude,codex,gemini,opencode,grok— or any resumable TUI agent exceptpi/omp/prime-agent. Reported as "not triggering as often as it should"; it was actually total for those agents.Root cause. #10238 (
b97e8c4e27) broadened theorigin: 'live'resume anchor so every resumable agent keeps its--resumehandle when a turn ends — fixing bare-shell restore after macOS logout (#9454). The planner rejects any pane that already carries a sleeping record, and its exemption was left Pi-only from #8991. Because the planner's eligibility conditions (done+ resumable + provider session + resume argv) are exactly the conditions that write the anchor, that rejection covered every otherwise-eligible non-Pi pane.Runtime-confirmed: driving the real store through a Claude
working → donewrites the anchor, and the planner then returns[]for a 31-minute-idle pane in a background worktree. Same for codex/gemini/opencode/grok. The identical pane without the record plans correctly.Changes
isLiveResumeAnchorForCompletedAgentanswers "is this record just this pane's own live anchor?" — no vendor gate. The Pi-gated wrapper keeps today's exact semantics at the manual-sleep (agent-status.ts:743) and quit-capture (:3205) call sites.isAutomaticHibernationAllowedcarries theautomaticResumeBlockedByfence separately.sleepingRecordFromEntrydoes not copy the flag — so hibernating one would erase the fence. Checked in the planner, and again insideshutdownCompletedAgentPaneForHibernationagainst freshest state, re-evaluated after the synchronous capture callback (which can itself set it).stateStartedAt. Same-state repaints (OSC 9999, reconnect snapshot replays) advanceupdatedAt, restarting the 30-minute countdown and invalidating the two-tick confirmation.stateStartedAtis the field that exists to survive within-state pings.dropHibernatedAgentStatusPanenever notifies main and main'slastStatusByPaneKeyis persisted, so a woken or restarted pane replays an ancient anchor and would be instantly overdue. A wake spawns a fresh PTY and the map starts empty at launch, so binding age restores the graceupdatedAtgave by accident. The boundary stamp is written synchronously wheresessionBoundaryclears — sampling it on the 60s tick would miss a boundary written and cleared between samples.updatedAt, gaining agent kind and full resume identity (provider key/id/transcript path) — the change detectionupdatedAtwas providing incidentally.Planner split into
planner/pane-eligibility/snapshotto stay under the file-length limit.Expected behavior change
This is the first time auto-sleep actually works since 2026-07-23, so the first run after updating will sleep a backlog of overdue panes. The binding floor delays that by one idle window after launch, and teardowns now drain one at a time (see below), so the backlog clears over minutes rather than all at once. Sleeping is the intended end state and is reversible via
--resume. This is deliberate and signed off.Sequential teardown drain (second commit)
runAgentHibernationTicklaunched every confirmed shutdown unawaited. Each shutdown re-runs a full runtime-liveness sweep (oneterminal.listper runtime-owned worktree, 10s timeout) and then aterminal.stopExact(15s timeout) — so a backlog of ~100 overdue panes meant ~100 concurrent sweeps plus ~100 concurrent stops plus interleaved persistence writes. On an SSH runtime that is hundreds of near-simultaneous RPCs at the relay.The fanout predates this branch; auto-hibernation simply could not fire for non-Pi agents, so it never ran at scale. Restoring eligibility is what exposes it.
Awaiting each teardown also makes
tickInFlightreal — it was cleared in thefinallyas soon as the promises were launched, so it never covered the drains it was meant to guard. Each candidate still re-validates against a fresh plan at its own turn, so a slow drain cannot act on stale confirmation, and per-candidate failures are already caught so one stuck teardown cannot abort the rest.Head-of-line blocking is the tradeoff: a slow pane delays the rest. Bounded by RPC timeouts (~25s worst case per pane) on a background reclaimer that ticks every 60s. A small worker pool is the natural upgrade if first-run drain latency ever matters; it is not needed for correctness.
Testing
agent-hibernation-planner.test.ts— parametrized over every non-PiRESUMABLE_TUI_AGENTSentry; fence rejection with an unfenced control; repaint/idle-anchor; signature stability and identity invalidation withupdatedAtheld constant; both floors.agent-hibernation-live-anchor-e2e.test.ts— drives the real storeworking → done, asserts the live anchor is written, then feeds real store state to the planner. This pins the seam fix(agent-status): resume finished agents after macOS logout instead of a bare shell (#9454) #10238 broke.agent-hibernation-pane-age.test.ts— binding carry/reset, layout-gap retention, age expiry, tab-removal pruning.