Skip to content

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

Closed
Jinwoo-H wants to merge 5 commits into
mainfrom
sep01-terminal-notification-wake-audit
Closed

Jinwoo-H wants to merge 5 commits into
mainfrom
sep01-terminal-notification-wake-audit

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 2, 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

ELI5

Putting a workspace to sleep must keep it asleep until you open it. Before this fix, anything that re-mounted one of its terminal panes behind the scenes brought the shell back.

Scope, stated plainly: this closes the mechanism, not a reproduced user journey. The two field triggers reported in #10205 (sleeping the focused workspace revives a background-slept one; clicking an agent row or answering an agent question) do not reproduce on current origin/main: I drove both through the sidebar against identical builds of main and this branch, and both stayed cold on main with zero connect attempts. The mechanism is still real and deterministic: any remount of a slept pane reattaches its retained dead session id and the daemon spawns a fresh shell. The e2e proves that by calling the shipping remount entry point directly.

What changed

  • The existing 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 the marker 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 (resolved by either tab id form through one shared live lookup), 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 after its generation bump, setActiveFolderWorkspace), on any PTY binding to one of the workspace's tabs (updateTabPtyId, createTab with an initial PTY, which covers CLI, automation, and client wakes), and forgotten without waking anything on purge (removeWorktree, buildWorktreePurgeState).
  • The sleep flow marks each workspace when its own teardown starts and re-asserts the marker after teardown, so a spawn that resolves mid-sleep cannot un-sleep it; a workspace the user activated during a batch sleep is released instead. Failed sleeps release the marker for the failed workspace only.

Why

The community root cause in #13343 by @gatsby74 is right: the wake is the renderer pane-connect path. This PR lands that design with the gate moved to the connect entry, so it covers both connect arms, and with clear-on-bind so non-activation wakes never leave a workspace stuck cold.

Linked issue

Fixes #10205 (STA-2449). Related: #13343 (source of the design, co-authored), #14705 (delete-focus fallback).

Testing

  • New e2e tests/e2e/slept-workspace-remount-wake.spec.ts: sleeps a workspace via the sidebar, activates another, forces a pane remount through remountTerminalTabForRecovery (the production entry point used by terminal pane recovery: undeliverable or host-rejected input, stalled write pipeline, replay-guard wedge, the Retry button on the pane-owner-unverified toast; the direct-SSH retry chain and all-dead activation bump the tab generation the same way), and asserts zero live PTYs, zero host sessions, and no tab growth over 8s, then proves a deliberate click still wakes it. Fails on origin/main (live PTY 1, host session 1, verdict REATTACH), passes here (verdict WAIT FOR WAKE (deliberate sleep), asserted).
  • New unit suites: connect gate (reattach arm, fresh-spawn arm, resume on wake, no resume for a remounted generation, listener dropped on dispose, queued startup still connects) and marker lifecycle (activation, null selection, folder activation, PTY bind, tab created with a PTY, listener semantics, purge forgets without waking).
  • Local probe: a deliberate wake of a waiting pane produces exactly one connect and one host session.
  • Existing terminal-sleep-wake-restore, terminal-attention, terminal-cold-activation-deferral, local-cli-terminal-retention e2e pass locally.
  • Full renderer unit suites (14.7k tests), pnpm tc, check:code-quality:changed pass.
  • Four adversarial review rounds; every finding fixed with a regression test.
  • Not reproduced: [Bug]: Sleeping workspaces revive without user activation — hard to diagnose (open question on opt-in lifecycle logging) #10205 Trigger A (focused-workspace sleep cascade, both slept-in-background and slept-while-focused variants) and Trigger B (agent-row activation) pass on current origin/main. Those reports are from July builds.

Compatibility and boundaries

  • No persisted or wire changes; the marker is renderer memory only. Restart cold state is already modelled by activeWorktreeIdsOnShutdown, which excludes slept worktrees.
  • Folder workspaces use the same key for mark and clear. SSH and paired-runtime panes go through the same connect entry.

AI disclosure

Implementation, reproduction, and review were AI-assisted; verification was run locally.

@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 977058f8-bd30-497a-b923-7b1f6cc79502

📥 Commits

Reviewing files that changed from the base of the PR and between a35451f and 667d230.

📒 Files selected for processing (13)
  • 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/run-deferred-connect.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
  • tests/e2e/helpers/slept-workspace-probe.ts
  • tests/e2e/slept-workspace-remount-wake.spec.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/renderer/src/components/sidebar/sleep-worktree-flow.test.ts
  • src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts
  • src/renderer/src/store/slices/worktrees/session/set-active-folder-workspace.ts
  • src/renderer/src/components/sidebar/sleep-worktree-flow.ts

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


