Skip to content

fix(worktrees): fence SSH worktree deletion PTY teardown to the owning host - #12388

Merged
brennanb2025 merged 1 commit into
mainfrom
brennanb2025/fix-ssh-deletion-fence
Aug 4, 2026
Merged

brennanb2025 merged 1 commit into
mainfrom
brennanb2025/fix-ssh-deletion-fence

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Deleting a workspace stopped terminals by worktree id alone. Worktree ids are repoId::path and 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 with selector_ambiguous once 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:

  • stopPtysForDestructiveWorktreeRemoval in src/main/ipc/worktrees.ts — covers all five destructive callers (SSH git delete, SSH orphan-directory cleanup, local git delete, local orphan/leftover-directory cleanup).
  • The IPC folder-workspace branch of 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 with includeLocalRegistry: false when the owner is external.
  • OrcaRuntimeService.stopPtysForDestructiveWorktreeRemoval and the runtime folder branch of removeManagedWorktree — the CLI/mobile worktree.rm surface, 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 allowUnverifiedStop force-delete gate is untouched (still set only by an explicit Force Delete, never inferred from force); its two regression tests still pass.

Audit of every teardown call site (requirement: fence or justify):

Call site Before Now
ipc/worktrees.ts stopPtysForDestructiveWorktreeRemoval (5 callers) unfenced fenced
ipc/worktrees.ts folder-workspace remove unfenced, local provider fenced + owner provider
ipc/worktrees.ts forget-local already fenced (#12153-era hardening) unchanged
orca-runtime.ts stopPtysForDestructiveWorktreeRemoval unfenced fenced
orca-runtime.ts folder-workspace removeManagedWorktree unfenced, local provider fenced + owner provider
orca-runtime.ts orphan (!repo) removal already fenced unchanged
missing-worktree-terminal-reconciliation.ts (both paths) unfenced fenced

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). stopTerminalsForWorktree has no "local-only" predicate — resolvedConnectionId === undefined means "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 exclude remote:-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, green
  • pnpm typecheck — full run, green
  • pnpm 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 targeted orca-runtime.test.ts filters (SSH 76, folder 23, remove 12, terminal 223, same-id 3 — 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.
  • Added or updated high-quality tests that would catch regressions
    • orca-runtime.test.ts: an SSH removeManagedWorktree end-to-end test asserting a same-id local PTY is never stopped while the remote one is; plus a stopTerminalsForWorktree unit 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, no resolvedConnectionId leaked 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 resolvedWorktreeId change matching semantics — yes, it swaps exact-string id equality for repoId + runtimePathsEqual path 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/allowUnverifiedStop are untouched and both waiver tests still pass; (3) do the includeProviderInventory / includeLocalRegistry toggles 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 through resolvedRuntimeEnvironmentId.

Cross-platform: explicitly checked. No shortcuts, labels, shell invocations, or path string-building were added — path comparison is delegated to the existing runtimePathsEqual / splitWorktreeId helpers 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 same resolvedRuntimeEnvironmentId branch 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 (RemoveWorktreeArgs is 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

  • Scope note: the task named ipc/worktrees.ts, but the identical function is duplicated in orca-runtime.ts (the CLI/mobile worktree.rm path) 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.
  • No migration or persisted-state change; the fence is computed per-call from the store's existing host ownership.

…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.
@brennanb2025
brennanb2025 merged commit 9e5bd5f into main Aug 4, 2026
43 checks passed
@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Worktree 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)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: scoping SSH worktree deletion PTY teardown to the owning host.
Description check ✅ Passed The description covers the required sections, explains the change and risks, documents testing limitations, and confirms cross-platform review.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c7469b30-3b6e-4645-838d-a006b5b6d55e

📥 Commits

Reviewing files that changed from the base of the PR and between 73e7df7 and 37440ef.

📒 Files selected for processing (6)
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/runtime/missing-worktree-terminal-reconciliation.test.ts
  • src/main/runtime/missing-worktree-terminal-reconciliation.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts

Comment on lines +51 to +58
function hostFence(
repo: Repo,
worktreeId: string
): { resolvedWorktreeId: string; resolvedConnectionId?: string } {
return {
resolvedWorktreeId: worktreeId,
...(repo.connectionId ? { resolvedConnectionId: repo.connectionId } : {})
}

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.

🩺 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: derive resolvedRuntimeEnvironmentId from 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 expects resolvedRuntimeEnvironmentId.

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-L90
  • src/main/runtime/missing-worktree-terminal-reconciliation.ts#L115-L124
  • src/main/runtime/missing-worktree-terminal-reconciliation.test.ts#L67-L83
  • src/main/runtime/missing-worktree-terminal-reconciliation.test.ts#L107-L112

addedAt: 1,
connectionId: 'ssh-1'
}
const remoteStore = { ...store, getRepos: () => [remoteRepo], getRepo: () => remoteRepo }

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.

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

Comment on lines +23445 to +23472
// 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
}
: {})

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.

🎯 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 || true

Repository: 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))
}
JS

Repository: 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 || true

Repository: 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 || true

Repository: 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.

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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.

1 participant