Skip to content

fix(worktree): stop the PTY gate from permanently wedging workspace removal (#11960) - #12153

Merged
OrcaWin merged 9 commits into
mainfrom
OrcaWin/bug-worktree-permanently-unremovable-failed-to-p
Aug 3, 2026
Merged

OrcaWin merged 9 commits into
mainfrom
OrcaWin/bug-worktree-permanently-unremovable-failed-to-p

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #11960

Summary

A workspace could become permanently unremovable. orca worktree rm failed with
Failed to physically stop every PTY for worktree: …, --force failed identically, and every
retry gave the same result — with no terminal listed and no OS process holding the path.

Root cause is (b) from the issue report: verifyFailedPtysExited conflated "could not verify"
with "still live", and it was structurally guaranteed to never verify.

Destructive removal sweeps PTYs under a 10s deadline. If a stop RPC fails, it re-lists the
provider to check whether that PTY had in fact already exited — but it re-listed on the same
deadline the sweeps had just spent
:

const sessions = await settleBeforeDeadline(
  () => provider.listProcesses({ deadlineMs: deadline }), null, deadline  // ← already ~0ms left
).catch(() => null)
if (!sessions) return false   // "timed out" === "still alive"

settleBeforeDeadline returns the fallback immediately when remaining <= 0, so a sweep that
used most of its budget reached the re-list with nothing left, "timed out" without ever asking
the provider, and reported the PTY as live. The sweep spends that budget on every run, so the
failure is deterministic — which is exactly why retrying never helped.

The reporter's stale registry row (kill RPC returns Session not found) is precisely the case
this verification exists to forgive, and precisely the case it could never reach.

ELI5

Orca refuses to delete a workspace folder until it is sure every terminal inside it is really
dead — otherwise it would delete files out from under a running process.

To be sure, it kills the terminals, then double-checks by asking "is that terminal still in your
list?" The bug: it gave itself a 10-second budget, spent all 10 seconds doing the killing, and
then tried to ask the double-check question with 0 seconds left. The question timed out
instantly — and Orca treated "I didn't get an answer" as "the terminal must still be alive."

So it refused to delete. Every retry did the same thing: spend the budget, fail to ask, refuse.
And the --force escape hatch didn't apply to this check, so the workspace was stuck forever —
even though the terminal had actually been dead the whole time.

The fixes: give the double-check its own time budget instead of leftovers; say "I couldn't
check" instead of "it's alive" when that is what really happened (and name the terminal); and
give the user a real way out — wired to the button that actually means "force", not to the
ordinary Delete button.

What changed

  1. Verification gets its own budget — sized like the sweep's (floored at 2s) rather than
    inheriting its exhausted remainder.
  2. Three distinct verdicts — exited / live / unverifiable. The error names the blocking
    PTY ids and, when verification failed, why.
  3. A reachable escape hatch. allowUnverifiedPtyStop waives the proof, plumbed preload →
    IPC → runtime → RPC (and through the web/mobile client). It is set only by genuine force
    affordances: the dialog's Force Delete branch, the failure toast's Force Delete action, the
    Space panel's force recovery, and the CLI's --force. A new unstopped-pty force-delete
    reason and toast copy make the button appear, so the first attempt fails, offers Force Delete,
    and the retry carries the waiver.
  4. Force also survives a sweep that cannot complete (unresponsive daemon, dropped SSH
    channel), which fails before the gate is even reached — while the non-force path still fails
    fast, since it aborts without deleting anything.

Screenshots

No visual change beyond one new failure-toast message (existing Force Delete button, new copy).

Testing

  • pnpm lint — oxlint, code-quality audits, reliability gates, max-lines ratchet (no
    suppressions added), and all three localization gates pass. verify:skill-bundle-manifest
    reports stale generated skill artifacts; verified identical on origin/main at
    d426e35be
    , so it is pre-existing and unrelated.
  • pnpm typecheck (node + cli + web)
  • pnpm test — 4017 passing across the affected surface. The only failures are pre-existing
    on this Windows box (symlink permissions, /bin/sh spawns, SSH/codex home paths);
    spot-checked src/relay/pty-handler.test.ts at the pre-change commit — same 15 failures.
  • pnpm build
  • Every behavioural fix is mutation-verified — reverting it fails a named test. That
    includes the budget fix, the fixed-grace variant, each verdict, the force bypass at both
    the gate and the sweep, the classifier branch and its ordering, clear-only-on-proven-exit,
    and re-deriving the waiver from force at any of the ten teardown call sites.

AI Review Report

Reviewed by Claude (Opus 5) plus four adversarial sub-agents (correctness, cross-platform,
data-loss safety, test quality) over four rounds, each finding re-verified against the code
before acting. Rounds 1–3 found real defects; round 4 found none in the product code.

Highest-severity findings, all fixed:

  • The waiver was wired to the wrong signal. It aliased force, but the desktop's plain
    Delete button already passes force: true after the ordinary confirmation (to skip the
    dirty-file prompt). That silently disabled the PTY gate on the primary delete path. Fixed with
    a separate field; a mutation-verified guard asserts force-without-waiver keeps the gate strict.
  • Then decoupling it re-created the original dead end: the classifier bailed on force
    before testing the PTY error, so the confirmed Delete hit the gate with no Force Delete button
    anywhere. The PTY case is now decided before the force guard and suppressed by the waiver.
  • --force could not escape a sweep-level failure — the sweeps fail closed before the gate.
  • The web/mobile preload silently dropped the new field, defeating the fix on paired clients.
    TypeScript could not catch it: the field is optional and destructuring a subset is legal.
  • Force with a live verdict unregistered a PTY just proven alive, hiding it from the retry.
  • The forced path returned while sibling sweeps were still inside shutdown(), racing the
    delete against a PTY about to release its handles.
  • A generic deadline sentinel masked the actionable error in the log the user is left with.
  • Both in-flight removal dedupe keys include the new flag, so a forced retry cannot coalesce onto
    the attempt that just failed the gate.

A flaky test was root-caused, not papered over: these tests advanced fake timers before
awaiting the teardown, so a rejection mid-advance was unhandled and vitest attributed it to
whichever test was running. Under the two-shell concurrent repro it went from 7/40 failing to
0/40, with zero unhandled rejections.

Cross-platform, explicitly checked. All SSH-bearing call sites keep connectionId through
the signature change (diffed one-for-one against origin/main), so no SSH removal can sweep the
local provider. The folder-workspace ::workspace:<uuid> guard from #10252 is byte-identical to
main, and folder-workspace removal never sets requirePhysicalStop at all. Absolute-epoch
deadlineMs is correct for both the daemon adapter and the SSH provider. No path-separator,
shell, shortcut or label assumptions. CI runs native smoke jobs on macOS, Ubuntu and Windows
plus a Windows package build.

Known trade-off: a forced removal with a failed stop can take ~20s (10s sweep + up to 10s
verify) instead of failing at ~10s. Checked for an outer timeout this could exceed — the CLI's
runtime-client sets none, and the renderer RPC path allows 60s. The non-force path still fails
fast (measured at 1ms).

Security Audit

  • No new untrusted input, command execution, path construction, auth, or secrets handling.
  • Privilege: the waiver cannot be reached without an explicit user force affordance. Every
    caller was traced — notably the background workspace-cleanup batch (which derives force from
    an unverified git status) and the failed-creation rollback paths pass no waiver, so the gate
    stays strict for all automated removals. Guarded behaviourally at the RPC and store bridges,
    and by a source invariant across all ten teardown call sites.
  • Path-safety guards unchanged and still upstream of every teardown call:
    isDangerousWorktreeRemovalPath, assertWorktreeDoesNotContainRegisteredWorktree,
    canSafelyRemoveOrphanedWorktreeDirectory, assertWorktreeCleanForRemoval,
    assertWorktreeUnlockedForRemoval. PTY ownership matching was not widened.
  • Information disclosure: the error now includes PTY ids, which are internal and embed the
    worktree path the message already contained.
  • DoS: the extra verification window is bounded by the sweep budget and cannot loop.

Notes

I could not reproduce against the reporter's live wedged worktree, so this is diagnosed from the
code path and reproduced in tests. The deterministic 0ms-budget mechanism accounts for every
symptom reported, so I am confident it is the cause, though hypothesis (a) (a genuinely surviving
daemon PTY) is not strictly excluded. If it were (a), Force Delete now provides the escape hatch
either way and the error names the PTY.

Deliberately not in scope, worth follow-ups:

  1. Mobile has no recovery path. It sends force: true without the waiver, so it fails safe —
    but mobile/app/h/[hostId]/index.tsx swallows the error in a bare catch {}, so the row
    silently reappears with no explanation. Surface the error first; add the affordance second.
  2. The forced sweep-failure path returns before rendering a verdict, so it cannot name live
    PTYs when only one sweep failed. Diagnosability only — it is behind an explicit Force Delete,
    deletes either way, and clears no registry rows. Recorded at the return site.
  3. The reporter also saw orca terminal stop report success for a PTY that orca terminal list
    never showed. This PR makes such a PTY visible in the error rather than fixing that.

OrcaWin added 2 commits August 2, 2026 17:33
Destructive worktree removal proves every PTY is physically dead before it
touches the filesystem. When a stop RPC failed, it re-listed the provider to
check whether the PTY had actually exited — but on the *same* deadline the
sweeps had just spent. A slow-but-successful sweep therefore reached the
re-list with ~0ms of budget, timed out, and reported "unverifiable", which the
gate treated as "still live". `--force` never reached this gate, so the
workspace became permanently unremovable and every retry failed identically.

- Verification now gets its own 2s window instead of inheriting an exhausted
  deadline, so an already-exited PTY can be proven exited.
- The verdict distinguishes live / unverifiable / exited, and the error names
  the blocking PTY ids plus the escape hatch instead of only the worktree.
- `--force` propagates to the gate (`allowUnverifiedStop`), downgrading an
  unproven stop to a loud warning so removal can always complete.

Extracts `settleBeforeDeadline` and the verification logic into their own
modules to stay under max-lines.
…race

A 2s grace still wedged a workspace whose process inventory is merely slow:
the sweep spends its 10s, then the re-list needs a comparable window to
answer. Verification now gets a budget the size of the sweep's (floored at
2s), so "slow provider" stops reading as "PTY still alive".