📝 Walkthrough

Walkthrough

The change keeps sleep intent marked for successfully slept worktrees and marks background worktrees before teardown. Deferred PTY connections now suppress reattachment and fresh spawning for deliberately slept panes unless explicit startup exists. Activation, PTY binding, removal, and purge clear sleep intent. New unit and end-to-end tests validate intent lifecycle, cold remount behavior, and deliberate wake.

Merge Risk: ⚪ Minimal · up to 667d2

The deliberate-sleep lifecycle changes have no identified merge-blocking risk.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.52% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 25 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address issue #10205 by preserving sleep intent, blocking unintended PTY reattachment and fresh spawning, releasing the marker on explicit wake paths, and adding focused unit and E2E cover…
Out of Scope Changes check ✅ Passed The implementation, lifecycle updates, helper utilities, and tests are all related to keeping deliberately slept workspaces cold and releasing sleep intent at valid wake or removal boundaries.
Title check ✅ Passed The title clearly and concisely describes the primary change: deliberately slept workspaces remain cold until explicitly woken.
Description check ✅ Passed The description is detailed and covers the problem, implementation, rationale, linked issue, testing, compatibility, and AI disclosure. It omits the required Visual Proof section and several checklist…
Full details: Linked Issues check

Explanation

The changes address issue #10205 by preserving sleep intent, blocking unintended PTY reattachment and fresh spawning, releasing the marker on explicit wake paths, and adding focused unit and E2E coverage. The issue’s diagnostic-logging discussion is an open question and is explicitly outside this PR’s stated scope.

Full details: Description check

Explanation

The description is detailed and covers the problem, implementation, rationale, linked issue, testing, compatibility, and AI disclosure. It omits the required Visual Proof section and several checklist sections, but it is otherwise substantially complete and directly related to the changes.

  • 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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: c791f003-c016-4e47-855e-69738b65905e

📥 Commits

Reviewing files that changed from the base of the PR and between fdfe354 and bbe8f96.

📒 Files selected for processing (13)
  • 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-fresh-spawn-guards.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts
  • src/renderer/src/components/terminal-pane/pty-connection/deliberate-sleep-cold-start.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/deliberate-sleep-cold-start.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.test.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.ts
  • src/renderer/src/lib/worktree-activation-emptied-workspace-reseed.test.ts
  • src/renderer/src/lib/worktree-activation.ts
  • src/renderer/src/lib/worktree-sleep-intent.ts
  • src/renderer/src/store/slices/store-session-workspace-hydration.test.ts
  • src/renderer/src/store/slices/tabs-unread-and-focus.test.ts

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

@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.

Important

The fix is sound and well-tested for the sidebar/wake paths, but the sleep marker's lifecycle has a gap: it is only released from four call sites, while many production activation paths call setActiveWorktree directly. Waking a slept workspace through one of those paths leaves the marker set indefinitely and silently suppresses bumpWorktreeActivity for an otherwise-live workspace.

Reviewed changes

  • Persistent sleep marker — worktree-sleep-intent.ts now retains the per-worktree marker across a successful sleep (previously cleared in finally), and sleep-worktree-flow.ts marks every target before teardown while clearing only failed worktrees.
  • Cold-start guard — new shouldStayColdForDeliberateSleep in deferred-session-reattach-choice.ts suppresses the fresh spawn for a hidden, inactive, deliberately-slept pane; queued startups, visible panes, and the active worktree bypass it.
  • Explicit wake clearing — worktree-activation.ts clears the marker on worktree and folder activation; wake-sleeping-agents-in-background.ts clears it even for record-less (plain shell) workspaces.
  • Tests — cold-start guard unit tests, fresh-spawn guards, background-wake release, restart hydration, and repeated-activation coverage.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@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. The prior activity-suppression leak is now closed at the shared activation boundary.

Reviewed changes

  • Centralized marker release — clearWorktreeSleepIntent now lives inside the non-null setActiveWorktree boundary (set-active-worktree.ts:45) and the shared setActiveFolderWorkspace boundary, so every direct activation caller (terminal-handle-links, launch-dashboard-agent, http-link-routing, file-preview, activity-thread-actions, restored-editor-owner, terminal-command-state, web-runtime selection) releases the marker.
  • Removed redundant per-helper clears — activateAndRevealWorktree / activateAndRevealFolderWorkspace dropped their explicit clears, now covered by the store boundary.
  • Null preserved — setActiveWorktree(null) skips the clear, keeping the marker through sleep teardown and workspace close.
  • Regression coverage — store-level tests for release-at-boundary and null-preservation, plus strengthened restart-hydration layout and repeated-activation identity assertions.

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

