Skip to content

fix(workspaces): keep slept workspaces parked so they stop waking themselves - #20039

Closed
nwparker wants to merge 1 commit into
mainfrom
nwparker/sleep-branch-keeps-unsleeping
Closed

nwparker wants to merge 1 commit into
mainfrom
nwparker/sleep-branch-keeps-unsleeping

Conversation

@nwparker

@nwparker nwparker commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​123 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​120
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​100 $\color{#cf222e}{\Huge{\mathbf{−}}}$​37 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​63

ELI5

You put a workspace to sleep. Twenty minutes later it's awake again, with your agent relaunched, and you never touched it. Sleep killed the terminals but forgot to tell the UI to stop re-opening them — so the next time Orca shuffled hidden workspaces in the background, it tried to reconnect to the terminals sleep had just killed, failed, and started fresh ones. Now sleeping also tells the UI "leave this one alone until I come back."

What Changed

  • requestManualTerminalWorktreePark takes a reason ('manual' | 'workspace-sleep').
  • A 'workspace-sleep' park skips the on-demand eligibility gates. A slept workspace has no surviving PTY, so canManuallyParkTerminalWorktreeRenderers can never pass (isParkRestorableTerminalPty is false for a dead local PTY, and the gate is off entirely when terminalHiddenViewParking is disabled) — and it would toast "These terminals cannot be parked safely." on every sleep. Manual parks keep the gates and the warning.
  • runSleepWorktrees latches that park after the last teardown step, so only a workspace that fully slept earns it.
  • The latch releases on reveal (existing effect) and on BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT — a navigation-free wake (mobile, CLI reveal) only suspends the park for its 3s measure window, so a latch left set would unmount the panes it just woke.

Why

Fixes the "no durable stay-dead-until-Wake gate" this issue identifies.

Sleep kills the workspace's PTYs but keeps the tab records and layout pty ids (keepIdentifiers: true), and leaves the workspace in mountedWorktreeIdsRef — which terminal-cold-activation.ts only prunes when a worktree leaves workspaceSurfaceIds, i.e. when it is deleted. The panes then cold-park like any hidden workspace. When the park verdict flips back, they remount, runDeferredSessionReattachChoice reattaches to the restored session id, misses, and handleReattachResult falls through to startFreshColdRestoreAgentResume — a fresh spawn under the same deterministic session id, re-running the agent's --resume. Live PTYs reappear, hasActiveWorkspaceActivity goes true, and the sidebar row un-sleeps.

From my own daemon log — every respawn trails another hidden workspace's pane remounting in the same sweep by ~100ms. crash-closer attaches (its PTY is alive); 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) produced three self-wakes (04:27, 04:59, 05:15) at irregular 16–28 min gaps matching park-verdict churn, with no sidebar activation for that workspace in between.

Why park rather than block the spawn: the reattach→cold-restore fallback is correct behaviour for a real wake — it is how waking a slept workspace restores its agents. The bug is that the panes remount at all. Keeping them parked leaves the existing, tested wake path untouched; reveal releases the latch and wake proceeds normally.

Linked Issue

Fixes #10205

Visual Proof

N/A — the change has no visual delta to capture. What it fixes is the absence of an event: a slept row that previously re-appeared after 16–28 minutes now stays slept. The daemon-log evidence above is the observable signal; tests/e2e/terminal-sleep-wake-restore.spec.ts covers the visible sleep→wake path and still passes.

Testing

Tested on macOS (local execution host). Not exercised on Windows/Linux/SSH — the change is renderer-only with no platform-dependent code (no paths, processes, shells, or native modules).

  • I manually tested these changes locally
  • Automated tests added/updated

Added terminal-worktree-sleep-park-latch.test.tsx (4 cases): the sleep reason parks a workspace the gates would refuse; a manual park still refuses and warns; the latch releases on reveal; the latch releases on a background wake. Extended sleep-worktree-flow.test.ts with the latch, its ordering, and a parameterised case that no park is latched when terminal shutdown or host suspension fails.

  • pnpm tc — clean
  • pnpm test src/renderer/src/components src/renderer/src/lib — 2949 files / 24 656 tests pass
  • pnpm test src/renderer/src/components/sidebar src/renderer/src/components/terminal-pane — 745 files / 6790 tests pass
  • tests/e2e/terminal-sleep-wake-restore.spec.ts (electron-headless) — passes: slept terminal output restores and accepts fresh input after wake

Verified while reviewing, not just assumed:

  • Parked byte watchers only subscribeToPtyData — they never connect or spawn, so parking a slept workspace cannot itself start a process.
  • handlePtyExit bails on consumeSuppressedPtyExit before any parked-exit tab-close logic, so the sleep kill cannot close the slept tabs.
  • The worktree-level park short-circuits the per-tab policy, so the latch works even with terminalHiddenViewParking off — which is exactly the configuration where the eligibility gate would have refused.

Residual risk: the latch is component state, so it is lost on renderer reload; after a restart nothing mounts a hidden workspace anyway, so this is not a re-wake path. Stale ids for deleted worktrees are never pruned from the set — inert (membership is only tested against live surfaces) and bounded by worktree count. As before this PR, a worktree-level park bypasses terminalSshViewParking; for a slept SSH workspace there is no scrollback to lose, since sleep already captured buffers into buffersByLeafId.

AI Disclosure

Investigated and implemented with Claude Opus 4.6 in Claude Code.

Review

Reviewed against readiness-checklist (two passes). The first pass caught a real defect in the first draft of this fix: the latch was only released on reveal, so a mobile/CLI background wake would have re-parked the panes ~3s later, once the measure window closed. That is the BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT release above, with a test. Second pass: no candidate findings.

Reviewer questions worth a second opinion:

  1. Should the latch survive a renderer reload (persisted), or is in-memory correct?
  2. Is releasing the latch on any background mount too broad — should a mobile wake of an explicitly-slept workspace stay parked instead?

…mselves

Sleep kills a workspace's PTYs but leaves it in the terminal workbench's
mounted set, which is only pruned when a worktree is deleted. Its panes then
cold-park like any hidden workspace, and when the park verdict flips back they
remount, reattach to the preserved session ids, miss, and fall through to a
fresh cold-restore spawn that re-runs the agent's --resume. The row un-sleeps
minutes later with no user action.

Sleeping now latches the on-demand park, which holds until the workspace is
revealed or background-woken. The on-demand eligibility gates are skipped for
that reason: a workspace with no surviving PTY can never satisfy them, and
refusing would leave it mounted and re-spawnable.
@coderabbitai

coderabbitai Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: bfa79223-e184-423c-a54f-69608780af95

📥 Commits

Reviewing files that changed from the base of the PR and between 2ecde71 and e2a3979.

📒 Files selected for processing (7)
  • src/renderer/src/components/sidebar/sleep-worktree-activation-race.test.ts
  • 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/terminal-worktree-sleep-park-latch.test.tsx
  • src/renderer/src/components/terminal-pane/use-manual-terminal-worktree-parking.ts
  • src/renderer/src/lib/manual-terminal-worktree-parking.test.ts
  • src/renderer/src/lib/manual-terminal-worktree-parking.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The change adds reason-aware manual terminal worktree parking. Workspace sleep requests parking with the workspace-sleep reason after terminal shutdown and host suspension succeed. The parking hook bypasses normal eligibility checks for this reason, preserves queued reasons, and releases parked worktrees after reveal or background terminal mounting. Tests cover event details, sleep-flow ordering, failure handling, eligibility, and release behavior.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to e2a39

The workspace sleep parking changes have no supported unresolved merge-blocking risk.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 7 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 describes the primary change: keeping slept workspaces parked to prevent unintended reactivation.
Description check ✅ Passed The description is detailed and covers the change, rationale, linked issue, visual proof, testing, AI disclosure, review, and residual risks. Some template items are not explicit, such as the Agent sk…
Linked Issues check ✅ Passed Issue #10205 requires slept workspaces to remain inactive until deliberate opening or an intended wake path. The sleep flow requests a workspace-sleep park only after terminal and host teardown succ…
Out of Scope Changes check ✅ Passed The changes stay within issue #10205. The park-reason type, pending-request propagation, sleep-flow integration, wake release, and related tests all support prevention of unintended workspace revival.…
  • 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.

@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

  • Park reason plumbing — requestManualTerminalWorktreePark and the pending queue now carry a 'manual' | 'workspace-sleep' reason end-to-end, with takePending/takeAll returning the reason instead of a bare boolean/string list.
  • Sleep latch — runSleepWorktrees parks the workspace ('workspace-sleep') only after the final teardown step succeeds, so a partially-slept workspace never earns the latch.
  • Gate bypass — useManualTerminalWorktreeParking skips the on-demand eligibility gates for the sleep reason (a dead-PTY workspace can never pass them) while preserving the gates and toast for manual parks.
  • Latch release — released on reveal (existing effect) and on BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT.
  • Tests — a new 4-case latch test plus extended sleep-flow tests covering latch ordering and the no-park-on-failure parameterization.

ℹ️ On the two reviewer questions

1. Should the latch survive a renderer reload? In-memory is correct. After a reload nothing auto-mounts a hidden workspace, so there is no re-wake path to defend against; persisting would add a storage/schema surface for no benefit.

2. Is releasing on any background mount too broad? No, for the cases that matter. Every requestBackgroundTerminalWorktreeMount caller is a genuine "this worktree's terminals are needed" signal (mobile wake, agent launch, CLI reveal, browser-automation bootstrap). The residual per-worktree-vs-per-tab granularity — a single-tab mount releases the whole worktree's latch — is already scoped by the pre-existing restoreOnTabOpenOnly filtering in wake-sleeping-agents-in-background.ts, which keeps a phone tap from respawning an explicitly-slept workspace's finished agents. The one case that does release the latch (a phone resuming a still-working agent of a slept workspace) is the intended behavior, since that agent should wake. No change required; the current design holds.

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

@nwparker

Copy link
Copy Markdown
Contributor Author

Superseded by #18051 (and its design source #13343 by @mmarabel). Converting to draft rather than closing, so it isn't lost if those stall.

I opened this before finding the two existing PRs for the same bug. Having reviewed both, #18051 fixes it at the better seam and I'd rather help land that than compete with it.

Why theirs wins. I gated the remount (latch the on-demand terminal park on sleep, so the panes never come back). @Jinwoo-H gates the connect. Verifying my own change, I found the park gate leaks where theirs doesn't — candidateParkedTerminalTabIds in use-terminal-tab-cold-parking.ts refuses to park a tab that has hasActivityTerminalPortal, is in terminalPaneSplitMountLeaseTabIds, or any tab while shouldMeasureHiddenWorktree is set. Each is a remount path my latch can't stop, including remountTerminalTabForRecovery, which their e2e drives directly. They also handle the batch-sleep cases I missed entirely: per-workspace marking inside the loop, a teardown window so a spawn resolving mid-sleep can't un-sleep the workspace, and releasing a workspace the user activated mid-batch.

What I'm contributing instead, posted on #18051:

  • Field evidence for a third trigger that does reproduce, which neither PR had — a background unpark sweep, three self-wakes after three sleeps in one evening on a packaged build, with daemon logs.
  • Verified analysis of the park-path gaps above, as independent confirmation their seam is the right one.
  • Three review notes: the !session.paneStartup exemption and whether a stale queued startup can reach it; clear-on-bind being workspace-wide, so one CLI tab bind resumes every waiting pane; and that their red CI is a stale localization catalog from a Sep 2 branch, not their change.

No code taken from either PR, so no co-authorship is owed here — the credit that matters is on those PRs.

Possibly still worth salvaging, separately from this bug: sleep's stated purpose in sleep-worktree-flow.ts is "close all panels to free memory / CPU", but neither fix unmounts the panes — #18051 leaves xterm instances and WebGL renderers mounted behind dead PTYs. Parking a slept workspace reclaims that. If a maintainer wants it, it's a small follow-up on top of #18051, not a competing fix, and it should not block this bug.

@nwparker

Copy link
Copy Markdown
Contributor Author

Closing in favour of #20075, which is @Jinwoo-H's #18051 rebased onto current main and verified (their regression test still fails on main, passes there). My park-latch approach is not being merged — the connect-entry gate covers remount paths the park gate cannot. Field evidence and review notes from here are carried into #20075.

@nwparker nwparker closed this Sep 11, 2026
@nwparker
nwparker deleted the nwparker/sleep-branch-keeps-unsleeping branch September 11, 2026 08:30
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)

1 participant