Adds the reported scenario — stale registry row the daemon 404s on, behind a
9.9s inventory — as a regression test.
@greptile-apps

greptile-apps Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a deterministic wedge that made workspaces permanently unremovable: PTY stop verification ran on the same deadline the sweeps had just exhausted, so listProcesses timed out instantly and reported every PTY as still-alive, even stale registry ghosts. The fix gives verification its own fresh budget, introduces three explicit verdicts (exited/live/unverifiable), and adds a separately-signalled allowUnverifiedPtyStop waiver that is reachable only from genuine force affordances.

  • Root-cause fix (unstopped-pty-verification.ts): re-list runs on max(2s, sweepBudget) from the current moment instead of inheriting whatever the sweeps left over.
  • Waiver isolation (allowUnverifiedPtyStop): kept strictly separate from force and threaded identically through CLI → RPC → IPC → runtime → teardown; the dedup key includes both flags so a forced retry cannot coalesce onto the failed attempt.
  • Force-path safety (worktree-teardown.ts): Promise.allSettled ensures every in-flight shutdown RPC finishes before deletion starts; sweep-level failures warn instead of throw; live-verdict PTY registry rows are preserved so a retry can still discover them.
  • Reachable escape hatch: the unstopped-pty classifier reason causes the failure toast to display its Force Delete button; the hint string lives beside its matcher so they cannot drift.

