Skip to content

Fix un-removable SSH ghost worktrees after host remove/re-add - #7753

Merged
Jinwoo-H merged 15 commits into
mainfrom
Jinwoo-H/ssh-fixes
Jul 8, 2026
Merged

Jinwoo-H merged 15 commits into
mainfrom
Jinwoo-H/ssh-fixes

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A user removed an SSH host that had broken, re-added it, and was left with grey "ghost" worktrees they couldn't delete. Deleting them failed with "Remote connection dropped. Click Reconnect on the SSH target before retrying" or spawning git ENOENT, because worktrees:remove throws at requireSshGitProvider before any cleanup runs when the target/provider is gone.

Root causes (two, both fixed)

  1. Re-adding a host never re-associated its orphaned workspaces. Every SSH target gets a random id (ssh-${Date.now()}-…); removing a target deleted the target row but left every repo/worktree pinned to the dead id, and re-adding minted a new id with nothing linking the old workspaces to it. Association is purely by exact id, so the old workspaces became un-removable project-only ghost hosts.
  2. Removal had no local-only escape hatch, and the project-removal path (store.removeProject, repo-id-only) could over-delete a repo id shared across hosts.

What this does

Re-adoption (the primary fix). Removing a target now records an identity tombstone ({ oldTargetId, configHost, host, port, username }). Adding or importing a target whose identity matches (configHost alias first, then host+user+port) re-points orphaned repos/worktrees onto the new id (reassignSshTargetId), so workspaces reattach to the reconnected host. Tombstones are capped/deduped; runtime-owned (ephemeral-VM) targets are excluded. Matching is strict: two distinct config aliases sharing one endpoint do not steal each other's workspaces.

Forget escape hatch. New provider-free worktrees:forgetLocal IPC handler clears Orca's records (metadata, history, transient state, PTYs) without touching the SSH provider — so a ghost workspace can always be removed. New host-scoped removeProjectForHost / repos:removeForHost remove only the intended host's repo row when an id is shared across hosts (local / SSH / re-added target), avoiding cross-host data loss.

UX.

  • Deleting a workspace on a disconnected/ghost SSH host opens a dialog: Reconnect & Delete (hidden when the target is gone) / Remove from Orca (local-only, names the host, "remote files left untouched") / Cancel.
  • Removing an SSH host that still has workspaces offers Delete host & workspaces (real remote removal when connected) / Keep workspaces, remove host / Cancel, or, when offline, Remove host & forget workspaces. Unchanged when the host has no workspaces.

Adversarial review — findings fixed in this PR

A four-lens adversarial review (correctness, contract/persistence, remoting/parity, scenario) surfaced issues that are fixed here:

  • [High] Paired web/mobile clients misclassified every SSH repo as a ghost (empty sshTargetLabels), routing deletes to a local-only path that's unavailable there → SSH workspaces became undeletable on web/mobile. Now the SSH-forget interception is skipped on paired web clients; they keep their normal worktree.rm RPC path.
  • [High] Host-removal cleared the root repo via removeProject(id), which resolves by focused host — for a duplicate id it deleted the wrong (local) project and left the SSH ghost. Now an explicit hostId is threaded through so it targets the SSH row.
  • [Medium] The re-adoption tuple fallback could re-adopt across two distinct config aliases sharing host+user+port. Now blocked when both sides carry a (differing) alias.
  • [Medium] Host removal ignored per-workspace failures and removed the target anyway. Now it aborts and reports failure, keeping the host so the user can retry.
  • [Low] Fake pluralization ("1 workspace(s)") and a documented conservative meta-prune residual.

Persistence / backcompat

New removedSshTargetTombstones? field is optional with ?? guards on every access; old state files load cleanly and new files round-trip. IPC channels registered + removed, preload + web-shim + type surface all updated.

Tests

New/updated coverage: worktrees:forgetLocal never touches the SSH provider (even with no provider registered); host-scoped removeProjectForHost / reassignSshTargetId; re-adoption matching incl. the different-alias/same-endpoint case; per-workspace + host-remove resolution helpers; explicit-hostId project removal targets the right host. Full affected suites green; typecheck, oxlint, max-lines ratchet, and localization coverage all pass.

Not committed: PR evidence images (none).

Made with Orca 🐋

When a user removed a broken SSH host and re-added it, old grey worktrees
stayed pinned to the dead target id and could not be deleted: worktrees:remove
threw at requireSshGitProvider before any cleanup ran.

Two root causes, both fixed:

- Re-add never re-associated orphaned workspaces. Removing a target now records
  an identity tombstone; adding/importing a target with matching identity
  (configHost alias, else host+user+port) re-points orphaned repos/worktrees
  onto the new id (reassignSshTargetId), so workspaces reattach to the live host.
