Repository navigation
fix(worktree): stop the PTY gate from permanently wedging workspace removal (#11960) - #12153
Conversation
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 SummaryThis PR fixes a deterministic wedge that made workspaces permanently unremovable: PTY stop verification ran on the same deadline the sweeps had just exhausted, so
Confidence Score: 5/5Safe 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.
|
| 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
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/main/runtime/settle-before-deadline.ts (1)
46-48: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winGuard against a synchronous throw from
run().If
run()throws synchronously, the exception escapes the executor and rejects the returned promise. That bypasses both thefallbackpath and thefailClosedOnRunErrorfilter, so a best-effort caller receives a rejection instead offallback.♻️ 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 valueDerive the delays from the sweep-timeout constant.
This test omits
timeoutMs, so it depends on the defaultWORKTREE_PROCESS_SWEEP_TIMEOUT_MSbeing 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 explicittimeoutMs.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c66ca405-ed67-43b2-8fae-624831a8c9be
📒 Files selected for processing (7)
src/main/ipc/worktrees.test.tssrc/main/ipc/worktrees.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/settle-before-deadline.tssrc/main/runtime/unstopped-pty-verification.tssrc/main/runtime/worktree-teardown-unstopped-pty.test.tssrc/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.
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.
There was a problem hiding this comment.
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 winReturn and merge unverified PTY teardown warnings.
killAllProcessesForWorktreemay print console warnings when forced removal proceeds after incomplete sweeps or unstopped PTYs, but it only returns{ runtimeStopped, providerStopped, registryStopped }.stopPtysForDestructiveWorktreeRemovalalso returnsPromise<void>and discards that summary, soRemoveWorktreeResult & { 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
📒 Files selected for processing (18)
src/cli/handlers/worktree.tssrc/main/ipc/worktrees.test.tssrc/main/ipc/worktrees.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/worktree-rm-pty-waiver.test.tssrc/main/runtime/rpc/methods/worktree-schemas.tssrc/main/runtime/rpc/methods/worktree.test.tssrc/main/runtime/rpc/methods/worktree.tssrc/main/runtime/worktree-teardown-unstopped-pty.test.tssrc/main/runtime/worktree-teardown.tssrc/preload/api-types.tssrc/renderer/src/components/sidebar/DeleteWorktreeDialog.tsxsrc/renderer/src/components/sidebar/delete-worktree-flow.test.tssrc/renderer/src/components/sidebar/delete-worktree-flow.tssrc/renderer/src/components/status-bar/WorkspaceSpaceManagerPanel.tsxsrc/renderer/src/store/slices/worktree-helpers.tssrc/renderer/src/store/slices/worktrees.test.tssrc/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
| /** Explicit Force Delete only — `force` alone is set by the ordinary confirmation (#11960). */ | ||
| allowUnverifiedPtyStop?: boolean |
There was a problem hiding this comment.
🗄️ 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
| // 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 } : {}), |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
rg -n -C 4 'allowUnverifiedPtyStop|allowUnverifiedStop|worktrees:remove' src/main src/preload src/renderer src/cliRepository: 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)}));
}
JSRepository: 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.
There was a problem hiding this comment.
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
📒 Files selected for processing (7)
src/main/runtime/pty-waiver-source-invariant.test.tssrc/main/runtime/worktree-teardown-unstopped-pty.test.tssrc/main/runtime/worktree-teardown.tssrc/renderer/src/store/slices/worktrees.tssrc/renderer/src/web/web-preload-api.tssrc/shared/worktree-removal-force-classification.test.tssrc/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
| 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 | ||
| } | ||
| } |
There was a problem hiding this comment.
🗄️ 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 || trueRepository: 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
doneRepository: 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).
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/runtime/worktree-teardown-unstopped-pty.test.ts (1)
14-18: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten 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
📒 Files selected for processing (3)
src/main/runtime/pty-waiver-source-invariant.test.tssrc/main/runtime/worktree-teardown-unstopped-pty.test.tssrc/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
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.
…ep-failure return
|
thanks for reporting. looking into it |
…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
Fixes #11960
Summary
A workspace could become permanently unremovable.
orca worktree rmfailed withFailed to physically stop every PTY for worktree: …,--forcefailed identically, and everyretry gave the same result — with no terminal listed and no OS process holding the path.
Root cause is (b) from the issue report:
verifyFailedPtysExitedconflated "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:
settleBeforeDeadlinereturns the fallback immediately whenremaining <= 0, so a sweep thatused 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 casethis 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
--forceescape 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
inheriting its exhausted remainder.
exited/live/unverifiable. The error names the blockingPTY ids and, when verification failed, why.
allowUnverifiedPtyStopwaives 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 newunstopped-ptyforce-deletereason and toast copy make the button appear, so the first attempt fails, offers Force Delete,
and the retry carries the waiver.
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 (nosuppressions added), and all three localization gates pass.
verify:skill-bundle-manifestreports stale generated skill artifacts; verified identical on
origin/mainatd426e35be, 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-existingon this Windows box (symlink permissions,
/bin/shspawns, SSH/codex home paths);spot-checked
src/relay/pty-handler.test.tsat the pre-change commit — same 15 failures.pnpm buildincludes 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
forceat 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:
force, but the desktop's plainDelete button already passes
force: trueafter the ordinary confirmation (to skip thedirty-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.
forcebefore 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
forceguard and suppressed by the waiver.--forcecould not escape a sweep-level failure — the sweeps fail closed before the gate.TypeScript could not catch it: the field is optional and destructuring a subset is legal.
shutdown(), racing thedelete against a PTY about to release its handles.
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
connectionIdthroughthe signature change (diffed one-for-one against
origin/main), so no SSH removal can sweep thelocal provider. The folder-workspace
::workspace:<uuid>guard from #10252 is byte-identical tomain, and folder-workspace removal never sets
requirePhysicalStopat all. Absolute-epochdeadlineMsis 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-clientsets none, and the renderer RPC path allows 60s. The non-force path still failsfast (measured at 1ms).
Security Audit
caller was traced — notably the background workspace-cleanup batch (which derives
forcefroman 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.
isDangerousWorktreeRemovalPath,assertWorktreeDoesNotContainRegisteredWorktree,canSafelyRemoveOrphanedWorktreeDirectory,assertWorktreeCleanForRemoval,assertWorktreeUnlockedForRemoval. PTY ownership matching was not widened.worktree path the message already contained.
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:
force: truewithout the waiver, so it fails safe —but
mobile/app/h/[hostId]/index.tsxswallows the error in a barecatch {}, so the rowsilently reappears with no explanation. Surface the error first; add the affordance second.
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.
orca terminal stopreport success for a PTY thatorca terminal listnever showed. This PR makes such a PTY visible in the error rather than fixing that.