Confidence Score: 5/5

Safe to merge — targeted fix to a deterministic bug with no new untrusted inputs, no path construction changes, and all destructive paths still gated behind the same physical-stop proofs as before.

The root cause is correctly identified and the fix directly addresses every symptom. The allowUnverifiedPtyStop waiver is cleanly separated from force, threaded identically through all call sites in both IPC and runtime layers, and protected by a static source-invariant test that would catch any re-aliasing. The force path uses Promise.allSettled to avoid racing deletions against in-flight shutdown RPCs. Registry rows are preserved for live PTYs. Tests were written failing-first and mutation-verified at every significant branch.

Files Needing Attention: No files require special attention. All changed files are consistent and well-tested.

Important Files Changed

Filename Overview
src/main/runtime/unstopped-pty-verification.ts New module: extracts PTY stop verification with its own fresh budget, three distinct verdicts (exited/live/unverifiable), and error description helpers
src/main/runtime/settle-before-deadline.ts Promoted from internal worktree-teardown.ts to its own module; adds .then(run) over run() to route synchronous throws through the fail-closed filter
src/main/runtime/worktree-teardown.ts Core teardown logic restructured: allowUnverifiedStop uses Promise.allSettled to wait for every sweep before returning, then gates deletion on the new three-verdict check
src/shared/worktree-removal.ts Adds UNSTOPPED_PTY_REMOVAL_PREFIX, WORKTREE_TEARDOWN_FORCE_HINT, isUnstoppedPtyRemovalError, and 'unstopped-pty' reason to classifier; unstopped-pty check correctly precedes the force guard
src/main/runtime/pty-waiver-source-invariant.test.ts New static invariant test: parses source of both large teardown files to assert allowUnverifiedStop is never derived from force, with both value and condition checks
src/main/ipc/worktrees.ts Threads allowUnverifiedPtyStop through all five stopPtysForDestructiveWorktreeRemoval call sites and the dedup key, keeping connectionId routing intact
src/main/runtime/orca-runtime.ts Adds allowUnverifiedPtyStop parameter to removeManagedWorktree and threads it through all internal stopPtysForDestructiveWorktreeRemoval call sites and dedup key
src/renderer/src/store/slices/worktrees.ts Passes allowUnverifiedPtyStop through both local IPC and RPC runtime paths; normalises to false (not undefined) so the dedup key is deterministic
src/renderer/src/components/sidebar/DeleteWorktreeDialog.tsx Force Delete branch now passes allowUnverifiedPtyStop:true, correctly distinguishing it from the plain confirmed-delete branch below
src/renderer/src/components/status-bar/WorkspaceSpaceManagerPanel.tsx Space panel force-recovery path passes allowUnverifiedPtyStop:true, consistent with other explicit force affordances
src/main/runtime/worktree-teardown-unstopped-pty.test.ts Comprehensive new test suite: covers fresh-budget fix, sweep-timeout bypass, live/unverifiable verdict distinction, registry-row preservation on force, and sweep-race safety
src/renderer/src/components/sidebar/delete-worktree-toast.ts Adds unstopped-pty toast case (non-destructive, offers Force Delete); hint string co-located with its matcher in worktree-removal.ts per design comment