- Removal had no local-only escape hatch. New worktrees:forgetLocal IPC handler
  clears Orca records without touching the SSH provider; new host-scoped
  removeProjectForHost/repos:removeForHost avoids over-deleting a repo id shared
  across hosts.

UX: per-workspace delete on a disconnected/ghost SSH host offers Reconnect &
Delete / Remove from Orca / Cancel; host removal accounts for its workspaces.

Review fixes: skip the SSH-forget interception on paired web/mobile clients
(they have no SSH host state and would misroute to an unavailable local path);
thread an explicit hostId through removeProject so host removal targets the SSH
row not the focused host; the re-adoption tuple fallback no longer matches
across two distinct config aliases sharing an endpoint; host removal aborts and
reports failure instead of removing the target when a workspace fails to clear.

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 7, 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

Changes

This PR adds host-scoped repo removal and SSH workspace forget flows across main, preload, and renderer code. Persistence now tracks removed SSH target tombstones, supports host-specific repo pruning, and can reassign orphaned records when an SSH target is re-added. Renderer store and dialogs add host-aware removal, local-only worktree forgetting, and SSH-specific resolution paths. IPC and preload expose the new channels, and tests cover the new persistence, IPC, and renderer behavior.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately captures the main change: fixing ghost worktrees after SSH host re-addition.
Description check ✅ Passed It covers the main problem, fix, testing, review, security, and notes content, though not with the exact template headings.
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.

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: 8

🧹 Nitpick comments (5)
src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts (1)

1-61: 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy lift

Missing test coverage for this critical failure-aggregation path.

Unlike ssh-host-remove-resolution.ts, this file has no accompanying test. Given its role in deciding whether an SSH target is safe to remove (based on failedIds), a regression here directly risks reintroducing ghost repos/worktrees. Consider adding unit tests covering: successful clear in both modes, a failing removeWorktree, and a failing removeProject.

src/renderer/src/components/sidebar/HostRemoveDialog.tsx (2)

91-147: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant setBusy(null) before early return.

Lines 111-113 explicitly clear busy before returning on the failure path, but the finally block (lines 142-146) also runs on that same path and clears it again. The early call is dead weight; the finally already guarantees cleanup.