@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

  • Scoped typecheck cache to the commit — the typecheck job's TypeScript incremental-state cache is now keyed on ${{ github.sha }} with no restore-keys, so a fresh commit no longer restores a stale .tsbuildinfo graph from an earlier commit on the same PR. The comment now explains the rationale (shared graphs across commits can retain stale symbol tables and emit diagnostics for declarations that exist on disk).

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

@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

  • TypeScript cache contract test — config/scripts/pr-workflow-parallelism.test.mjs now asserts the commit-scoped cache (key contains github.sha, restore-keys is undefined), matching the workflow change from the prior commit.

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

…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 <[email protected]>
@Jinwoo-H
Jinwoo-H force-pushed the sep01-terminal-notification-wake-audit branch from 3e51e73 to 667d230 Compare September 3, 2026 20:46
@coderabbitai

coderabbitai Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@Jinwoo-H Jinwoo-H changed the title fix(terminal): keep deliberately slept workspaces cold fix(terminal): keep a deliberately slept workspace cold until it is woken Sep 3, 2026

@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.

Reviewed changes

This run reviewed the squashed rewrite that consolidates the sleep-intent handling into a single connect-entry gate and a bind-driven clear.

  • Moved the cold-start gate to the connect entry — run-deferred-connect.ts now checks hasWorktreeSleepIntent immediately before safeFit, so a deliberately slept pane skips both the reattach arm (its retained dead session id) and the fresh-spawn arm; a queued startup (session.paneStartup) still connects.
  • Clear-on-bind replaces several helper clears — updateTabPtyId (terminal-pty-bindings.ts) releases the marker on any PTY bind; the setActiveWorktree / setActiveFolderWorkspace boundary clears remain.
  • Purge/remove clears — removeWorktree and buildWorktreePurgeState release the marker so a recreated worktree at the same path does not inherit a stale sleep.
  • Dropped wakeSleepingAgentsForWorktreeInBackground / worktree-activation clear sites — the paired-client wake now relies on PTY bind to release the marker.
  • Reworked tests — a connect-guard unit suite (reattach, fresh-spawn, queued startup, released marker), a store lifecycle suite, and an e2e slept-workspace-remount-wake.spec.ts with explicit non-vacuity assertions.

⚠️ Record-less client wakes no longer release the sleep marker

The description claims clear-on-bind "covers CLI, automation, and client wakes," but wakeSleepingAgentsForWorktreeInBackground no longer clears the marker and only produces a PTY bind when the workspace actually carries sleeping-agent records. Opening a manually-slept workspace that has no agent records (a plain shell) through a paired mobile/remote client runs activateManagedWorktree in the main process and never drives the renderer's setActiveWorktree nor binds a PTY, so the marker stays set and the desktop workspace remains cold. This diverges from the prior revision, which explicitly cleared the marker on that path.

The practical blast radius is narrow: the desktop user can still recover by clicking the workspace (activation clears the marker and the allDead branch remounts the dead panes), and a client-issued create with activate: true or a queued command still clears. But since this is exactly the wake route this PR's clear sites are meant to cover, it is worth confirming whether record-less wakes are expected to clear before merging.

Technical details
# Record-less client-wake marker release

## Affected sites
- `src/renderer/src/lib/wake-sleeping-agents-in-background.ts:167-176` — the `worktreeRecords.length === 0` early return now leaves the marker set; no `clearWorktreeSleepIntent` call remains in this module after the rewrite.
- `src/renderer/src/store/terminals/terminal-pty-bindings.ts:124-125` — the replacement clear-on-bind only fires on an actual PTY bind, which the record-less wake never produces.

## Required outcome
- Decide whether a paired client opening a manually-slept, agentless workspace should wake it. If yes, restore a `clearWorktreeSleepIntent(worktreeId)` on that wake path (before the early return), and add a lifecycle test for the record-less case. If no, state that record-less wakes are intentionally cold and nullify this section.

## Open questions for the human (optional)
- Is `resumeSleepingAgents`/`activateManagedWorktree` expected to wake agentless workspaces at all, or is it scoped to sleeping-agent records only?

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

… 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.