Reviews (5): Last reviewed commit: "docs(worktree): record the diagnosabilit..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 3, 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
📝 Walkthrough

Walkthrough

The change adds deadline settlement and PTY verification helpers. Worktree teardown now classifies failed PTY stops, rejects live or unverifiable stops by default, and permits explicit forced removal to continue with a warning. CLI, RPC, preload, IPC, runtime, and renderer paths propagate the separate PTY-stop waiver option. Tests cover verification timing, diagnostics, forced behavior, error classification, and option forwarding.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.81% which is insufficient. The required threshold is 80.00%. 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 #11960 by improving PTY verification, reporting blocking IDs, and providing explicit force-removal escape hatches.
Out of Scope Changes check ✅ Passed The changes are focused on PTY teardown verification, force removal, related user messaging, API plumbing, and regression tests.
Title check ✅ Passed The title clearly identifies the PTY gate fix that prevents workspace removal from becoming permanently blocked.
Description check ✅ Passed The description covers the required summary, screenshots statement, testing, AI review, security audit, and notes sections in detail.
✨ 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.

🧹 Nitpick comments (2)
src/main/runtime/settle-before-deadline.ts (1)

46-48: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Guard against a synchronous throw from run().

If run() throws synchronously, the exception escapes the executor and rejects the returned promise. That bypasses both the fallback path and the failClosedOnRunError filter, so a best-effort caller receives a rejection instead of fallback.

♻️ Proposed fix
-    void run().then(finish, (error: unknown) =>
-      failClosedError && failClosedOnRunError(error) ? fail(error) : finish(fallback)
-    )
+    void Promise.resolve()
+      .then(run)
+      .then(finish, (error: unknown) =>
+        failClosedError && failClosedOnRunError(error) ? fail(error) : finish(fallback)
+      )
src/main/runtime/worktree-teardown-unstopped-pty.test.ts (1)

68-86: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Derive the delays from the sweep-timeout constant.

This test omits timeoutMs, so it depends on the default WORKTREE_PROCESS_SWEEP_TIMEOUT_MS being larger than the 9,900 ms list delay. If that default is lowered, verification times out and the test fails with an unrelated-looking rejection. Import the constant and compute the list delay and the timer advance from it, or pass an explicit timeoutMs.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c66ca405-ed67-43b2-8fae-624831a8c9be

📥 Commits

Reviewing files that changed from the base of the PR and between d426e35 and f10a50e.

📒 Files selected for processing (7)
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/settle-before-deadline.ts
  • src/main/runtime/unstopped-pty-verification.ts
  • src/main/runtime/worktree-teardown-unstopped-pty.test.ts
  • src/main/runtime/worktree-teardown.ts

…ible

Adversarial review found the previous commits fixed the wedge in one place and
left it in two others.

1. Force did not survive a sweep-level failure. All three sweeps fail closed on
   `requirePhysicalStop` alone and reject before the unproven-stop gate is ever
   reached, so an unresponsive daemon or dropped SSH channel still wedged the
   workspace with --force. Confirmed by test: a provider whose listProcesses
   rejects threw straight through `allowUnverifiedStop`. Force now degrades a
   failed sweep to a warning and proceeds.

2. The remedy the error advertised was unreachable from the desktop. The Force
   Delete button renders only when classifyWorktreeForceDeleteReason returns a
   reason, and it matched none of the PTY-gate messages — so the app told users
   to force-delete while hiding the button. Adds an 'unstopped-pty' reason plus
   toast copy; the hint string now lives next to its matcher so the two cannot
   drift apart.

3. Force with a *live* verdict unregistered the PTY it had just watched stay
   alive, dropping the registry row that the next sweep reads — hiding it from
   both the retry and the user. State is now cleared only on a proven exit.

