Skip to content

fix(sidebar): stop workspace delete from waking a sleeping sibling - #14705

Open
jeongph wants to merge 3 commits into
stablyai:mainfrom
jeongph:fix/worktree-delete-wakes-sleeping-workspace
Open

jeongph wants to merge 3 commits into
stablyai:mainfrom
jeongph:fix/worktree-delete-wakes-sleeping-workspace

Conversation

@jeongph

@jeongph jeongph commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

ELI5

When you delete the workspace you're looking at, Orca moves you to another workspace in the same project so you don't end up staring at nothing. It just wasn't checking whether that other workspace was asleep. So if you'd put everything else to sleep, deleting your last awake workspace would drag a sleeping one back to life — new terminal, agent session resumed, none of it asked for. Now Orca only hands focus to a workspace that's already awake, and if they're all asleep it leaves the selection empty instead of waking one.

What Changed

pickNextWorktreeIdAfterDelete in src/renderer/src/components/sidebar/active-worktree-focus-after-delete.ts already excluded siblings that were mid-delete or hosted on a torn-down runtime-owned SSH target. It now also excludes siblings that are asleep, via the existing isInactiveWorkspace helper.

That helper is the same predicate the sidebar uses to decide whether a workspace renders as sleeping, so the focus logic and the sleeping indicator can't disagree. A workspace counts as awake if it has a live PTY, a browser tab, or a live agent — the last one matters because an SSH reconnect drops the PTY while the agent keeps running (#7197), and treating that as asleep would skip a workspace that's genuinely alive.

When no sibling qualifies, the function returns null and focus stays empty. That is not a new UI state: sleeping the focused workspace already leaves activeWorktreeId null via setActiveWorktree(null) in sleep-worktree-flow.ts.

Why

Steps to reproduce on main:

  1. Create two or more worktrees in a project.
  2. Sleep all of them except one.
  3. In the remaining awake worktree, right-click → Delete.
  4. A sleeping worktree wakes up and opens a terminal.

runWorktreeDeleteWithToast calls prepareActiveWorktreeFocusAfterDelete, whose committer runs activateAndRevealWorktree(nextWorktreeId) on the chosen successor. That call does two things to a slept workspace:

  • resumeSleepingAgentSessionsForWorktree (worktree-activation.ts:339) relaunches the persisted CLI agent sessions
  • ensureWorktreeHasInitialTerminal (worktree-activation.ts:342) brings the tab back and reconnects its PTY

The picked workspace looks arbitrary to the user because the ranking is lastVisitedAtByWorktreeId (most-recently-focused first), and sleeping a workspace does not restamp that value.

Only awake siblings can be safely activated, because activating an awake one is a no-op with respect to process lifecycle — that's the invariant this restores.

Linked Issue

Refs #10205

Not Fixes — #10205 is an umbrella report for "sleeping workspaces revive without user activation" and lists two other triggers (sleeping the focused workspace cascades into another wake; answering an agent question). Those are separate code paths and are untouched here, so this PR should not close it. The delete path is a third trigger that was not in that report, and unlike the other two it reproduces deterministically.

Happy to split a dedicated issue out for this trigger if maintainers prefer one PR ↔ one issue.

Visual Proof

No before/after capture attached. The change has no static visual difference — the observable delta is a terminal that no longer spontaneously appears, which a screenshot pair can't show honestly. The behavioral difference is covered by the repro steps above and by the tests below.

Before: after step 3, a sleeping worktree becomes selected and its terminal spawns.
After: after step 3, the terminal view is left with nothing selected and every slept worktree stays slept.

Testing

src/renderer/src/components/sidebar/active-worktree-focus-after-delete.test.ts — three tests added, written before the fix and confirmed red against it:

Test Before fix
leaves focus empty rather than waking a sleeping sibling ❌ activated wt-slept (the reported bug)
prefers an awake sibling over a more-recently-visited sleeping one ❌ activated wt-slept
keeps a sibling whose agent is live across a PTY gap eligible guard for the #7197 carve-out

The third test is a regression guard rather than a red-first test, so I verified it earns its place by mutation: replacing the live-agent set with an empty one makes it fail while the other 14 stay green.

The file's seed() helper previously modeled no tabs or PTYs at all, which left every seeded worktree "asleep" under the new predicate. It now seeds a live PTY by default and takes an explicit asleep: true. Each pre-existing test keeps its original assertion and subject (MRU ordering, base-worktree fallback, SSH exclusion, focus-stealing guards).

Verification run locally on macOS:

  • pnpm lint — pass

  • pnpm typecheck (node + cli + web) — pass

  • pnpm test — 51,647 passed. Four failures, all unrelated to this change: src/relay/agent-exec-handler.test.ts (2) fails identically on a clean main with this branch stashed; src/main/updater.test.ts and src/main/runtime/rpc/terminal-output-frame-chunks-equivalence.test.ts are load-induced timing assertions that pass in isolation.

  • Targeted: the sidebar + status-bar suites (2,401 tests) cover five of the six modules that import this one.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