♻️ Proposed simplification
         if (failedIds.length > 0) {
-          if (mountedRef.current) {
-            setBusy(null)
-          }
           toast.error(

91-98: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

mode and busyKey are always identical at every call site.

runSshRemoval takes both mode and busyKey as separate parameters, but every caller (lines 232, 245, 256) passes the same value for both. Consider deriving busyKey from mode inside the function to remove the duplicated argument.

Also applies to: 227-260

src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.tsx (1)

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

Arbitrary font size bypasses design tokens.

text-[11px] is a custom bracket value not on the standard Tailwind text scale (closest token is text-xs). As per path instructions, UI work under src/renderer/src/**/*.{ts,tsx,css} should "use the design tokens... instead of inventing new colors, font sizes, or shadow tiers when existing documented values cover the need."

🎨 Proposed fix
-        <p className="text-[11px] leading-snug text-muted-foreground">{forgetDescription}</p>
+        <p className="text-xs leading-snug text-muted-foreground">{forgetDescription}</p>

Source: Coding guidelines

src/main/ssh/ssh-connection-store.ts (1)

34-43: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Fragile shared-state pattern for surfacing lastReadoptedRepoCount.

Exposing the last operation's result via a mutable instance field that the IPC layer reads-then-resets works today because both addTarget and importFromSshConfig (and their IPC handlers) are fully synchronous, but it's an implicit contract that would silently break if either becomes async or gains an await before the notify call. Consider returning the count alongside the result (e.g. { target, readoptedCount }) instead of a side-channel field.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a43a4572-f5a1-4ebb-bce9-7499283880fd

📥 Commits

Reviewing files that changed from the base of the PR and between d8df9c8 and 40ff6fe.

📒 Files selected for processing (29)
  • src/main/ipc/repos.ts
  • src/main/ipc/ssh.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/ssh/ssh-connection-store.test.ts
  • src/main/ssh/ssh-connection-store.ts
  • src/main/ssh/ssh-target-readoption.test.ts
  • src/main/ssh/ssh-target-readoption.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.tsx
  • src/renderer/src/components/sidebar/HostRemoveDialog.tsx
  • src/renderer/src/components/sidebar/delete-worktree-flow.ts
  • src/renderer/src/components/sidebar/index.tsx
  • src/renderer/src/components/sidebar/ssh-host-remove-resolution.test.ts
  • src/renderer/src/components/sidebar/ssh-host-remove-resolution.ts
  • src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts
  • src/renderer/src/components/sidebar/ssh-workspace-forget-resolution.test.ts
  • src/renderer/src/components/sidebar/ssh-workspace-forget-resolution.ts
  • src/renderer/src/store/slices/repos-host-identity-routing.test.ts
  • src/renderer/src/store/slices/repos.ts
  • src/renderer/src/store/slices/ui.ts
  • src/renderer/src/store/slices/worktree-helpers.ts
  • src/renderer/src/store/slices/worktrees.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/ssh-types.ts
  • src/shared/types.ts

Comment thread src/main/persistence.ts Resolved
Comment thread src/main/ssh/ssh-target-readoption.ts Resolved
Comment thread src/renderer/src/store/slices/repos.ts Resolved
Jinwoo-H and others added 2 commits July 7, 2026 19:33
Explain the orphaned state in the user's terms ('no longer connected to a
live host') and name the host, so it's clear why the workspace can only be
removed from Orca. Fold the 'remote untouched' reassurance into that copy and
drop the now-redundant secondary line on the ghost path.

Co-authored-by: Orca <[email protected]>
E2E testing surfaced a renderer bug: after re-adoption re-points a repo from
the old (removed) SSH target id to a re-added one, the renderer's per-host repo
merge preserved the stale row on the dead id (it looks like 'another host').
A terminal pane bound to that ghost row then failed with 'SSH target not found'.

Prune a repo row when it targets an SSH connection that is no longer a known
target AND the same repo id also exists on a live host (the re-adoption
sibling). A lone project-only ghost — repo id only on the dead host, no live
sibling — is deliberately kept so it can still be surfaced and forgotten.
Runtime-owned SSH rows are never pruned.

Co-authored-by: Orca <[email protected]>

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

♻️ Duplicate comments (1)
src/renderer/src/store/slices/repos.ts (1)

2577-2589: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Derive the runtime target from ownerHostId — still unresolved.

ownerRepo now honors options?.hostId via findRepoForHost, but target still comes from settingsForRepoOwner(get(), projectId), which ignores the explicit host. When duplicate repo IDs exist across hosts, this can route repo.rm to the focused runtime instead of the intended one, deleting the wrong remote row. Pass ownerHostId into target selection (e.g., getProjectSetupRuntimeTarget(ownerHostId)) or derive the target from ownerRepo directly.

This was previously flagged and remains unaddressed.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 45420952-72f8-4ec2-96f6-00678fa2674e

📥 Commits

Reviewing files that changed from the base of the PR and between 048debd and 2933e82.

📒 Files selected for processing (3)
  • src/renderer/src/store/slices/repos.ts
  • src/renderer/src/store/slices/superseded-ssh-repo-rows.test.ts
  • src/renderer/src/store/slices/superseded-ssh-repo-rows.ts

E2E: a workspace pinned to a removed SSH target showed the reconnect overlay
with a 'Connect' button that always failed ('SSH target not found'), because
the overlay decided its action purely from connection status and had no notion
of the target being gone.

When the target is no longer a known SSH target, show an 'SSH host removed'
state with a 'Remove workspace' action (routing through the normal delete flow
-> forget dialog) instead of a dead Connect button. Runtime-owned targets are
unaffected.

Co-authored-by: Orca <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.tsx (1)

151-162: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

"Remove workspace" button uses neutral outline styling for a destructive action.

The button triggers runWorktreeDelete, which ultimately deletes the workspace record. Consider using a destructive variant (if one exists in the design system) to visually distinguish this from the benign "Connect" action it replaces, consistent with how other destructive actions are styled elsewhere in the app.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 44c3bc46-1a01-4434-bab2-8752bd147739

📥 Commits

Reviewing files that changed from the base of the PR and between 2933e82 and d8cb591.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/TerminalPane.tsx
  • src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.test.tsx
  • src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.tsx

The terminal PTY auto-reattach path called ssh:connect for the workspace's
connectionId even after the target was removed, failing with 'SSH target not
found' and surfacing a red 'please file an issue' banner for what is an
expected user action.

Skip reattach when the connectionId is no longer a known SSH target (a real,
populated target map that omits it). The 'SSH host removed' overlay already
gives the user a clear state and a remove action. Runtime-owned targets and
not-yet-hydrated label maps are exempt.

Co-authored-by: Orca <[email protected]>

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0bf29ca8-8c07-49c5-951f-5c093e50c205

📥 Commits

Reviewing files that changed from the base of the PR and between d8cb591 and 031a623.

📒 Files selected for processing (1)
  • src/renderer/src/components/terminal-pane/pty-connection.ts

Jinwoo-H and others added 10 commits July 7, 2026 20:44
The sidebar host menu routed removal through the workspace-aware HostRemoveDialog,
but the SSH settings pane used a plain confirm that silently orphaned the host's
workspaces. Route the settings-pane remove through the same HostRemoveDialog when
the target still owns workspaces (falling back to the plain confirm otherwise),
so both entry points offer the same delete/keep choice.

Also dedupe repo/worktree ids in resolveSshHostRemoval so a transient duplicate
store row can't inflate the workspace count or double-remove a worktree.

Co-authored-by: Orca <[email protected]>
…dvanced

The host-removal dialog crammed three buttons in a row and made 'Delete host &
workspaces' the primary red action, signalling destruction as the default.

Redesign: the default primary is now just 'Remove host' (keeps workspaces,
reversible). Deleting/forgetting the host's workspaces moves behind an Advanced
disclosure (matching the create-workspace modal) as an opt-in checkbox with a
'cannot be undone' warning; ticking it re-labels the primary to the destructive
variant. Clean two-button footer (Cancel + primary).

Co-authored-by: Orca <[email protected]>
Replace the bordered-card + checkbox with the same borderless ghost 'Advanced'
header + grid-rows collapse + toggle switch used by the New Workspace composer,
so the disclosure looks consistent with the rest of the app. Switch turns red
(destructive) when the workspace-deletion opt-in is enabled.

Co-authored-by: Orca <[email protected]>
Make the workspace-deletion toggle use the neutral foreground color (not red),
and always label the confirm button 'Remove host' regardless of the toggle
state instead of switching to a longer conditional label.

Co-authored-by: Orca <[email protected]>
Deleting a workspace on a connected SSH host always removed the remote git
worktree, with no way to just declutter Orca while keeping the remote. Route
connected-SSH deletes to a new dialog whose default is 'Remove from Orca' only
(keeps the remote worktree/branch), with a gated 'Also delete on the remote'
toggle to opt into the destructive remote removal.

The second toggle is disabled until 'Remove from Orca' is on, and Delete is
disabled if neither would do anything. Reuses the provider-free forgetLocal for
the keep-remote path and the normal removal for the delete-remote path.

Co-authored-by: Orca <[email protected]>
'Also delete these N workspaces on the remote' read awkwardly; use the host
label — 'Also delete these N workspaces on «host»' — consistent with the rest
of the dialog.

Co-authored-by: Orca <[email protected]>
The re-adoption tombstones already store each removed target's label, but the
renderer had no access to it, so ghost-host UI fell back to the raw
ssh-<ts>-<rand> id. Expose removed-target labels via ssh:listRemovedTargetLabels,
hydrate a removedSshTargetLabels store map, and use it as a fallback in:
- the terminal 'SSH host removed' overlay
- the forget-workspace dialog
- the Remove Project dialog, which now says an SSH project's files stay on the
  named host and can be recovered by re-adding it (instead of the misleading
  'still on your disk').

Co-authored-by: Orca <[email protected]>
- Re-adoption tuple bypass (Major): treat configHost === host as no alias, so a
  manual add (which defaults configHost to host) can't reattach workspaces to a
  different account/port on the same host. Falls back to host+user+port. +tests.
- persistence.reassignSshTargetId (Major): persist worktree-meta-only re-points
  (repoCount === 0) by tracking metaChanged; keep host-setup sync repo-gated. +test.
- clearSshHostWorkspaces (Major): removeProject swallows its errors, so verify the
  host's repo row is actually gone and mark it failed if it lingers.
- removeProject target (Major): derive the runtime target from the resolved owner
  host (getProjectSetupRuntimeTarget) instead of settingsForRepoOwner, so an
  explicit hostId routes repo.rm to the right host, not the focused one. +test update.
- superseded test name: 'keeps' -> 'drops' to match the assertion.
- Document why the ghost/disconnected forget path skips the lineage-children
  warning (forget-local is metadata-only, per-worktree; descendants stay
  independently forgettable, not orphaned).

Co-authored-by: Orca <[email protected]>
removeProject now derives the runtime target via settingsForRepoOwner
(threaded with the explicit hostId) instead of getProjectSetupRuntimeTarget.
settingsForRepoOwner already pins runtime owners to their env and clears the
focused runtime for SSH/local owners, so an explicit SSH host removal still
routes local while focused-runtime repos route their repo.rm RPC. The prior
change ignored the focused runtime env for repos with no explicit
executionHostId, breaking three runtime-routing tests.

Add an SSH-explicit-host removeProject regression test.

Co-authored-by: Orca <[email protected]>
@Jinwoo-H
Jinwoo-H merged commit 98bee1b into main Jul 8, 2026
2 checks passed
@Jinwoo-H
Jinwoo-H deleted the Jinwoo-H/ssh-fixes branch July 8, 2026 02:01
eviannaive added a commit to eviannaive/orca that referenced this pull request Jul 8, 2026
Registers 21 translation keys referenced by ForgetSshWorkspaceDialog,
HostRemoveDialog, RemoveFolderDialog, and TerminalSshReconnectOverlay
(added in stablyai#7753) that were never synced into en.json, and repairs key
parity across all locale catalogs. Mechanical output of
`pnpm run sync:localization-catalog`; fixes the currently failing
verify:localization-catalog lint step on main.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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