Also: drop the always-dead `deadline` operand in the verification budget, route
synchronous throws in settleBeforeDeadline through the fail-closed filter
(CodeRabbit), and derive the slow-inventory test delay from the sweep constant.
@OrcaWin
OrcaWin requested a review from brennanb2025 as a code owner August 3, 2026 01:14
OrcaWin added 2 commits August 2, 2026 18:37
Adversarial review found the previous commit wired the waiver to the wrong
signal. `allowUnverifiedStop` was aliased to `force`, but the desktop's plain
Delete button already passes force:true after the ordinary confirmation
(DeleteWorktreeDialog.tsx, "the user already confirmed" — it exists to skip the
dirty-file prompt). So the PTY gate was effectively disabled on the primary
delete path: a transient provider failure would delete a workspace while its
terminals were still live, where main throws and touches nothing.

The waiver now travels on its own field, `allowUnverifiedPtyStop`, set by the
three genuine force affordances only — the dialog's Force Delete branch, the
failure toast's Force Delete action, the Space panel's force recovery — plus
the CLI's --force, which is unambiguous. An ordinary confirmed delete keeps the
gate strict, which is also what makes the new 'unstopped-pty' toast reachable:
the first attempt now fails, offers Force Delete, and the retry carries the
waiver.

Both in-flight removal dedupe keys include the new flag, so a forced retry can
never coalesce onto the attempt that just failed the gate.

Tests: a guard asserting force-without-waiver keeps the gate strict (verified
by mutation — re-aliasing force fails it), RPC coverage both ways, and the
renderer force paths. Also widens the slow-inventory test's 100ms fake-time
margin that raced under parallel load, pins "still live:" instead of a loose
regex, and covers clearing PTY state on a proven exit.

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/runtime/orca-runtime.ts (1)

3310-3338: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Return and merge unverified PTY teardown warnings.

killAllProcessesForWorktree may print console warnings when forced removal proceeds after incomplete sweeps or unstopped PTYs, but it only returns { runtimeStopped, providerStopped, registryStopped }. stopPtysForDestructiveWorktreeRemoval also returns Promise<void> and discards that summary, so RemoveWorktreeResult & { warning?: string } never receives the forced-teardown warning. Add a return/warning field from teardown and merge it into the result from each removable worktree path.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 789e9ac6-8162-42fc-b150-bd0cb35e1a43

📥 Commits

Reviewing files that changed from the base of the PR and between 6b30e9a and b09636d.

📒 Files selected for processing (18)
  • src/cli/handlers/worktree.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/worktree-rm-pty-waiver.test.ts
  • src/main/runtime/rpc/methods/worktree-schemas.ts
  • src/main/runtime/rpc/methods/worktree.test.ts
  • src/main/runtime/rpc/methods/worktree.ts
  • src/main/runtime/worktree-teardown-unstopped-pty.test.ts
  • src/main/runtime/worktree-teardown.ts
  • src/preload/api-types.ts
  • src/renderer/src/components/sidebar/DeleteWorktreeDialog.tsx
  • src/renderer/src/components/sidebar/delete-worktree-flow.test.ts
  • src/renderer/src/components/sidebar/delete-worktree-flow.ts
  • src/renderer/src/components/status-bar/WorkspaceSpaceManagerPanel.tsx
  • src/renderer/src/store/slices/worktree-helpers.ts
  • src/renderer/src/store/slices/worktrees.test.ts
  • src/renderer/src/store/slices/worktrees.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/ipc/worktrees.test.ts
  • src/main/runtime/worktree-teardown.ts

Comment thread src/main/ipc/worktrees.ts
Comment on lines +152 to +153
/** Explicit Force Delete only — `force` alone is set by the ordinary confirmation (#11960). */
allowUnverifiedPtyStop?: boolean

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Keep folder-workspace deletion behind the PTY verdict gate.

The new allowUnverifiedPtyStop option is used only by stopPtysForDestructiveWorktreeRemoval. The folder-workspace path still calls killAllProcessesForWorktree directly and catches its failure before purging metadata. A live or unverifiable PTY can therefore disappear from workspace state during ordinary deletion, and the Force Delete option does not control this path.

Route folder cleanup through the shared helper. Let only allowUnverifiedPtyStop === true continue after an unverified stop. Add tests for both policies.

The PR objective requires ordinary confirmed deletion to remain strict. As per coding guidelines, changes must support folder workspaces as well as Git worktrees.

Proposed fix
-            await killAllProcessesForWorktree(args.worktreeId, {
-              runtime,
-              localProvider: getLocalPtyProvider(),
-              onPtyStopped: clearProviderPtyState
-            }).catch((err) => {
-              console.warn(`[worktree-teardown] failed for ${args.worktreeId}:`, err)
-            })
+            await stopPtysForDestructiveWorktreeRemoval(runtime, args.worktreeId, {
+              allowUnverifiedStop: args.allowUnverifiedPtyStop === true
+            })

Source: Coding guidelines