@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

  • Replaced the latch-cold gate with a wait-for-wake subscription — run-deferred-connect.ts now cancels the slept pane's scheduled connect and registers an onWorktreeSleepIntentCleared listener that re-enters runDeferredConnect on wake, so a remounted pane resumes its own connect instead of depending on a generation-bump remount.
  • Split marker release into clear vs forget — worktree-sleep-intent.ts gains forgetWorktreeSleepIntent (drops marker + listeners without notifying), and remove-worktree.ts / worktree-purge-state.ts now use it so panes being unmounted are never woken by a purge.
  • Clear-on-initialPtyId — terminal-tab-creation.ts releases the marker when a tab is born with a live PTY (CLI/runtime create), closing the bind-less client-create wake route.
  • Moved the PTY-bind clear out of the store updater — terminal-pty-bindings.ts now clears after set() (required once clear fires listeners that call back into the store), and the sleep flow marks each target per-worktree so a slow earlier teardown no longer holds later still-awake workspaces cold.
  • Extended tests — wake-resume, disposed-pane unsubscription, per-worktree marking, and the WAIT FOR WAKE e2e verdict all assert the new behavior non-vacuously.

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

@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

  • Generation guard on the wake resume — the onWorktreeSleepIntentCleared callback in run-deferred-connect.ts now re-reads the live tab and connects only when (currentTab?.generation ?? 0) === session.tabGeneration, mirroring the existing fresh-spawn-start.ts idiom, so a stale session no longer double-connects alongside the remounted pane.
  • Clear after the store commit — setActiveWorktree now calls clearWorktreeSleepIntent after its set(), so the activation generation bump is committed before the wake listeners fire and a waiting pane connects exactly once, in its remounted generation.
  • Regression test — pty-connection-deliberate-sleep-guard.test.ts gains does not connect a waiting pane whose tab was remounted by the wake, asserting non-connect after a clear plus generation bump.

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

… 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.

@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

This run reviewed the delta that resolves a waiting pane's tab by either id form, re-arms the wake wait, and re-asserts the marker after teardown.

  • Shared tab resolution — findTerminalTabForPane now lives in terminal-tab-id.ts, replacing the duplicated inline lookups that connect-pane-pty.ts (initial tabGeneration) and fresh-spawn-start.ts (shouldContinue) each carried, and the wake callback in run-deferred-connect.ts resolves the live tab through the same helper by unified or terminal id.
  • Wake re-arm — run-deferred-connect.ts resets wakeWaitStarted when the wake fires, so a pane that has already woken can be held again by a later sleep instead of being stranded with no listener.
  • Listener isolation — clearWorktreeSleepIntent wraps each wake listener in try/catch so one pane's connect failure cannot strand its siblings or throw out of a store action.
  • Folder-workspace clear ordering — set-active-folder-workspace.ts clears the marker after its set(), matching the worktree path so a waiting pane wakes against the activated state.
  • Post-teardown re-assert — sleep-worktree-flow.ts re-marks each workspace after suspension (or releases it if the user re-activated it mid-batch), so a PTY that binds during teardown cannot un-sleep a deliberately slept workspace.
  • Regression tests — unified-tab resume, re-arm after wake, post-teardown re-assert, mid-batch activation release, and sibling-listener notification are all asserted non-vacuously.

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

@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

This run reviewed the delta that replaces the post-teardown re-assert with a teardown-window guard.

  • Teardown-window guard — withWorktreeSleepTeardown marks a worktree as tearing down for the duration of its shutdown, and clearWorktreeSleepIntent now ignores any clear (PTY bind) that lands while that flag is set, so a spawn resolving mid-sleep can no longer wake the panes. forgetWorktreeSleepIntent clears the flag too, so a same-path recreation is not tainted.
  • Sleep flow simplification — the shutdown of browsers and terminals (plus the ephemeral-VM suspend) is wrapped in the guard, and the previous else { markWorktreeSleepIntent(worktreeId) } re-assert branch is removed — the loop's initial mark now survives teardown because in-window clears are ignored, while the "activated mid-batch" clear is retained.
  • Exactly-once wake assertion — the e2e now waits 3s after the deliberate wake and asserts one live PTY and one host session, proving the waiting pane and its remounted successor do not both reattach.
  • Sharpened tests — a lifecycle test proves an in-flight PTY bind is ignored during teardown (and honored after), and the disposed-pane test now also asserts the wake listener itself is torn down rather than just that connect is skipped.

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

@nwparker

Copy link
Copy Markdown
Contributor

Cross-review from #20039, which I opened tonight for the same bug before finding this PR. Your approach is better than mine and I'm standing mine down — details below, plus field evidence you didn't have.

Independent field evidence: a third trigger that does reproduce

You noted Trigger A and Trigger B from #10205 don't repro on current main, and scoped this to "the mechanism, not a reproduced user journey." I hit the mechanism in the wild tonight on a packaged build, three times in one evening, and the daemon log names the trigger: a background unpark sweep, not an activation.

