Repository navigation
fix(terminal): keep a deliberately slept workspace cold until it is woken - #20075
Conversation
…oken Sleeping a workspace kills its PTYs but keeps its panes mounted and keeps each tab's session id as a wake hint. Any later remount of those panes (recovery, parking, portals) reattached that dead id, and the daemon's create-or-attach spawned a fresh shell, so slept workspaces revived on their own (#10205). The existing sleep-intent marker now outlives teardown and gates the deferred connect itself, so both the reattach and fresh-spawn arms stay cold. It is released by activating the workspace, by any PTY binding to one of its tabs (CLI, automation, client wake), and by purge. A queued startup still connects. Reproduces the community root cause from gatsby74 in #13343; the regression e2e remounts a slept hidden pane and fails on main. Co-authored-by: gatsby74 <gatsby74@users.noreply.github.com> Co-authored-by: mmarabel <mmarabel@users.noreply.github.com>
… cold A pane whose connect ran while its workspace was slept used to mark itself connected and stop; nothing re-armed it, so a wake that produced a live PTY before the user clicked (CLI create, background agent resume, split panes) left panes stranded. The connect now waits on the sleep marker and resumes when the marker clears, and a torn-down pane drops its listener. Tabs created with a live PTY clear the marker too, the sleep flow marks each workspace only when its own teardown starts, and purge forgets the marker without waking anything.
Activation clears the sleep marker after the set() that bumps dead tabs' generations, and the waiting pane only resumes its connect when its tab generation is still current. Otherwise the stale pane and its remounted successor both reattached the same session id on a deliberate wake.
… after wake The wake listener looked the tab up by the pane's render id, which can be a unified id whose terminal tab lives under entityId, so the generation check declined forever for those panes. Mount, fresh spawn, and the wake listener now share one live resolver. The wait flag resets when the listener fires so a second sleep can hold the pane again, listener dispatch is guarded, folder activation clears after its own set(), and the sleep flow re-asserts the marker after each teardown while releasing a workspace the user activated meanwhile.
…indow A spawn resolving while shutdown was still awaiting the host bound a PTY and cleared the marker, waking every waiting pane mid-sleep; re-marking afterwards could not un-connect them. The sleep flow now scopes each teardown so binds in that window are not wakes. The e2e asserts a deliberate wake yields exactly one PTY, and the dispose test proves the listener is gone.
📝 WalkthroughWalkthroughThe change adds per-worktree sleep intents that persist after successful teardown and clear on explicit activation, PTY binding, live-tab creation, or purge. Teardown windows prevent premature clearing during shutdown. PTY connection now resolves terminal tabs through a shared helper and waits for wake while preserving generation checks. Unit and end-to-end tests cover sleep, wake, remount, listener, purge, and diagnostic behavior. Priority: ⬆️ High Merge Risk: 🟡 Moderate · up to An overlapping shutdown can let a deliberately slept workspace reconnect before teardown completes. The sleep-guard diagnostic contract also lacks direct renderer coverage, making regressions harder to isolate. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ 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 |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/pty-connection-deliberate-sleep-guard.test.ts (1)
182-185: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winEnable
exposeStorebefore asserting the diagnostic.
recordPtyConnectDiagnosticskips__ptyConnectDiagwhene2eConfig.exposeStoreis false.installTerminalTestGlobals()does not configure this flag. Add the E2E config mock, then assert that the latest diagnostic containsWAIT FOR WAKE.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 46d3c117-40cd-4fe1-94bc-c65201ca9ddb
📒 Files selected for processing (17)
src/renderer/src/components/sidebar/sleep-worktree-flow.test.tssrc/renderer/src/components/sidebar/sleep-worktree-flow.tssrc/renderer/src/components/terminal-pane/pty-connection-deliberate-sleep-guard.test.tssrc/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.tssrc/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.tssrc/renderer/src/components/terminal-pane/pty-connection/run-deferred-connect.tssrc/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.tssrc/renderer/src/lib/worktree-sleep-intent.tssrc/renderer/src/store/slices/worktree-sleep-intent-lifecycle.test.tssrc/renderer/src/store/slices/worktrees/session/set-active-folder-workspace.tssrc/renderer/src/store/slices/worktrees/session/set-active-worktree.tssrc/renderer/src/store/slices/worktrees/teardown/remove-worktree.tssrc/renderer/src/store/slices/worktrees/teardown/worktree-purge-state.tssrc/renderer/src/store/terminals/terminal-pty-bindings.tssrc/renderer/src/store/terminals/terminal-tab-creation.tstests/e2e/helpers/slept-workspace-probe.tstests/e2e/slept-workspace-remount-wake.spec.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| try { | ||
| return await teardown() | ||
| } finally { | ||
| tearingDownWorktreeIds.delete(worktreeId) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings
Length of output: 30403
🏁 Script executed:
#!/bin/bash
set -e
file=$(fd -t f -i 'worktree-sleep-intent\.ts$' . | head -n 1)
printf '%s\n' "FILE=$file"
cat -n "$file"
printf '\n--- references ---\n'
rg -n -C 3 'withWorktreeSleepTeardown|clearWorktreeSleepIntent|tearingDownWorktreeIds|worktreeSleepIntent' srcRepository: stablyai/orca
Length of output: 38958
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- teardown call sites ---'
rg -n -C 12 'withWorktreeSleepTeardown' src/renderer/src
printf '%s\n' '--- sleep flow entrypoints and overlap guards ---'
rg -n -C 8 'runSleepWorktree|runSleepWorktrees|sleepWorktree|sleep.*worktree' src/renderer/src/components/sidebar/sleep-worktree-flow.ts src/renderer/src/components/sidebar
printf '%s\n' '--- PTY bind clear path ---'
sed -n '230,292p' src/renderer/src/store/terminals/terminal-pty-bindings.ts
printf '%s\n' '--- lifecycle tests around teardown ---'
sed -n '115,165p' src/renderer/src/store/slices/worktree-sleep-intent-lifecycle.test.tsRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- production callers ---'
rg -n 'runSleepWorktree|runSleepWorktrees' src/renderer/src --glob '!**/*.test.ts'
printf '%s\n' '--- command implementation context ---'
sed -n '120,155p' src/renderer/src/components/sidebar/use-worktree-context-menu-commands.ts
printf '%s\n' '--- per-row sleep action references ---'
rg -n -C 5 'sleepWorktree|runSleep|handleCloseTerminals|handleSleepSubtree' src/renderer/src/components/sidebar --glob '!**/*.test.ts'
printf '%s\n' '--- PTY bind context ---'
sed -n '255,285p' src/renderer/src/store/terminals/terminal-pty-bindings.tsRepository: stablyai/orca
Length of output: 22817
Make teardown tracking reference-counted per worktree.
When two withWorktreeSleepTeardown(worktreeId, ...) calls overlap, the first finally removes the shared tearingDownWorktreeIds entry. A PTY bind can then call clearWorktreeSleepIntent(worktreeId) while the second teardown is still active and wake waiting panes too early. Use a per-worktree count or unique teardown tokens, and test this overlap.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Connect-entry sleep gate —
run-deferred-connect.tsnow waits on the sleep marker (while no queued startup) instead of latching cold; it cancels the pending rAF/fallback timer and subscribes toonWorktreeSleepIntentCleared. - Generation-guarded wake — the wake listener re-resolves the pane's tab via
findTerminalTabForPaneand only reconnects when the tab generation is still current, so an activation wake (which bumps generation) lets the remounted pane connect once while the stale pane stays out. - Marker outlives sleep —
worktree-sleep-intent.tsgains a teardown fence (withWorktreeSleepTeardown), wake listeners, and a purge-onlyforget; the marker is released on activation, any PTY bind, andcreateTabwithinitialPtyId. - Per-workspace marking —
sleep-worktree-flow.tsmarks each worktree as its own teardown starts and releases a workspace the user activated mid-batch. - Dedup'd tab resolution —
connect-pane-pty.tsandfresh-spawn-start.tsnow sharefindTerminalTabForPaneinstead of duplicatingresolveTerminalTabId+ owner/fallback lookup. I traced this against the pre-PR logic (byId worktree → byId owner → flat scan → unified-tab) and it is behavior-preserving. - Tests — the unit suite (
pty-connection-deliberate-sleep-guard.test.ts,worktree-sleep-intent-lifecycle.test.ts) has exact, discriminating assertions (connect called/not-called, generation remount case, teardown-fence case, purge-no-wake case), and the e2e spec asserts non-vacuous preconditions (mounted pane still carrying its wake hint) plus host-sidetotalCount === 0.
The interaction with the pre-existing hasWorktreeSleepIntent guard in terminal-pty-release.ts (clearTabPtyId) stays consistent now that the marker persists: a slept workspace's PTYs are dead, and late exits still shouldn't stamp activity.
ℹ️ Design decisions already surfaced in the PR body
Both open questions are well-scoped and non-blocking as written, but they are maintainer calls worth an explicit answer before this becomes long-lived behavior: (1) updateTabPtyId clears the marker workspace-wide, so one narrow CLI/automation bind resumes every waiting pane, not just that tab's; (2) the !session.paneStartup exemption treats a queued startup as an explicit launch, reachable only via in-memory leftover since pendingStartupByTabId isn't persisted.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Rebase of #18051 by @Jinwoo-H onto current
main, so it can land. All five commits are theirs, unmodified — I resolved one import conflict, verified the whole thing against today'smain, and added a co-author trailer for the design source.Supersedes #18051 and #20039. Design originates in #13343 by @mmarabel.
ELI5
Putting a workspace to sleep must keep it asleep until you open it. Before this, anything that re-mounted one of its terminal panes behind the scenes brought the shell back — often with
claude … --resumetyped into a fresh terminal.What changed
@Jinwoo-H's commits, verbatim:
finally.tab.ptyIdas a wake hint, so a remount otherwise reattaches the dead session id and the daemon's create-or-attach spawns a fresh shell.setActiveWorktree,setActiveFolderWorkspace), on any PTY bind to one of the workspace's tabs (updateTabPtyId,createTabwith an initial PTY — covers CLI, automation and client wakes), and forgotten without waking anything on purge.withWorktreeSleepTeardownfences the teardown window so a spawn resolving mid-sleep cannot un-sleep the workspace; per-workspace marking inside the batch loop; a workspace the user activated mid-batch is released instead.Why this rebase
#18051 was 660 commits behind
mainwith merge conflicts and red CI. The red was not their change —static analysisfailed on a stale localization runtime catalog (components.onboarding.integrations.capabilities.*, unrelated to sleep). On currentmainthe catalog regenerates to a no-op.The fix is still needed.
mainhas since landed #20034 (perf(terminal): mount only the visible pane on a worktree switch), which could plausibly have made the regression test vacuous. It did not — see below.Field evidence (new, from #20039)
I hit this independently on a packaged build and the daemon log names a trigger neither PR had: a background unpark sweep, not an activation. Each respawn trails another hidden workspace's pane remounting in the same pass by ~100ms.
crash-closerattaches (live PTY); the slept workspace spawns (sleep killed its PTY):Three sleeps (04:03, 04:31, 04:59) → three self-wakes (04:27, 04:59, 05:15), 16–28 min apart, no
sidebar_worktree_activatebreadcrumb for that workspace in between. So this is not a theoretical mechanism: in a long session with many workspaces it is the dominant trigger, which is what @Jinwoo-H's scope note left open.I also tried fixing this by latching the terminal park on sleep (#20039) and abandoned it:
candidateParkedTerminalTabIdsrefuses to park a tab withhasActivityTerminalPortal, one interminalPaneSplitMountLeaseTabIds, or any tab whileshouldMeasureHiddenWorktreeis set — each a remount a park-based gate cannot stop. The connect entry is the correct chokepoint.Linked issue
Fixes #10205
Visual Proof
N/A — what this fixes is the absence of an event: a slept workspace stays slept instead of re-appearing minutes later. The daemon log above is the observable signal, and
slept-workspace-remount-wake.spec.tsasserts it mechanically.Testing
macOS, local execution host. Renderer-only, no platform-dependent code.
The regression test still discriminates on today's
main— I putslept-workspace-remount-wake.spec.tson a cleanorigin/maincheckout and ran it:tests/e2e/slept-workspace-remount-wake.spec.ts+tests/e2e/terminal-sleep-wake-restore.spec.ts(electron-headless) — 2 passedpnpm tc— cleanpnpm run sync:localization-runtime-catalog— no diff, so the fix(terminal): keep a deliberately slept workspace cold until it is woken #18051 CI failure is gonepnpm test src/renderer/src/components src/renderer/src/lib src/renderer/src/store— 28,015 passed. One unrelated failure,ai-vault-session-worktree-map.test.tsx:235(expect(elapsedMs).toBeLessThan(150)), a wall-clock assertion that flaked while two Electron e2e suites ran concurrently; passes in isolation and the file has zero references to sleep.Open question for a maintainer
Clear-on-bind is workspace-wide:
updateTabPtyIdclears the marker for the whole workspace, so one narrow bind — a CLIorca terminalcreating a single tab in a slept workspace — resumes every waiting pane, not just that tab's. Intended per @Jinwoo-H's design ("covers CLI, automation, and client wakes"), and I reached the same question from the park side. Worth an explicit decision rather than inheriting it.Second, smaller: the
&& !session.paneStartupexemption treats a queued startup as an explicit launch.pendingStartupByTabIdisn't persisted, so only an in-memory leftover could reach it — if a startup queued for a pane whose spawn never consumed it before sleep is reachable, that exemption survives the sleep. Neither blocks this landing.Credit
Co-authored-byon the base commit.Co-authored-byon the base commit from fix(terminal): keep a deliberately slept workspace cold until it is woken #18051.My contribution is the rebase, the verification above, and the field evidence. @Jinwoo-H, if you'd rather land this yourself on your own branch, say so and I'll close this.
AI Disclosure
Rebase, verification and review AI-assisted (Claude Opus 4.6 in Claude Code); upstream commits per @Jinwoo-H's own disclosure on #18051.