Repository navigation
fix(worktrees): fence SSH worktree deletion PTY teardown to the owning host - #12388
Conversation
…g host Destructive worktree removal swept PTYs by worktree id alone. Worktree ids are `repoId::path` and the store keeps one per host, so deleting an SSH worktree could stop a same-id local (or other-connection) workspace's terminals — or fail outright with `selector_ambiguous` when two hosts owned the id. Every destructive teardown now names its owner (resolvedWorktreeId plus the connection/runtime environment), matching the already-hardened forget-local path: - IPC `worktrees:remove` (git + folder workspaces) - runtime `removeManagedWorktree` (CLI/mobile `worktree.rm`, git + folder) - missing-worktree terminal reconciliation, including its no-provider fallback The #11960 allowUnverifiedStop force-delete gate is untouched.
📝 WalkthroughWalkthroughWorktree terminal cleanup now uses the resolved worktree ID and owning connection or runtime environment. Folder-workspace deletion selects the provider for the owning host and avoids local registry cleanup for external hosts. Missing-worktree reconciliation applies the same host fence to runtime-only and provider-based cleanup. Tests cover identical worktree identifiers across local and SSH hosts. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 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.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c7469b30-3b6e-4645-838d-a006b5b6d55e
📒 Files selected for processing (6)
src/main/ipc/worktrees.test.tssrc/main/ipc/worktrees.tssrc/main/runtime/missing-worktree-terminal-reconciliation.test.tssrc/main/runtime/missing-worktree-terminal-reconciliation.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.ts
| function hostFence( | ||
| repo: Repo, | ||
| worktreeId: string | ||
| ): { resolvedWorktreeId: string; resolvedConnectionId?: string } { | ||
| return { | ||
| resolvedWorktreeId: worktreeId, | ||
| ...(repo.connectionId ? { resolvedConnectionId: repo.connectionId } : {}) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Fence runtime-host reconciliation.
hostFence handles SSH ownership only. If repo.executionHostId is runtime:<id>, reconciliation uses the local provider and leaves local inventory and registry sweeps enabled. Those ID-only sweeps can affect a same-ID local PTY.
src/main/runtime/missing-worktree-terminal-reconciliation.ts#L51-L58: deriveresolvedRuntimeEnvironmentIdfrom runtime execution-host ownership.src/main/runtime/missing-worktree-terminal-reconciliation.ts#L87-L90: do not select the local provider for a runtime-owned repository.src/main/runtime/missing-worktree-terminal-reconciliation.ts#L115-L124: disable provider inventory and local registry sweeps for runtime-owned repositories.src/main/runtime/missing-worktree-terminal-reconciliation.test.ts#L67-L83: add a runtime-host provider-path test.src/main/runtime/missing-worktree-terminal-reconciliation.test.ts#L107-L112: add a runtime-only fallback test that expectsresolvedRuntimeEnvironmentId.
This conflicts with the PR objective to fence cleanup by the owning connection or runtime environment.
📍 Affects 2 files
src/main/runtime/missing-worktree-terminal-reconciliation.ts#L51-L58(this comment)src/main/runtime/missing-worktree-terminal-reconciliation.ts#L87-L90src/main/runtime/missing-worktree-terminal-reconciliation.ts#L115-L124src/main/runtime/missing-worktree-terminal-reconciliation.test.ts#L67-L83src/main/runtime/missing-worktree-terminal-reconciliation.test.ts#L107-L112
| addedAt: 1, | ||
| connectionId: 'ssh-1' | ||
| } | ||
| const remoteStore = { ...store, getRepos: () => [remoteRepo], getRepo: () => remoteRepo } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win
Remove the duplicate declaration.
const remoteStore appears twice at Line 5937 in the same block. TypeScript rejects the redeclaration and cannot typecheck this test file. Keep one declaration.
| // Folder projects can be SSH-backed, so resolve the owner before sweeping. | ||
| const folderHost = parseExecutionHostId( | ||
| store.getWorktreeMeta(removalTarget.id)?.hostId ?? getRepoExecutionHostId(repo) | ||
| ) | ||
| const folderSshPtyProvider = | ||
| folderHost?.kind === 'ssh' ? this.getSshProviderFn?.(folderHost.targetId) : undefined | ||
| const externalFolderHost = folderHost?.kind === 'ssh' || folderHost?.kind === 'runtime' | ||
| const folderPtyProvider = folderSshPtyProvider ?? this.getLocalProvider() | ||
| if (folderPtyProvider) { | ||
| // Why: folder workspace deletion has no Git removal phase where PTYs | ||
| // would otherwise be swept; tear them down before hiding the workspace. | ||
| await killAllProcessesForWorktree(removalTarget.id, { | ||
| runtime: this, | ||
| localProvider, | ||
| onPtyStopped: this.onPtyStopped ?? undefined | ||
| // External host inventories must never sweep a same-id local workspace. | ||
| resolvedWorktreeId: removalTarget.id, | ||
| ...(folderHost?.kind === 'ssh' ? { resolvedConnectionId: folderHost.targetId } : {}), | ||
| ...(folderHost?.kind === 'runtime' | ||
| ? { resolvedRuntimeEnvironmentId: folderHost.environmentId } | ||
| : {}), | ||
| localProvider: folderPtyProvider, | ||
| onPtyStopped: this.onPtyStopped ?? undefined, | ||
| ...(externalFolderHost | ||
| ? { | ||
| includeProviderInventory: | ||
| folderHost?.kind === 'ssh' && Boolean(folderSshPtyProvider), | ||
| includeLocalRegistry: false | ||
| } | ||
| : {}) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check whether a local PTY provider is guaranteed to be installed
# in headless/serve deployment paths that can own runtime-kind execution hosts.
set -euo pipefail
rg -n 'setLocalPtyProvider' --type=ts -C 5
echo '---'
rg -n "kind: 'runtime'" --type=ts -C 3 -g '!**/*.test.ts'Repository: stablyai/orca
Length of output: 151
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Repo files around orca runtime:"
fd -a 'orca-runtime\.ts$' . || true
echo '---'
echo "Git status/stat:"
git status --short || true
echo '---'
echo "Line count for candidate:"
candidate="$(fd 'orca-runtime\.ts$' . | head -n 1)"
if [ -n "${candidate:-}" ]; then
wc -l "$candidate"
echo "Candidate: $candidate"
echo "--- lines 23430-23490 ---"
sed -n '23430,23490p' "$candidate" | nl -ba -v23430
fi
echo "--- setLocalPtyProvider searches ---"
rg -n 'setLocalPtyProvider|LocalPtyProvider|getLocalProviderFn|getLocalProvider\(' --type=ts -g '!**/*.test.ts' || true
echo "--- runtime kind searches ---"
rg -n "kind: 'runtime'|kind = 'runtime'|environmentId|stopTerminalsForWorktree|killAllProcessesForWorktree" --type=ts -g '!**/*.test.ts' -C 3 || trueRepository: stablyai/orca
Length of output: 440
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="src/main/runtime/orca-runtime.ts"
echo "--- lines 23430-23490 ---"
awk 'NR>=23430 && NR<=23490 { printf "%7d %s\n", NR, $0 }' "$FILE"
echo "--- getLocalProvider/setLocalPtyProvider/getLocalProviderFn ---"
rg -n 'setLocalPtyProvider|LocalPtyProvider|getLocalProviderFn|getLocalProvider\(' --type=ts -g '!**/*.test.ts' || true
echo "--- runtime environment and PTY sweep related symbols ---"
rg -n "kind: 'runtime'|kind = 'runtime'|environmentId|stopTerminalsForWorktree|killAllProcessesForWorktree|includeProviderInventory|includeLocalRegistry" --type=ts -g '!**/*.test.ts' -C 3 || true
echo "--- deterministic JS probe for folderPtyProvider resolution in reviewed branch ---"
node - <<'JS'
for (const kind of ['ssh', 'runtime']) {
const folderHost = { kind, targetId: 'target-' + kind, environmentId: 'env-' + kind }
const folderSshPtyProvider = folderHost.kind === 'ssh' ? 'sshProvider' : undefined
const getLocalProvider = null
const folderPtyProvider = folderSshPtyProvider ?? getLocalProvider
const externalFolderHost = folderHost.kind === 'ssh' || folderHost.kind === 'runtime'
const callBlocked = !folderPtyProvider
const includeProviderInventory = folderHost.kind === 'ssh' && Boolean(folderSshPtyProvider)
const includeLocalRegistry = false
console.log(JSON.stringify({
kind,
folderSshPtyProvider,
folderPtyProvider,
externalFolderHost,
callBlocked,
includeProviderInventory,
includeLocalRegistry
}, null, 2))
}
JSRepository: stablyai/orca
Length of output: 4188
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="src/main/runtime/orca-runtime.ts"
echo "--- getLocalProvider/setLocalPtyProvider/getLocalProviderFn usages ---"
rg -n 'setLocalPtyProvider|LocalPtyProvider|getLocalProviderFn|getLocalProvider\(' --type=ts -g '!**/*.test.ts' || true
echo "--- runtime environment and PTY sweep related symbols ---"
rg -n "kind: 'runtime'|kind = 'runtime'|environmentId|stopTerminalsForWorktree|killAllProcessesForWorktree|includeProviderInventory|includeLocalRegistry" --type=ts -g '!**/*.test.ts' -C 3 || true
echo "--- deterministic JS probe for folderPtyProvider resolution in reviewed branch ---"
node - <<'JS'
for (const kind of ['ssh', 'runtime']) {
const folderHost = { kind, targetId: 'target-' + kind, environmentId: 'env-' + kind }
const folderSshPtyProvider = folderHost.kind === 'ssh' ? 'sshProvider' : undefined
const getLocalProvider = null
const folderPtyProvider = folderSshPtyProvider ?? getLocalProvider
const externalFolderHost = folderHost.kind === 'ssh' || folderHost.kind === 'runtime'
const callBlocked = !folderPtyProvider
const includeProviderInventory = folderHost.kind === 'ssh' && Boolean(folderSshPtyProvider)
const includeLocalRegistry = false
console.log(JSON.stringify({
kind,
folderSshPtyProvider,
folderPtyProvider,
externalFolderHost,
callBlocked,
includeProviderInventory,
includeLocalRegistry
}, null, 2))
}
JS
echo "--- search killAllProcessesForWorktree definition and dependencies ---"
rg -n "function killAllProcessesForWorktree|const killAllProcessesForWorktree|export .*killAllProcessesForWorktree|getRuntimeFolderWorkspaceRootId|getRepoExecutionHostId|parseExecutionHostId" --type=ts -g '!**/*.test.ts' -C 4 || trueRepository: stablyai/orca
Length of output: 222
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "--- locate runtime-related declarations ---"
rg -n "getLocalProviderFn|setLocalPtyProvider|stopTerminalsForWorktree|killAllProcessesForWorktree|getRuntimeFolderWorkspaceRootId|getRepoExecutionHostId|parseExecutionHostId" --type=ts -g '!**/*.test.ts' -C 6 || true
echo "--- declarations mentioning Local provider in non-ORCA files ---"
rg -n "Runtime|localProvider|LocalProvider|ptyProvider|PtyProvider|stopTerminalsForWorktree|killAllProcessesForWorktree" src/main src -g '!**/*.test.ts' -g '!src/main/runtime/orca-runtime.ts' -C 4 || true
echo "--- package/workspace search for headless/serve ---"
rg -n "orcaserve|serve|serve host|headless|runtimeFolder|runtime.*folder|environmentId" package*.json README.md src config .github -g '!*.test.ts' -g '!**/node_modules/**' -C 4 || trueRepository: stablyai/orca
Length of output: 730
Run the runtime-fenced PTY sweep independently of getLocalProvider().
For folderHost.kind === 'runtime', folderPtyProvider falls back to this.getLocalProvider(), and the if (folderPtyProvider) guard skips killAllProcessesForWorktree. That call uses resolvedRuntimeEnvironmentId, and with includeProviderInventory: false, the local provider is not needed for the sweep. Make the runtime-fenced path call the sweep unconditionally, or skip only the local-provider-owned branch.
…g host (stablyai#12388) Destructive worktree removal swept PTYs by worktree id alone. Worktree ids are `repoId::path` and the store keeps one per host, so deleting an SSH worktree could stop a same-id local (or other-connection) workspace's terminals — or fail outright with `selector_ambiguous` when two hosts owned the id. Every destructive teardown now names its owner (resolvedWorktreeId plus the connection/runtime environment), matching the already-hardened forget-local path: - IPC `worktrees:remove` (git + folder workspaces) - runtime `removeManagedWorktree` (CLI/mobile `worktree.rm`, git + folder) - missing-worktree terminal reconciliation, including its no-provider fallback The stablyai#11960 allowUnverifiedStop force-delete gate is untouched.
Summary
Deleting a workspace stopped terminals by worktree id alone. Worktree ids are
repoId::pathand the store deliberately keeps the same id under more than one host, so an SSH delete could kill a same-id local workspace's live terminals — or fail the delete outright withselector_ambiguousonce two hosts owned the id.Every destructive PTY sweep now names its owner (
resolvedWorktreeId+resolvedConnectionId/resolvedRuntimeEnvironmentId), the same fence the forget-local path already had:stopPtysForDestructiveWorktreeRemovalinsrc/main/ipc/worktrees.ts— covers all five destructive callers (SSH git delete, SSH orphan-directory cleanup, local git delete, local orphan/leftover-directory cleanup).worktrees:remove— folder projects can be SSH-backed, and it was sweeping the local inventory unfenced. Now resolves the owner host (worktree meta > repo) exactly like forget-local, and uses the SSH PTY provider withincludeLocalRegistry: falsewhen the owner is external.OrcaRuntimeService.stopPtysForDestructiveWorktreeRemovaland the runtime folder branch ofremoveManagedWorktree— the CLI/mobileworktree.rmsurface, a line-for-line duplicate of the IPC bug.stopMissingWorktreeTerminals— a repo-scoped reconciliation sweep that could stop another host's same-id terminals; both the provider path and the no-provider graph fallback are fenced.The #11960
allowUnverifiedStopforce-delete gate is untouched (still set only by an explicit Force Delete, never inferred fromforce); its two regression tests still pass.Audit of every teardown call site (requirement: fence or justify):
ipc/worktrees.tsstopPtysForDestructiveWorktreeRemoval(5 callers)ipc/worktrees.tsfolder-workspace removeipc/worktrees.tsforget-localorca-runtime.tsstopPtysForDestructiveWorktreeRemovalorca-runtime.tsfolder-workspaceremoveManagedWorktreeorca-runtime.tsorphan (!repo) removalmissing-worktree-terminal-reconciliation.ts(both paths)Known residual, not fixed here: a local delete still passes no host fence, so it can in principle reach an SSH/runtime same-id workspace (the mirror direction).
stopTerminalsForWorktreehas no "local-only" predicate —resolvedConnectionId === undefinedmeans "any host" — and adding one would change that method's contract and the already-shipped forget-local path's behavior. It also can't simply excluderemote:-prefixed PTYs, because local repos can be runtime-environment-backed and those PTYs must die before deletion. Left as a separate follow-up; the reported P1 (SSH delete reaching other hosts) is closed.Screenshots
No visual change.
Testing
pnpm lint— full run, greenpnpm typecheck— full run, greenpnpm test— ran the affected suites only (ipc/worktrees,ipc/worktrees-windows,runtime/worktree-teardown,runtime/worktree-teardown-unstopped-pty,runtime/missing-worktree-terminal-reconciliation,rpc/methods/worktree*: 316 passed) plus targetedorca-runtime.test.tsfilters (SSH76,folder23,remove12,terminal223,same-id3 — all passed). The full suite was not run locally; CI covers it.pnpm build— not run locally; no build-surface change (main-process logic only). CI covers it.orca-runtime.test.ts: an SSHremoveManagedWorktreeend-to-end test asserting a same-id local PTY is never stopped while the remote one is; plus astopTerminalsForWorktreeunit test that two hosts sharing one id stop only the fenced one. Both were verified to fail with the fence reverted (the e2e one killed 2 PTYs instead of 1).ipc/worktrees.test.ts: exact-deps assertions for the SSH git delete, the SSH folder workspace delete, and the local delete (fence present, noresolvedConnectionIdleaked into the local path).missing-worktree-terminal-reconciliation.test.ts: fence assertions on both the provider and no-provider paths.AI Review Report
Self-review with Claude, focused on: (1) does adding
resolvedWorktreeIdchange matching semantics — yes, it swaps exact-string id equality for repoId +runtimePathsEqualpath comparison and skips selector resolution; that is the same trade the forget-local path already makes, and the #10252 regression test proves folder-instance suffixes are still not collapsed into their sibling checkouts; (2) does it weaken the #11960 gate — no,requirePhysicalStop/allowUnverifiedStopare untouched and both waiver tests still pass; (3) do theincludeProviderInventory/includeLocalRegistrytoggles match the proven forget-local shape — yes, copied field-for-field; (4) folder workspaces vs git worktrees and local vs SSH vs runtime hosts are each covered by an explicit branch, with the runtime-environment case routed throughresolvedRuntimeEnvironmentId.Cross-platform: explicitly checked. No shortcuts, labels, shell invocations, or path string-building were added — path comparison is delegated to the existing
runtimePathsEqual/splitWorktreeIdhelpers that already normalize Windows vs POSIX spelling, and no Electron-specific API is touched. Behavior is identical on macOS, Linux, and Windows; the WSL/runtime-environment host is handled by the sameresolvedRuntimeEnvironmentIdbranch as before.Declining CodeRabbit's Docstring Coverage check per
AGENTS.md("Concise/Brief Non-obvious comments ONLY … 1 LINE if possible") — the added comments state why the fence exists, which is the non-obvious part.Security Audit
This is a privilege-scoping fix: it narrows which processes a delete may kill, so a workspace on host A can no longer have its terminals terminated by a deletion on host B (an availability/data-loss class issue — killing a live agent's shell). No new input handling, no command execution, no new path construction, no auth or secrets, and no IPC surface change (
RemoveWorktreeArgsis unchanged). The one behavioral widening to note: for external hosts the local PTY registry is no longer swept (includeLocalRegistry: false) — intentional, since that registry only ever holds local rows, and it matches the existing forget-local path. No dependency changes. Follow-up: the local→remote mirror direction described in the Summary.Notes
ipc/worktrees.ts, but the identical function is duplicated inorca-runtime.ts(the CLI/mobileworktree.rmpath) and the same defect class sits in the reconciliation sweep. Fixing only the IPC copy would have left the CLI and mobile delete paths broken, so all three are in this PR — called out here rather than landed silently.