Every respawn trails another hidden workspace's pane remounting in the same pass 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)

04:59:16.448  session-attached  instant-switch-worktrees@@918d1f0c
04:59:16.487  session-created   fix-inline-…@@c490b5b6
04:59:16.700  session-created   fix-inline-…@@cc62a5d4

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), irregular 16–28 min gaps matching park-verdict churn, with no sidebar_worktree_activate breadcrumb for that workspace in between. Both panes belong to one split tab, which is why they always spawn as a pair.

So: the mechanism isn't just theoretically reachable, it's the dominant trigger in a long-running session with many workspaces. Worth putting in the PR body — it answers the "is this a real user journey" question your scope note leaves open.

Why your seam beats mine

I fixed this by latching the on-demand terminal park on sleep, so the panes never remount. That works for the trigger above, but I verified it leaks on paths yours catches. In use-terminal-tab-cold-parking.ts, candidateParkedTerminalTabIds refuses to park a tab that has hasActivityTerminalPortal, is in terminalPaneSplitMountLeaseTabIds, or while shouldMeasureHiddenWorktree is set. Each is a remount that a park-based gate can't stop and your connect gate does — including remountTerminalTabForRecovery, which your e2e drives directly.

Gating at the connect entry is the right chokepoint. Two independent attempts converging on "the mechanism is the pane connect" is also worth something.

Review notes

  1. && !session.paneStartup exemption. A queued startup is an explicit launch, agreed — but is a stale one possible? pendingStartupByTabId isn't persisted, so it can only be an in-memory leftover, e.g. a startup queued for a pane whose spawn never consumed it before sleep tore it down. If that's reachable, it's an exemption a slept workspace can carry indefinitely. A test that sleeps a workspace with a queued-but-unconsumed startup would close it either way.

  2. 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 your body ("covers CLI, automation, and client wakes"), and I landed on the same question from the other side (my PR asks whether releasing on any background mount is too broad). Flagging it as the one design decision here that deserves a maintainer's opinion rather than a reviewer's.

  3. CI red is stale-branch noise, not your change. static analysis fails on the localization runtime catalog — the missing keys are components.onboarding.integrations.capabilities.*, unrelated to sleep. A rebase on main plus pnpm run sync:localization-runtime-catalog should clear it. The branch is from Sep 2 and main has moved under it (refactor(rpc): make defineMethod preserve the method name and handler result #20016, refactor(shared): derive WellKnownAgentType from TuiAgent #19645).

  4. withWorktreeSleepTeardown and the per-workspace mark inside the batch loop are both things my version got wrong — I marked once, up front, and only for the active workspace. Your handling of "user activated this one mid-batch → release it" is a case I didn't cover at all.

Credit

The design lineage is #13343 by @mmarabel, refined here. I'm not taking code from either PR — I'm closing my mechanism in favour of this one — but if any of the evidence or the park-path analysis above is useful in the PR body, please fold it in directly, no attribution needed.

cc @mmarabel @gatsby74

@nwparker

Copy link
Copy Markdown
Contributor

Rebased this onto current main as #20075 so it can land — your five commits unmodified, authorship intact, plus a Co-authored-by for @mmarabel on the base commit. The only conflict was an import in set-active-folder-workspace.ts.

Two things worth knowing:

  • Your red CI was never your change. static analysis failed on a stale localization runtime catalog (components.onboarding.integrations.capabilities.*). On current main it regenerates to a no-op.
  • Your regression test still discriminates. perf(terminal): mount only the visible pane on a worktree switch #20034 (mount only the visible pane on a worktree switch") landed since, which could have made it vacuous. I put slept-workspace-remount-wake.spec.tson a cleanorigin/main` checkout: fails there ("host created a session for the slept workspace"), passes on the rebase. The bug is still live on main today.

If you'd rather land it yourself on sep01-terminal-notification-wake-audit, say so and I'll close #20075 — I have no attachment to who merges it, only that it lands. cc @mmarabel @gatsby74

@nwparker

Copy link
Copy Markdown
Contributor

Landed as #20075 — your five commits, rebased onto current main with authorship intact, plus a Co-authored-by for @mmarabel on the base commit. Closing this one only because the rebase is what merged; the fix and every test in it are yours.

For the record: the red CI here was never your change (stale localization catalog), and your regression test still discriminates on today's main — it fails on a clean origin/main checkout and passes on the rebase, even after #20034 changed pane mounting.

Thanks for the thorough work on this one. cc @mmarabel @gatsby74

@nwparker nwparker closed this Sep 11, 2026
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