The manual box is deliberately unchecked. This was verified through unit tests that encode the reported flow, not by driving the built app. A reviewer running the four repro steps above would be the missing confirmation.

AI Disclosure

Written with Claude Code (Claude Opus 5). Root cause, fix, and tests were reviewed by the author.

Review

Security — no new I/O, IPC, process spawning, or user input handling. The change only removes candidates from an in-memory selection list, so it can never broaden what gets activated.

Cross-platform — pure renderer state logic, no paths, shell strings, keyboard modifiers, or platform branches. Identical on macOS, Linux, and Windows.

Remote / SSH — the live-agent term keeps SSH workspaces eligible while a reconnect leaves their PTY gap, which is why isInactiveWorkspace was chosen over the narrower hasSleepableWorkspaceActivity. The pre-existing runtime-owned-SSH-target exclusion is untouched and still runs first.

Folder workspaces — unaffected. This path keys off worktreesByRepo[repoId], and prepareActiveWorktreeFocusAfterDelete already resolves repoId to null for a folder workspace, so it never reaches the picker.

Backwards compatibility — no persisted state, schema, or wire format touched. Nothing crosses the client/host boundary.

Performance — adds one getWorktreeIdsWithLiveAgent pass per delete commit, over the agent-status map. It runs once per delete, not per render; the sidebar already computes the same set every render.

Failure mode — if a client's ptyIdsByTabId under-reports liveness for a genuinely awake workspace, the result is a skipped auto-focus, not a spurious wake. The change can only ever activate fewer workspaces than before, never more.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test pass locally (pnpm build not run; no build-surface change)

@coderabbitai

coderabbitai Bot commented Aug 15, 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: c1694eb9-7212-4128-a3d2-078478340255

📥 Commits

Reviewing files that changed from the base of the PR and between 3631f88 and 2da7bdd.

📒 Files selected for processing (2)
  • src/renderer/src/components/sidebar/active-worktree-focus-after-delete.test.ts
  • src/renderer/src/components/sidebar/active-worktree-focus-after-delete.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/components/sidebar/active-worktree-focus-after-delete.ts
  • src/renderer/src/components/sidebar/active-worktree-focus-after-delete.test.ts

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


📝 Walkthrough

Walkthrough

Post-delete worktree selection excludes inactive or sleeping sibling worktrees. Worktrees with live agents remain eligible without PTYs. Tests expand mocked tab, PTY, browser-tab, and agent-status state. New cases verify awake sibling preference and no replacement when no eligible sibling exists.

Merge Risk: ⚪ Minimal · up to 2da7b

Deleting an active workspace now avoids selecting sleeping siblings while retaining eligible awake or live-agent workspaces. No current merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 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: preventing deletion from waking a sleeping sibling workspace.
Description check ✅ Passed The description is detailed and mostly complete. It explains the problem, implementation, tests, limitations, issue reference, and platform considerations. The linked issue uses “Refs #10205” instead …
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI

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.

🧹 Nitpick comments (1)
src/renderer/src/components/sidebar/active-worktree-focus-after-delete.ts (1)

40-45: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense the sleep-state comments.

  • src/renderer/src/components/sidebar/active-worktree-focus-after-delete.ts#L40-L45: Replace the six-line comment with one concise rationale for excluding inactive siblings.
  • src/renderer/src/components/sidebar/active-worktree-focus-after-delete.test.ts#L157-L159: Remove the repeated explanation. The test name and production comment identify the behavior.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ba18cd76-1d33-4c58-9856-83d1abacf731

📥 Commits

Reviewing files that changed from the base of the PR and between a275f5a and 98b329a706ebd069ce92260efd41ced0a8cc071e.

📒 Files selected for processing (2)
  • src/renderer/src/components/sidebar/active-worktree-focus-after-delete.test.ts
  • src/renderer/src/components/sidebar/active-worktree-focus-after-delete.ts

@mmarabel

Copy link
Copy Markdown
Contributor

Confirming this repro on main, with both workspaces on an Orca remote host — a paired orca environment (a runtime: execution host), not an SSH workspace. So the trigger is neither local-only nor specific to the SSH path.

Hit in normal use rather than reconstructed: two workspaces in one project, slept one, then deleted the remaining awake one. The slept workspace was immediately activated and spawned a fresh PTY on the remote host.

Sequence, from a screen recording:

t State
0:36 Project group shows one child, the workspace about to be deleted. The slept sibling is already hidden.
0:43 Right-click that workspace → Delete.
0:45 The slept sibling is back in the group, and selected.
0:47 Two terminal tabs, with a fresh shell prompt in the revived workspace's directory.

Two details that may be useful for the fix:

The predicate already agreed. Immediately before the delete, the sidebar had already hidden the slept sibling — using isInactiveWorkspace, the same predicate this PR adds to the picker. So the sidebar and pickNextWorktreeIdAfterDelete classify this case identically; the picker just wasn't asking. That seems like a point in favour of reusing the helper rather than introducing a second notion of "asleep".