Comment thread src/main/ipc/worktrees.ts Resolved
Comment thread src/main/ipc/worktrees.ts
Comment on lines +174 to +176
// Why (#11960): set only by an explicit Force Delete, never by the ordinary
// confirmation — otherwise the gate would be off on the primary delete path.
...(allowUnverifiedStop ? { allowUnverifiedStop: true } : {}),

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.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

rg -n -C 4 'allowUnverifiedPtyStop|allowUnverifiedStop|worktrees:remove' src/main src/preload src/renderer src/cli

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '## Candidate files:'
git ls-files | rg '(^src/main/ipc/worktrees\.ts$|^src/preload/api-types\.ts$|^src/preload/index\.ts$|^src/cli/handlers/worktree\.ts$|^src/renderer/src/store/slices/worktrees\.ts$)' || true

printf '%s\n' '## Type definitions and IPC handler registration:'
sed -n '136,160p' src/main/ipc/worktrees.ts
sed -n '2255,2275p' src/main/ipc/worktrees.ts
sed -n '425,438p' src/main/ipc/worktrees.ts

printf '%s\n' '## Renderer call sites:'
sed -n '218,231p' src/renderer/src/store/slices/worktree-helpers.ts
sed -n '4000,4037p' src/renderer/src/store/slices/worktrees.ts

printf '%s\n' '## Preload/API wrapper:'
sed -n '1406,1419p' src/preload/api-types.ts
sed -n '772,780p' src/preload/index.ts

printf '%s\n' '## CLI remove call site:'
sed -n '272,287p' src/cli/handlers/worktree.ts

printf '%s\n' '## Search for schema serialization/deserialization around worktree RPC:'
rg -n -C 3 "validate|schema|worktree\.rm|ipcMain\.handle|invoke\(" src/main src/preload src/renderer/src --glob '!**/*.test.ts' | head -n 200

printf '%s\n' '## Behavioral probe for JS truthiness vs equality used across locations:'
node - <<'JS'
function teardownGate(value) {
  return value ? "allows-PTY-waiver" : "requires-pty-stop";
}
function removalKey(value) {
  return value === true ? "allow-unverified-pty" : "require-pty-stop";
}
for (const value of [true, "true", "false", 0, 1, undefined, null]) {
  console.log(JSON.stringify({value, teardownGate: teardownGate(value), removalKey: removalKey(value)}));
}
JS

Repository: stablyai/orca

Length of output: 19252


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '## IPC schema/serialization references:'
rg -n -C 3 'ipcMain|ipcRenderer|invoke|send|remote|serializer|serialize|deserialize|createIPCMessenger|IPCMessenger|class.*Messenger|messenger|createSenderScoped|sender-scoped' src/main src/preload --glob '!**/*.test.ts' | head -n 240

printf '%s\n' '## Imports and shared types definitions:'
sed -n '1,100p' src/main/ipc/worktrees.ts
sed -n '1820,2265p' src/main/ipc/worktrees.ts

printf '%s\n' '## Runtime worktree remove types:'
rg -n -C 3 'RemoveWorktreeArgs|RuntimeWorktreeRemoveResult|worktree.rm|allowUnverifiedPtyStop' src/main src/preload src/cli src/renderer/src/store --glob '!**/*.test.ts'

Repository: stablyai/orca

Length of output: 50372


Normalize allowUnverifiedPtyStop before reusing it.

The handler uses both include ?? true when forwarding teardown options and ??? true when building the in-flight key. A removed option would use one truthiness branch in teardown but another equality-based key branch; use the same normalized boolean before each use.

… the waiver

Round-two review caught that separating the waiver from `force` reintroduced the
original dead end on the most common path, plus three related gaps.

- classifyWorktreeForceDeleteReason bailed on `force` before ever testing for the
  PTY-gate error. That guard was sound only while `force` implied the waiver;
  after the split, the ordinary confirmed Delete (which passes force:true to skip
  the dirty-file prompt) hit the gate and got no Force Delete button anywhere —
  the exact #11960 dead end, on the most common desktop delete. The PTY case is
  now decided before the `force` guard and suppressed by the waiver itself. The
  previous test had locked the broken behavior in; it now asserts the opposite.

- The web/mobile preload destructured `{ worktreeId, force, skipArchive }` and
  silently dropped the new field, so paired clients rendered Force Delete and
  stayed wedged when it was clicked. TypeScript could not catch it — the field is
  optional and destructuring a subset is legal.

- The forced path returned while sibling sweeps were still inside shutdown(), so
  the caller started deleting files against a PTY that was about to release its
  handles. Promise.all abandons the losers on first rejection; allSettled waits.
  It now also reports what the surviving sweeps actually stopped.

- Adds a source invariant pinning all ten teardown call sites: behavioural tests
  only reach one removal branch per file, so re-deriving the waiver from `force`
  at any of the other nine stayed green while disabling the gate on that path.
  Verified by mutation at a previously uncovered site.

