Skip to content

fix(terminal): keep a deliberately slept workspace cold until it is woken - #20075

Merged
nwparker merged 5 commits into
mainfrom
nwparker/slept-workspace-stays-cold
Sep 11, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/slept-workspace-stays-cold

Conversation

@nwparker

@nwparker nwparker commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​812 $\color{#cf222e}{\Huge{\mathbf{−}}}$​11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​801
Prod 12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​214 $\color{#cf222e}{\Huge{\mathbf{−}}}$​104 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​110

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's main, 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 … --resume typed into a fresh terminal.

What changed

@Jinwoo-H's commits, verbatim:

  • The in-memory sleep-intent marker now outlives a successful sleep instead of being cleared in finally.
  • The deferred pane connect waits while the marker is set and the pane has no queued startup, and resumes when it clears. This sits before both the reattach and fresh-spawn arms — manual sleep keeps tab.ptyId as a wake hint, so a remount otherwise reattaches the dead session id and the daemon's create-or-attach spawns a fresh shell.
  • A waiting pane resumes only if its tab generation is still current, so an activation that remounts the tab does not also connect the stale pane, and it re-arms so a later sleep can hold it again.
  • The marker is released on activation (setActiveWorktree, setActiveFolderWorkspace), on any PTY bind to one of the workspace's tabs (updateTabPtyId, createTab with an initial PTY — covers CLI, automation and client wakes), and forgotten without waking anything on purge.
  • withWorktreeSleepTeardown fences 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 main with merge conflicts and red CI. The red was not their change — static analysis failed on a stale localization runtime catalog (components.onboarding.integrations.capabilities.*, unrelated to sleep). On current main the catalog regenerates to a no-op.

The fix is still needed. main has 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-closer attaches (live PTY); the slept workspace spawns (sleep killed its PTY):

04:27:22.902  session-attached  crash-closer@@9cc873ad          ← unpark sweep
04:27:23.007  session-created   fix-inline-…@@c490b5b6          ← dead session → fresh spawn
04:27:24.884  session-created   fix-inline-…@@cc62a5d4            (hasCommand: true → claude --resume)

05:15:37.086  session-attached  crash-closer@@9cc873ad
05:15:37.212  session-created   fix-inline-…@@c490b5b6
05:15:37.384  session-created   fix-inline-…@@cc62a5d4

Three sleeps (04:03, 04:31, 04:59) → three self-wakes (04:27, 04:59, 05:15), 16–28 min apart, no sidebar_worktree_activate breadcrumb 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: candidateParkedTerminalTabIds refuses to park a tab with hasActivityTerminalPortal, one in terminalPaneSplitMountLeaseTabIds, or any tab while shouldMeasureHiddenWorktree is 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.ts asserts it mechanically.

Testing

macOS, local execution host. Renderer-only, no platform-dependent code.

  • Manually tested locally
  • Automated tests added/updated (all authored by @Jinwoo-H)

The regression test still discriminates on today's main — I put slept-workspace-remount-wake.spec.ts on a clean origin/main checkout and ran it:

main:        1 failed — "host created a session for the slept workspace"
this branch: 1 passed
  • tests/e2e/slept-workspace-remount-wake.spec.ts + tests/e2e/terminal-sleep-wake-restore.spec.ts (electron-headless) — 2 passed
  • pnpm tc — clean
  • pnpm 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 gone
  • pnpm 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: updateTabPtyId clears the marker for the whole workspace, so one narrow bind — a CLI orca terminal creating 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.paneStartup exemption treats a queued startup as an explicit launch. pendingStartupByTabId isn'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

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.

Jinwoo-H and others added 5 commits September 11, 2026 00:57
…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.
@coderabbitai

coderabbitai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The 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 14f41

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 17 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: keeping deliberately slept workspaces cold until they are explicitly woken.
Description check ✅ Passed The description is detailed and covers the change, motivation, linked issue, visual proof, testing, AI disclosure, and known open questions. The Review section is empty and the template checklist rema…
Linked Issues check ✅ Passed The PR satisfies the coding objective in #10205. runSleepWorktrees preserves the sleep marker through teardown, and installRunDeferredConnect blocks ambient pane reconnects while the marker exists…
Out of Scope Changes check ✅ Passed The changes stay within #10205. The sleep-intent lifecycle, terminal connection guards, tab resolution, teardown cleanup, and related unit and end-to-end tests directly support keeping deliberately sl…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Enable exposeStore before asserting the diagnostic.

recordPtyConnectDiagnostic skips __ptyConnectDiag when e2eConfig.exposeStore is false. installTerminalTestGlobals() does not configure this flag. Add the E2E config mock, then assert that the latest diagnostic contains WAIT FOR WAKE.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 46d3c117-40cd-4fe1-94bc-c65201ca9ddb

📥 Commits

Reviewing files that changed from the base of the PR and between 6bb2b0c and 14f41f9.

📒 Files selected for processing (17)
  • src/renderer/src/components/sidebar/sleep-worktree-flow.test.ts
  • src/renderer/src/components/sidebar/sleep-worktree-flow.ts
  • src/renderer/src/components/terminal-pane/pty-connection-deliberate-sleep-guard.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts
  • src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts
  • src/renderer/src/components/terminal-pane/pty-connection/run-deferred-connect.ts
  • src/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.ts
  • src/renderer/src/lib/worktree-sleep-intent.ts
  • src/renderer/src/store/slices/worktree-sleep-intent-lifecycle.test.ts
  • src/renderer/src/store/slices/worktrees/session/set-active-folder-workspace.ts
  • src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts
  • src/renderer/src/store/slices/worktrees/teardown/remove-worktree.ts
  • src/renderer/src/store/slices/worktrees/teardown/worktree-purge-state.ts
  • src/renderer/src/store/terminals/terminal-pty-bindings.ts
  • src/renderer/src/store/terminals/terminal-tab-creation.ts
  • tests/e2e/helpers/slept-workspace-probe.ts
  • tests/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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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' src

Repository: 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.ts

Repository: 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.ts

Repository: 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Connect-entry sleep gate — run-deferred-connect.ts now waits on the sleep marker (while no queued startup) instead of latching cold; it cancels the pending rAF/fallback timer and subscribes to onWorktreeSleepIntentCleared.
  • Generation-guarded wake — the wake listener re-resolves the pane's tab via findTerminalTabForPane and 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.ts gains a teardown fence (withWorktreeSleepTeardown), wake listeners, and a purge-only forget; the marker is released on activation, any PTY bind, and createTab with initialPtyId.
  • Per-workspace marking — sleep-worktree-flow.ts marks each worktree as its own teardown starts and releases a workspace the user activated mid-batch.
  • Dedup'd tab resolution — connect-pane-pty.ts and fresh-spawn-start.ts now share findTerminalTabForPane instead of duplicating resolveTerminalTabId + 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-side totalCount === 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Sleeping workspaces revive without user activation — hard to diagnose (open question on opt-in lifecycle logging)

2 participants