The existing carve-out never applied here. isHostedOnRuntimeOwnedSshTarget matches ssh: host ids and runtime-owned SSH targets (runtime-ssh- prefix). A plain runtime:<environmentId> host parses to kind: 'runtime' and doesn't match, so these siblings were never excluded by it. On an Orca remote host the new isInactiveWorkspace term is the only thing preventing the wake.

This is the manual confirmation the PR description flags as missing. I have redacted screenshots of the four moments above and can attach them if useful.

Repro captured and analysed with Claude Code.

@greptile-apps

greptile-apps Bot commented Sep 3, 2026

Copy link
Copy Markdown

Too many files changed for review (3000 files, 100 file limit).

@Jinwoo-H

Jinwoo-H commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Rebased onto current main (merge commit) and pushed one follow-up: main's delete fallback now activates with { revealInSidebar: false }, so the two new positive assertions needed that second argument. 15/15 pass on the merged tree, changed-code quality gate clean. Workflow runs approved.

Independent trace confirms the fix: every writer of the active selection after a delete goes through focusNextWorktreeAfterActiveDelete, which only activates a truthy id, and the store purge nulls the selection without repicking. Two accepted consequences: a sleeping base workspace is no longer a fallback (selection stays empty), and a never-opened workspace with no tabs is skipped. Both fail toward not spawning processes.

@Jinwoo-H
Jinwoo-H force-pushed the fix/worktree-delete-wakes-sleeping-workspace branch from d094b25 to a5f0485 Compare September 3, 2026 17:50
@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 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Re-pushed as a linear rebase on current main (the earlier merge commit made the PR's classify step diff 13k files and hit an EAGAIN reading stdin). Same two source commits plus one test-only follow-up for the { revealInSidebar: false } argument main now passes. PR Checks and PR test LoC are green on 0dcc761.

jeongph and others added 3 commits September 7, 2026 00:46
Deleting the active workspace hands focus to a surviving sibling so the
delete behaves like closing a tab. The successor filter skipped worktrees
that were mid-delete or hosted on a torn-down runtime-owned SSH target,
but never checked whether the candidate was asleep.

Activating a slept workspace respawns its PTYs and resumes its agent
sessions, so with every sibling slept the delete revived whichever one
was visited last -- an unattended wake the user never asked for, and one
more trigger for the revive-without-activation class in stablyai#10205.

Require candidates to be awake, reusing isInactiveWorkspace so the focus
logic and the sidebar's sleeping indicator read the same signal. A
workspace whose agent is live across a PTY gap (SSH reconnect, stablyai#7197)
still counts as awake. When every survivor is asleep the selection stays
empty, matching the state left behind by sleeping the focused workspace.
The successor-filter rationale restated behavior the code already shows, and the test repeated it verbatim.
@jeongph
jeongph force-pushed the fix/worktree-delete-wakes-sleeping-workspace branch from 0dcc761 to 2da7bdd Compare September 6, 2026 16:00
@coderabbitai

coderabbitai Bot commented Sep 6, 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.

@mmarabel

Copy link
Copy Markdown
Contributor

Three small updates on this one, all mechanical — no change requested to the diff.

1. There is now a dedicated issue: #21940. When this PR was opened it could only say Refs #10205, because #10205 was an umbrella. That umbrella was closed as completed on 2026-09-11 by #20075, which leaves this trigger with a PR and no issue. #21940 reports it on its own, with the deterministic repro run through the Hide sleeping filter (sleep every sibling, delete the last visible one, a hidden row comes back awake). This PR can carry Fixes #21940.

2. #20075 does not overlap this fix. Its sleep-intent marker keeps a slept workspace's panes cold, but the delete handoff reaches the successor through activation, and activation is an explicit wake by construction — setActiveWorktree calls clearWorktreeSleepIntent ("any activation is an explicit wake") before resumeSleepingAgentSessionsForWorktree and ensureWorktreeHasInitialTerminal run. So the gate that fixed the sleep-cascade trigger cannot fix this one.

Re-verified today: pickNextWorktreeIdAfterDelete still filters only isDeleting and isHostedOnRuntimeOwnedSshTarget at v1.4.205, at v1.4.206, and on main at 7e2ebac318.

It also strengthens the argument in the PR description that an empty selection is not a new UI state: with #20075 in, sleeping the focused workspace leaves the selection empty and nothing takes its place, so after this PR the two paths agree.

3. Checks have never run on the current head. 2da7bdd6 reports total_count: 0 check runs and an empty statusCheckRollup, which is why mergeStateStatus is UNSTABLE — not red CI, but CI that never started. @Jinwoo-H, your run approval covered 0dcc761; the test-only re-push after it needs a fresh one. Happy to re-run the repro and report back once checks are green.

This branch has not been deployed

No deployments
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.

6 participants