Also settles the fake-timer stub that previously dangled across tests.

@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: Pro Plus

Run ID: b3979e0d-98ef-4a86-b102-b8357e15ae70

📥 Commits

Reviewing files that changed from the base of the PR and between b09636d and 1e7bea2.

📒 Files selected for processing (7)
  • src/main/runtime/pty-waiver-source-invariant.test.ts
  • src/main/runtime/worktree-teardown-unstopped-pty.test.ts
  • src/main/runtime/worktree-teardown.ts
  • src/renderer/src/store/slices/worktrees.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/worktree-removal-force-classification.test.ts
  • src/shared/worktree-removal.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/shared/worktree-removal-force-classification.test.ts
  • src/renderer/src/store/slices/worktrees.ts

Comment thread src/main/runtime/worktree-teardown.ts Outdated
Comment on lines +185 to +202
if (sweepFailure?.status === 'rejected') {
// Why (#11960): a sweep that cannot even complete — unresponsive daemon,
// dropped SSH channel — fails here, before the unproven-stop gate below could
// offer its escape hatch. An explicit Force Delete has to survive this one
// too, or the workspace stays exactly as unremovable as the bug this fixes.
if (!deps.allowUnverifiedStop) {
throw sweepFailure.reason
}
console.warn(
`[worktree-teardown] forcing removal after an incomplete PTY sweep for ${worktreeId} — ${describeError(sweepFailure.reason)}`
)
// Report what the surviving sweeps actually stopped rather than a flat zero.
return {
runtimeStopped: runtimeSettled.status === 'fulfilled' ? runtimeSettled.value.stopped : 0,
providerStopped: providerSettled.status === 'fulfilled' ? providerSettled.value : 0,
registryStopped: registrySettled.status === 'fulfilled' ? registrySettled.value : 0
}
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== unstopped-pty prefix and matcher in worktree-removal.ts ==="
rg -n "UNSTOPPED_PTY|isUnstoppedPtyRemovalError|WORKTREE_TEARDOWN_FORCE_HINT" -A3 -B3 src/shared/worktree-removal.ts

echo "=== describeUnstoppedPtys implementation ==="
fd unstopped-pty-verification.ts src/main/runtime --exec cat -n {}

echo "=== sweep-failure throw site ==="
rg -n -B5 -A5 "sweepFailure.reason" src/main/runtime/worktree-teardown.ts

echo "=== regression test for sweep-level failure without allowUnverifiedStop ==="
rg -n -B5 -A25 "sweep-level" src/main/runtime/worktree-teardown-unstopped-pty.test.ts

echo "=== renderer fallback for unclassified worktree removal errors ==="
rg -n -B5 -A15 "classifyWorktreeForceDeleteReason" src/renderer/src/components/sidebar/delete-worktree-flow.ts src/renderer/src/components/sidebar/DeleteWorktreeDialog.tsx 2>/dev/null || true

Repository: stablyai/orca

Length of output: 8414


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== classifyWorktreeForceDeleteReason implementation ==="
rg -n -B15 -A45 "function classifyWorktreeForceDeleteReason|classifyWorktreeForceDeleteReason" src/shared/worktree-removal.ts

echo "=== worktree telemetry/error callers in renderer ==="
rg -n -B8 -A22 "classifyWorktreeForceDeleteReason|WorktreeForceDeleteReason|unstopped-pty|DeleteWorktreeDialog|delete-worktree-flow" src/renderer/src src/main/runtime/src 2>/dev/null || true

echo "=== renderer component snippets around force delete hints ==="
for f in $(git ls-files 'src/renderer/src/**/*.{tsx,ts,jsx,js}' | rg 'DeleteWorktree|delete-worktree|worktree' | head -20); do
  echo "--- $f"
  rg -n -B8 -A16 "force.delete|Force Delete|force delete|classifyWorktree|unstopped-pty|RemoveAnyway|confirming|force:" "$f" || true
done

Repository: stablyai/orca

Length of output: 50370


Propagate the force-delete marker for sweep failures.

When !deps.allowUnverifiedStop, sweepFailure.reason is thrown unmodified, but classifyWorktreeForceDeleteReason() only exposes canForceDelete: true through isUnstoppedPtyRemovalError(error). A raw provider/runtime sweep error will return null, so the renderer does not show the Force Delete path for this failure type. Wrap this throw in the same recognizable error contract used by describeUnstoppedPtys or otherwise map it as an unstopped-pty force-delete reason.

…the invariant

Round-three review, three findings.

1. allSettled picked the rejection by array position, not by time, so a runtime
   sweep hanging to its own deadline masked the provider's `ssh channel closed`
   with the generic "Timed out waiting for physical PTY teardown" — in both the
   thrown error and the forced path's warning. It now prefers any reason that
   isn't the shared deadline sentinel.

2. That same rewrite had made the non-force path wait the full sweep budget
   before reporting a failure it used to report instantly. Both are achievable:
   force still waits for every sweep (it goes on to delete files, so handles must
   be released first), while the non-force path fails fast, since a rejection
   aborts the removal and nothing is deleted.

3. The source invariant was bypassable by the most likely regression shape —
   `...(force ? { allowUnverifiedStop: true } : {})` keeps the value a blameless
   `true` while the `force` guarding it sits outside the capture, re-disabling
   the gate on a delete path with the whole suite green. It now checks the
   guarding condition too, pins exact site counts (a deleted site was also
   silent), and uses a lazy match so an optional chain can't end it early.
   Mutation-verified against all four shapes.

Also root-causes the flake instead of widening margins: these tests advanced
fake timers before awaiting the teardown, so a rejection mid-advance had no
handler and vitest attributed it to whichever test was running — which explains
the cross-test message that was impossible from its own stub. Handlers are now
attached at creation, and runAllTimersAsync drains timers scheduled from
microtasks rather than trusting a fixed advance window. Two concurrent 10x loops
of the reported repro: 20/20 green, no unhandled rejections (was 6/20 failing).

@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/main/runtime/worktree-teardown-unstopped-pty.test.ts (1)

14-18: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the test comments.

Replace each comment with one concise sentence that records only the non-obvious reason.

  • src/main/runtime/worktree-teardown-unstopped-pty.test.ts#L14-L18: summarize why the rejection handler is attached before fake timers advance.
  • src/main/runtime/worktree-teardown-unstopped-pty.test.ts#L288-L290: summarize why the provider failure takes priority over the deadline error.

As per coding guidelines, “Comments must be concise, limited to non-obvious information, and preferably one line.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4da6102e-88d6-4d95-88d7-05a68530cce6

📥 Commits

Reviewing files that changed from the base of the PR and between 1e7bea2 and 648ab86.

📒 Files selected for processing (3)
  • src/main/runtime/pty-waiver-source-invariant.test.ts
  • src/main/runtime/worktree-teardown-unstopped-pty.test.ts
  • src/main/runtime/worktree-teardown.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/runtime/pty-waiver-source-invariant.test.ts
  • src/main/runtime/worktree-teardown.ts

OrcaWin added 2 commits August 2, 2026 19:09
Round-four review found the previous tightening had traded strength for
brittleness in both directions.

Strength regression: replacing the per-value positive check with a
worktrees.ts-only exact count left orca-runtime.ts's five branches asserted only
against the literal `force`, so wiring one to any other in-scope boolean
(`allowUnverifiedStop: runHooks`) passed. The positive check is back for both
files and accepts either call style.

Brittleness: the hardcoded count of 6 failed on three legitimate refactors — a
destructured local (the style orca-runtime.ts already uses), a source comment
quoting the key, and merging two near-identical removal branches. The expected
count is now derived from the number of teardown call sites, and comments are
stripped before matching. Dropping the waiver from a branch that still exists
still fails.

Probe matrix, all mutation-verified: the five real regressions (spread gated on
force, helper gate, optional-chain condition, deleted waiver, wrong non-force
variable) fail; the three legitimate refactors pass.

Also reports every sweep failure rather than only the preferred one — specific
causes first, so the deadline sentinel neither masks nor is lost — and adds a
store-bridge guard, since collapsing `force` and the waiver back into one flag
is easiest exactly there. Both verified by mutation.
@OrcaWin
OrcaWin merged commit 525ffc5 into main Aug 3, 2026
49 checks passed
@AmethystLiang

Copy link
Copy Markdown
Contributor

thanks for reporting. looking into it

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…emoval (stablyai#12153)

Destructive worktree removal proves every PTY is dead before touching the filesystem. When a stop
RPC failed, it re-listed the provider to check whether the PTY had already exited — but on the
same deadline the sweeps had just spent, so it timed out without ever asking and read "could not
verify" as "still live". The sweep spends that budget every run, making the refusal deterministic;
--force never reached the gate, so the workspace was unremovable forever.

- Verification gets its own budget instead of an exhausted remainder.
- Verdicts split into exited / live / unverifiable; the error names the blocking PTY ids and why.
- A reachable escape hatch: allowUnverifiedPtyStop, set only by genuine Force Delete affordances
  and the CLI's --force — never by the force the ordinary delete confirmation already sets — with
  an 'unstopped-pty' classifier reason so the desktop actually offers the button.
- Force also survives a sweep that cannot complete; the non-force path still fails fast.

Fixes stablyai#11960
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]: worktree permanently unremovable — "Failed to physically stop every PTY" with no terminal listed and --force ineffective

2 participants