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

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-07-07 19:01:42 -07:00
committed by GitHub
co-authored by Orca
parent 7385494560
commit 98bee1b419
39 changed files with 2230 additions and 98 deletions
+17
View File
@@ -1118,6 +1118,7 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v
ipcMain.removeHandler('repos:list')
ipcMain.removeHandler('repos:add')
ipcMain.removeHandler('repos:remove')
ipcMain.removeHandler('repos:removeForHost')
ipcMain.removeHandler('repos:reorder')
ipcMain.removeHandler('repos:update')
ipcMain.removeHandler('projects:list')
@@ -1926,6 +1927,22 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v
notifyReposChanged(mainWindow)
})
// Why: forget a project on a single execution host without disturbing the
// same repo id on other hosts (local or a re-added SSH target). Used by the
// SSH-workspace forget flow when a host is removed/disconnected.
ipcMain.handle(
'repos:removeForHost',
async (_event, args: { repoId: string; hostId: string }) => {
const hostId = normalizeExecutionHostId(args.hostId)
if (!hostId) {
throw new Error(`Invalid host ID: ${args.hostId}`)
}
store.removeProjectForHost(args.repoId, hostId)
invalidateAuthorizedRootsCache()
notifyReposChanged(mainWindow)
}
)
ipcMain.handle(
'repos:update',
(
+28 -2
View File
@@ -51,6 +51,7 @@ let currentRuntime: OrcaRuntimeService | undefined
const SSH_IPC_CHANNELS = [
'ssh:listTargets',
'ssh:listRemovedTargetLabels',
'ssh:addTarget',
'ssh:updateTarget',
'ssh:removeTarget',
@@ -695,12 +696,35 @@ export function registerSshHandlers(
// ── Target CRUD ────────────────────────────────────────────────────
// Why: SSH target add/import can re-adopt workspaces orphaned on a removed
// target id (see ssh-target-readoption). When that re-points repos, the
// renderer must refresh its repo list to surface the reattached workspaces.
function notifyReposChangedIfReadopted(): void {
if (!sshStore || sshStore.lastReadoptedRepoCount <= 0) {
return
}
sshStore.lastReadoptedRepoCount = 0
const win = getCurrentMainWindow()
if (win && !win.isDestroyed()) {
win.webContents.send('repos:changed')
}
}
ipcMain.handle('ssh:listTargets', () => {
return sshStore!.listTargets()
})
ipcMain.handle('ssh:listRemovedTargetLabels', () => {
return sshStore!.listRemovedTargetLabels()
})
ipcMain.handle('ssh:addTarget', (_event, args: { target: Omit<SshTarget, 'id'> }) => {
return sshStore!.addTarget(args.target)
const target = sshStore!.addTarget(args.target)
// Why: re-adding a removed host can re-adopt orphaned workspaces (re-point
// repos/worktrees off the dead id). Refresh the renderer's repo list so the
// reattached workspaces move from grey ghosts back onto the live host.
notifyReposChangedIfReadopted()
return target
})
ipcMain.handle(
@@ -715,7 +739,9 @@ export function registerSshHandlers(
})
ipcMain.handle('ssh:importConfig', (_event, args?: { reAdopt?: boolean }) => {
return sshStore!.importFromSshConfig(args)
const result = sshStore!.importFromSshConfig(args)
notifyReposChangedIfReadopted()
return result
})
// ── Connection lifecycle ───────────────────────────────────────────
+76
View File
@@ -7946,4 +7946,80 @@ describe('registerWorktreeHandlers', () => {
expect(store.setWorktreeMeta).not.toHaveBeenCalled()
expect(createSetupRunnerScriptMock).not.toHaveBeenCalled()
})
describe('worktrees:forgetLocal', () => {
it('forgets a workspace pinned to a removed SSH target without touching the provider', async () => {
const repo = {
id: 'repo-1',
path: '/workspace/repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0,
connectionId: 'ssh-dead',
worktreeBaseRef: null
}
const ptyProvider = {} as never
const worktreeId = 'repo-1::/workspace/feature-wt'
store.getRepo.mockReturnValue(repo)
getLocalPtyProviderMock.mockReturnValue(ptyProvider)
// Why: a removed/disconnected SSH target has no live provider; forgetLocal
// must not reach for one.
getSshGitProviderMock.mockReturnValue(undefined)
const result = await handlers['worktrees:forgetLocal'](null, { worktreeId })
expect(result).toEqual({})
expect(killAllProcessesForWorktreeMock).toHaveBeenCalledWith(worktreeId, {
runtime: runtimeStub,
localProvider: ptyProvider,
onPtyStopped: clearProviderPtyStateMock
})
expect(runtimeStub.clearOptimisticReconcileToken).toHaveBeenCalledWith(worktreeId)
expect(store.removeWorktreeMeta).toHaveBeenCalledWith(worktreeId)
expect(advertisedUrlWatcherForgetWorktreeMock).toHaveBeenCalledWith(worktreeId)
expect(deleteWorktreeHistoryDirMock).toHaveBeenCalledWith(worktreeId)
expect(mainWindow.webContents.send).toHaveBeenCalledWith('worktrees:changed', {
repoId: 'repo-1'
})
// The whole point: local-only cleanup never dispatches to the SSH provider.
expect(getSshGitProviderMock).not.toHaveBeenCalled()
expect(getSshFilesystemProviderMock).not.toHaveBeenCalled()
expect(listWorktreesMock).not.toHaveBeenCalled()
expect(removeWorktreeMock).not.toHaveBeenCalled()
})
it('throws when the repo is missing', async () => {
store.getRepo.mockReturnValue(undefined)
await expect(
handlers['worktrees:forgetLocal'](null, {
worktreeId: 'repo-gone::/workspace/feature-wt'
})
).rejects.toThrow(/Repo not found/)
expect(store.removeWorktreeMeta).not.toHaveBeenCalled()
expect(getSshGitProviderMock).not.toHaveBeenCalled()
})
it('rejects forgetting a folder project root', async () => {
const repo = {
id: 'repo-folder',
path: '/workspace/folder',
displayName: 'folder',
badgeColor: '#000',
addedAt: 0,
kind: 'folder' as const
}
store.getRepo.mockReturnValue(repo)
await expect(
handlers['worktrees:forgetLocal'](null, {
worktreeId: `${repo.id}::${repo.path}`
})
).rejects.toThrow(/project root workspace/)
expect(store.removeWorktreeMeta).not.toHaveBeenCalled()
expect(deleteWorktreeHistoryDirMock).not.toHaveBeenCalled()
})
})
})
+62
View File
@@ -931,6 +931,7 @@ export function registerWorktreeHandlers(
ipcMain.removeHandler('worktrees:resolvePrBase')
ipcMain.removeHandler('worktrees:resolveMrBase')
ipcMain.removeHandler('worktrees:remove')
ipcMain.removeHandler('worktrees:forgetLocal')
ipcMain.removeHandler('worktrees:forceDeletePreservedBranch')
ipcMain.removeHandler('worktrees:updateMeta')
ipcMain.removeHandler('worktrees:listLineage')
@@ -1807,6 +1808,67 @@ export function registerWorktreeHandlers(
}
)
// Why: forget-locally drops a workspace from Orca without any remote Git or
// filesystem work. It exists so a workspace pinned to a removed/disconnected
// SSH target — whose provider is gone and whose `worktrees:remove` therefore
// throws at requireSshGitProvider before any cleanup runs — can still be
// cleared from the app. It never touches the remote: no worktree registration,
// no branches, no files are deleted there.
ipcMain.handle(
'worktrees:forgetLocal',
async (_event, args: { worktreeId: string }): Promise<RemoveWorktreeResult> => {
// Why: share the removal in-flight map (not a separate one) so a concurrent
// worktrees:remove and worktrees:forgetLocal on the same id cannot both
// mutate metadata. A forget takes no force/skipArchive options.
const optionsKey = 'forget-local'
const inFlight = worktreeRemovalsInFlight.get(args.worktreeId)
if (inFlight) {
if (inFlight.optionsKey === optionsKey) {
return inFlight.promise
}
throw new Error(`Worktree deletion already in progress: ${args.worktreeId}`)
}
const forget = (async (): Promise<RemoveWorktreeResult> => {
const { repoId } = parseWorktreeId(args.worktreeId)
const repo = store.getRepo(repoId)
if (!repo) {
throw new Error(`Repo not found: ${repoId}`)
}
if (isFolderRepo(repo) && args.worktreeId === getFolderWorkspaceRootId(repo)) {
throw new Error(
'Cannot delete the project root workspace. Remove the folder project instead.'
)
}
// Why: best-effort PTY sweep. killAllProcessesForWorktree resolves
// synchronously for a dead SSH relay (the provider tombstones the lease
// and returns without awaiting the remote), so this never hangs.
await killAllProcessesForWorktree(args.worktreeId, {
runtime,
localProvider: getLocalPtyProvider(),
onPtyStopped: clearProviderPtyState
}).catch((err) => {
console.warn(`[worktree-teardown] forget-local failed for ${args.worktreeId}:`, err)
})
runtime.clearOptimisticReconcileToken(args.worktreeId)
removeWorktreeMetadataAndTransientState(store, args.worktreeId)
preservedBranchCleanupByWorktreeId.delete(args.worktreeId)
notifyWorktreesChanged(mainWindow, repoId)
return {}
})()
worktreeRemovalsInFlight.set(args.worktreeId, { optionsKey, promise: forget })
try {
return await forget
} finally {
if (worktreeRemovalsInFlight.get(args.worktreeId)?.promise === forget) {
worktreeRemovalsInFlight.delete(args.worktreeId)
}
}
}
)
ipcMain.handle(
'worktrees:forceDeletePreservedBranch',
async (
+130
View File
@@ -3058,6 +3058,136 @@ describe('Store', () => {
expect(store.getWorktreeLineage('r2::/other')).toBeDefined()
})
// ── 6b. removeProjectForHost is host-scoped ───────────────────────────
it('removeProjectForHost removes only the target host row for a shared repo id', async () => {
const store = await createStore()
// Same repo id on both local and an SSH host.
store.addRepo(makeRepo({ id: 'shared', path: '/local/repo' }))
store.addRepo(
makeRepo({
id: 'shared',
path: '/remote/repo',
connectionId: 'ssh-old',
executionHostId: 'ssh:ssh-old'
})
)
store.setWorktreeMeta('shared::/local/repo/wt', { displayName: 'local-wt', hostId: 'local' })
store.setWorktreeMeta('shared::/remote/repo/wt', {
displayName: 'remote-wt',
hostId: 'ssh:ssh-old'
})
store.removeProjectForHost('shared', 'ssh:ssh-old')
const remaining = store.getRepos().filter((r) => r.id === 'shared')
expect(remaining).toHaveLength(1)
expect(remaining[0].path).toBe('/local/repo')
// Local worktree meta survives; the SSH host's meta is pruned.
expect(store.getWorktreeMeta('shared::/local/repo/wt')).toBeDefined()
expect(store.getWorktreeMeta('shared::/remote/repo/wt')).toBeUndefined()
})
it('removeProjectForHost prunes the SSH host meta (tagged hostId) for a shared id', async () => {
const store = await createStore()
store.addRepo(makeRepo({ id: 'shared', path: '/local/repo' }))
store.addRepo(
makeRepo({
id: 'shared',
path: '/remote/repo',
connectionId: 'ssh-old',
executionHostId: 'ssh:ssh-old'
})
)
// SSH worktree meta correctly carries hostId (the normal, stamped case).
store.setWorktreeMeta('shared::/remote/repo/wt', {
displayName: 'remote-wt',
hostId: 'ssh:ssh-old'
})
// A hostId-less meta under the same id is treated as local and left behind
// (conservative: never deletes the wrong host's meta).
store.setWorktreeMeta('shared::/local/repo/wt', { displayName: 'local-wt' })
store.removeProjectForHost('shared', 'ssh:ssh-old')
expect(store.getWorktreeMeta('shared::/remote/repo/wt')).toBeUndefined()
expect(store.getWorktreeMeta('shared::/local/repo/wt')).toBeDefined()
})
it('removeProjectForHost prunes everything when the id exists on no other host', async () => {
const store = await createStore()
store.addRepo(makeRepo({ id: 'only', connectionId: 'ssh-x', executionHostId: 'ssh:ssh-x' }))
store.setWorktreeMeta('only::/repo/wt', { displayName: 'wt', hostId: 'ssh:ssh-x' })
store.removeProjectForHost('only', 'ssh:ssh-x')
expect(store.getRepo('only')).toBeUndefined()
expect(store.getWorktreeMeta('only::/repo/wt')).toBeUndefined()
})
// ── 6c. reassignSshTargetId re-adopts orphaned workspaces ─────────────
it('reassignSshTargetId re-points repos and worktree metas onto the new id', async () => {
const store = await createStore()
store.addRepo(makeRepo({ id: 'r1', connectionId: 'ssh-old', executionHostId: 'ssh:ssh-old' }))
store.setWorktreeMeta('r1::/repo/wt', { displayName: 'wt', hostId: 'ssh:ssh-old' })
const count = store.reassignSshTargetId('ssh-old', 'ssh-new')
expect(count).toBe(1)
const repo = store.getRepo('r1')!
expect(repo.connectionId).toBe('ssh-new')
expect(repo.executionHostId).toBe('ssh:ssh-new')
expect(store.getWorktreeMeta('r1::/repo/wt')!.hostId).toBe('ssh:ssh-new')
})
it('reassignSshTargetId leaves repos on other hosts untouched', async () => {
const store = await createStore()
store.addRepo(makeRepo({ id: 'local-repo', path: '/local' }))
store.addRepo(
makeRepo({
id: 'ssh-repo',
path: '/remote',
connectionId: 'ssh-old',
executionHostId: 'ssh:ssh-old'
})
)
const count = store.reassignSshTargetId('ssh-old', 'ssh-new')
expect(count).toBe(1)
expect(store.getRepo('local-repo')!.connectionId).toBeUndefined()
expect(store.getRepo('ssh-repo')!.connectionId).toBe('ssh-new')
})
it('reassignSshTargetId re-points a repo that only carries connectionId (no executionHostId)', async () => {
const store = await createStore()
// SSH repos created via addRemoteRepoFromPath leave executionHostId unset.
store.addRepo(makeRepo({ id: 'r1', connectionId: 'ssh-old' }))
const count = store.reassignSshTargetId('ssh-old', 'ssh-new')
expect(count).toBe(1)
const repo = store.getRepo('r1')!
expect(repo.connectionId).toBe('ssh-new')
// Must not stamp an executionHostId where there wasn't one.
expect(repo.executionHostId).toBeUndefined()
})
it('reassignSshTargetId persists a worktree-meta-only re-point (no matching repo)', async () => {
const store = await createStore()
// A meta on the old SSH host with no corresponding repo row — the re-point
// must still be saved, not left in memory only.
store.setWorktreeMeta('r1::/remote/wt', { displayName: 'wt', hostId: 'ssh:ssh-old' })
const count = store.reassignSshTargetId('ssh-old', 'ssh-new')
expect(count).toBe(0) // no repo matched
store.flush()
const reloaded = await createStore()
expect(reloaded.getWorktreeMeta('r1::/remote/wt')?.hostId).toBe('ssh:ssh-new')
})
// ── 7. updateRepo ──────────────────────────────────────────────────
it('updateRepo modifies the repo in place', async () => {
+142 -6
View File
@@ -82,6 +82,7 @@ import { MOBILE_PAIRING_USERDATA_FILES } from './runtime/mobile-pairing-files'
import { hardenExistingSecureFile } from '../shared/secure-file'
import {
LEGACY_DEFAULT_SSH_RELAY_GRACE_PERIOD_SECONDS,
type RemovedSshTargetTombstone,
type SshRemotePtyLease,
type SshTarget
} from '../shared/ssh-types'
@@ -108,6 +109,7 @@ import {
normalizeExecutionHostOrder,
normalizeExecutionHostId,
normalizeVisibleExecutionHostIds,
toSshExecutionHostId,
type ExecutionHostId
} from '../shared/execution-host'
import { toRelaySshPtyId } from './providers/ssh-pty-id'
@@ -2181,6 +2183,10 @@ function remapAcknowledgedAgentPaneKeys(
// handful of Claude sessions a daemon can realistically keep alive.
const MAX_CLAUDE_LIVE_PTY_SESSION_IDS = 200
// Why: bound the removed-SSH-target history so remove/re-add churn can't grow
// the state file without limit. Re-adoption only needs recent removals.
const MAX_REMOVED_SSH_TARGET_TOMBSTONES = 50
function normalizeClaudeLivePtySessionIds(value: unknown): string[] {
if (!Array.isArray(value)) {
return []
@@ -4172,30 +4178,84 @@ export class Store {
// Why: presets are repo-scoped, so removing the repo means the presets
// can never be referenced again — drop them with the parent.
delete this.state.sparsePresetsByRepo[id]
// Clean up worktree meta for this repo
this.pruneWorktreeStateForRepo(id, null)
this.scheduleSave()
}
// Why: the same repo id can exist on more than one execution host (local, an
// SSH target, a re-added SSH target). Forgetting one host's copy must remove
// only that host's repo row and worktree metadata — never the local or
// another host's records that happen to share the id.
removeProjectForHost(id: string, hostId: ExecutionHostId): void {
this.state.repos = this.state.repos.filter(
(r) => !(r.id === id && getRepoExecutionHostId(r) === hostId)
)
const idStillPresent = this.state.repos.some((r) => r.id === id)
// Why: presets are repo-id-scoped (not host-scoped); only drop them once the
// last host's copy of this repo is gone, or a surviving host loses its presets.
if (!idStillPresent) {
delete this.state.sparsePresetsByRepo[id]
}
this.syncProjectHostSetupCompatibilityState()
// Why: if the id survives on another host, prune only this host's worktree
// metas; otherwise prune everything for the id (matches removeProject).
this.pruneWorktreeStateForRepo(id, idStillPresent ? hostId : null)
this.scheduleSave()
}
// Clean up worktree meta, lineage, and workspace lineage for a repo id.
// When hostId is null, prune all of the repo's entries; when a hostId is
// given, prune only entries whose meta.hostId resolves to that host (a
// missing hostId is treated as local).
private pruneWorktreeStateForRepo(id: string, hostId: ExecutionHostId | null): void {
const prefix = `${id}::`
// Why: snapshot host membership up front. Lineage pruning below checks the
// meta.hostId of worktree keys that may already have been deleted from
// worktreeMeta in the first loop, so reading hostId live would misclassify
// an SSH worktree as local once its meta is gone.
const hostMembership = new Map<string, boolean>()
const belongsToHost = (key: string): boolean => {
if (!key.startsWith(prefix)) {
return false
}
if (hostId === null) {
return true
}
const cached = hostMembership.get(key)
if (cached !== undefined) {
return cached
}
// Why default to local: worktree metas created on/after host-ownership
// stamping carry hostId. A metas without it predates that and is treated as
// local, so a host-scoped (non-local) prune conservatively leaves it — it
// may leak a stale entry for a legacy SSH worktree sharing a repo id with a
// local repo, but it never deletes the wrong host's live meta.
const metaHostId = this.state.worktreeMeta[key]?.hostId ?? LOCAL_EXECUTION_HOST_ID
const result = metaHostId === hostId
hostMembership.set(key, result)
return result
}
for (const key of Object.keys(this.state.worktreeMeta)) {
if (key.startsWith(prefix)) {
if (belongsToHost(key)) {
delete this.state.worktreeMeta[key]
}
}
for (const [childId, lineage] of Object.entries(this.state.worktreeLineageById)) {
if (childId.startsWith(prefix) || lineage.parentWorktreeId.startsWith(prefix)) {
if (belongsToHost(childId) || belongsToHost(lineage.parentWorktreeId)) {
delete this.state.worktreeLineageById[childId]
}
}
for (const [childKey, lineage] of Object.entries(this.state.workspaceLineageByChildKey)) {
const childScope = parseWorkspaceKey(childKey)
const parentScope = parseWorkspaceKey(lineage.parentWorkspaceKey)
if (childScope?.type === 'worktree' && childScope.worktreeId.startsWith(prefix)) {
if (childScope?.type === 'worktree' && belongsToHost(childScope.worktreeId)) {
delete this.state.workspaceLineageByChildKey[childKey as WorkspaceKey]
continue
}
if (parentScope?.type === 'worktree' && parentScope.worktreeId.startsWith(prefix)) {
if (parentScope?.type === 'worktree' && belongsToHost(parentScope.worktreeId)) {
delete this.state.workspaceLineageByChildKey[childKey as WorkspaceKey]
}
}
this.scheduleSave()
}
updateRepo(
@@ -6006,6 +6066,82 @@ export class Store {
}
}
getRemovedSshTargetTombstones(): RemovedSshTargetTombstone[] {
return [...(this.state.removedSshTargetTombstones ?? [])]
}
addRemovedSshTargetTombstone(tombstone: RemovedSshTargetTombstone): void {
const existing = this.state.removedSshTargetTombstones ?? []
// Why: dedupe by oldTargetId so a remove/re-remove of the same id can't
// stack duplicate tombstones. Newest wins.
const filtered = existing.filter((t) => t.oldTargetId !== tombstone.oldTargetId)
// Cap the history so pathological churn can't grow the state file unbounded.
this.state.removedSshTargetTombstones = [...filtered, tombstone].slice(
-MAX_REMOVED_SSH_TARGET_TOMBSTONES
)
this.scheduleSave()
}
removeRemovedSshTargetTombstone(oldTargetId: string): void {
const existing = this.state.removedSshTargetTombstones
if (!existing?.some((t) => t.oldTargetId === oldTargetId)) {
return
}
this.state.removedSshTargetTombstones = existing.filter((t) => t.oldTargetId !== oldTargetId)
this.scheduleSave()
}
/**
* Re-point every repo and worktree meta pinned to a removed SSH target id
* onto a re-added target's id, so orphaned workspaces reattach to the live
* host instead of remaining un-removable ghosts. Returns the number of repos
* re-pointed (0 when nothing referenced the old id).
*/
reassignSshTargetId(oldTargetId: string, newTargetId: string): number {
if (oldTargetId === newTargetId) {
return 0
}
const oldHostId = toSshExecutionHostId(oldTargetId)
const newHostId = toSshExecutionHostId(newTargetId)
let repoCount = 0
for (const repo of this.state.repos) {
const matchesConnection = repo.connectionId === oldTargetId
const matchesHost = repo.executionHostId === oldHostId
if (!matchesConnection && !matchesHost) {
continue
}
if (matchesConnection) {
repo.connectionId = newTargetId
}
// Why: only rewrite executionHostId when it was actually set to the old
// SSH host. SSH repos created via addRemoteRepoFromPath leave it unset and
// derive the host from connectionId, so we must not stamp a value where
// there wasn't one.
if (matchesHost) {
repo.executionHostId = newHostId
}
repoCount++
}
// Re-point worktree metas whose hostId pointed at the old SSH host.
let metaChanged = false
for (const meta of Object.values(this.state.worktreeMeta)) {
if (meta.hostId === oldHostId) {
meta.hostId = newHostId
metaChanged = true
}
}
// Why: repo-row rewrites can affect host-setup compatibility, but meta-only
// rewrites cannot — keep that sync under the repo gate. Persist whenever
// either repos OR metas changed, so meta-only re-points aren't lost on quit.
if (repoCount > 0) {
this.syncProjectHostSetupCompatibilityState()
}
if (repoCount > 0 || metaChanged) {
this.scheduleSave()
}
return repoCount
}
// ── SSH Remote PTY Leases ──────────────────────────────────────────
getSshRemotePtyLeases(targetId?: string): SshRemotePtyLease[] {
+157 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { SshConnectionStore } from './ssh-connection-store'
import type { SshTarget } from '../../shared/ssh-types'
import type { RemovedSshTargetTombstone, SshTarget } from '../../shared/ssh-types'
const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({
loadUserSshConfigMock: vi.fn(),
@@ -15,6 +15,8 @@ vi.mock('./ssh-config-parser', () => ({
function createMockStore() {
const targets: SshTarget[] = []
let deletedAliases: string[] = []
const removedTombstones: RemovedSshTargetTombstone[] = []
const reassignments: { oldTargetId: string; newTargetId: string }[] = []
return {
getSshTargets: vi.fn(() => [...targets]),
@@ -45,6 +47,24 @@ function createMockStore() {
}),
clearDeletedSshConfigAliases: vi.fn(() => {
deletedAliases = []
}),
removedTombstones,
reassignments,
getRemovedSshTargetTombstones: vi.fn(() => [...removedTombstones]),
addRemovedSshTargetTombstone: vi.fn((tombstone: RemovedSshTargetTombstone) => {
const filtered = removedTombstones.filter((t) => t.oldTargetId !== tombstone.oldTargetId)
removedTombstones.length = 0
removedTombstones.push(...filtered, tombstone)
}),
removeRemovedSshTargetTombstone: vi.fn((oldTargetId: string) => {
const kept = removedTombstones.filter((t) => t.oldTargetId !== oldTargetId)
removedTombstones.length = 0
removedTombstones.push(...kept)
}),
reassignSshTargetId: vi.fn((oldTargetId: string, newTargetId: string) => {
reassignments.push({ oldTargetId, newTargetId })
// Pretend one repo referenced the old id.
return 1
})
}
}
@@ -439,4 +459,140 @@ describe('SshConnectionStore', () => {
expect(result).toHaveLength(1)
})
})
describe('re-adoption of orphaned workspaces', () => {
it('records a tombstone when removing any user-facing target', () => {
mockStore.addSshTarget({
id: 'ssh-1',
label: 'Dev',
host: 'dev.example.com',
port: 22,
username: 'tim',
source: 'manual'
})
sshStore.removeTarget('ssh-1')
expect(mockStore.addRemovedSshTargetTombstone).toHaveBeenCalledWith(
expect.objectContaining({
oldTargetId: 'ssh-1',
host: 'dev.example.com',
port: 22,
username: 'tim'
})
)
})
it('does not tombstone runtime-owned targets', () => {
mockStore.addSshTarget({
id: 'runtime-ssh-abc',
label: 'VM',
host: 'vm.example.com',
port: 22,
username: 'tim',
owner: { type: 'on-demand-runtime', runtimeId: 'abc' }
})
sshStore.removeTarget('runtime-ssh-abc')
expect(mockStore.addRemovedSshTargetTombstone).not.toHaveBeenCalled()
})
it('re-adopts orphaned repos when the same host is re-added', () => {
// Simulate a prior removal by seeding a matching tombstone.
mockStore.addRemovedSshTargetTombstone({
oldTargetId: 'ssh-old',
host: 'dev.example.com',
port: 22,
username: 'tim',
label: 'Dev',
removedAt: 1
})
sshStore.addTarget({
label: 'Dev',
host: 'dev.example.com',
port: 22,
username: 'tim'
})
expect(mockStore.reassignSshTargetId).toHaveBeenCalledTimes(1)
const [oldId, newId] = mockStore.reassignSshTargetId.mock.calls[0]
expect(oldId).toBe('ssh-old')
expect(newId).toMatch(/^ssh-/)
// Re-adoption count surfaces so the IPC layer can refresh the repo list.
expect(sshStore.lastReadoptedRepoCount).toBe(1)
})
// Why: drive the real remove→re-add path so the tombstone carries the
// defaulted configHost (host) that buildRemovedSshTargetTombstone produces,
// rather than a hand-seeded tombstone without one.
it('re-adopts through an actual removeTarget then re-add of the same host', () => {
const added = sshStore.addTarget({
label: 'Dev',
host: 'dev.example.com',
port: 22,
username: 'tim'
})
sshStore.removeTarget(added.id)
// The tombstone was built from the real target (configHost defaulted to host).
const tombstones = mockStore.getRemovedSshTargetTombstones()
expect(tombstones).toHaveLength(1)
expect(tombstones[0]).toMatchObject({ oldTargetId: added.id, configHost: 'dev.example.com' })
mockStore.reassignSshTargetId.mockClear()
const readded = sshStore.addTarget({
label: 'Dev',
host: 'dev.example.com',
port: 22,
username: 'tim'
})
expect(mockStore.reassignSshTargetId).toHaveBeenCalledWith(added.id, readded.id)
expect(sshStore.lastReadoptedRepoCount).toBe(1)
})
// A different account on the SAME host must NOT re-adopt, even though both
// manual adds default configHost to the shared hostname.
it('does not re-adopt a different account on the same host', () => {
const alice = sshStore.addTarget({
label: 'alice',
host: 'dev.example.com',
port: 22,
username: 'alice'
})
sshStore.removeTarget(alice.id)
mockStore.reassignSshTargetId.mockClear()
sshStore.addTarget({
label: 'bob',
host: 'dev.example.com',
port: 2222,
username: 'bob'
})
expect(mockStore.reassignSshTargetId).not.toHaveBeenCalled()
})
it('does not re-adopt when the re-added host identity differs', () => {
mockStore.addRemovedSshTargetTombstone({
oldTargetId: 'ssh-old',
host: 'other.example.com',
port: 22,
username: 'root',
label: 'Other',
removedAt: 1
})
sshStore.addTarget({
label: 'Dev',
host: 'dev.example.com',
port: 22,
username: 'tim'
})
expect(mockStore.reassignSshTargetId).not.toHaveBeenCalled()
expect(sshStore.lastReadoptedRepoCount).toBe(0)
})
})
})
+36
View File
@@ -2,6 +2,10 @@ import type { Store } from '../persistence'
import type { SshTarget } from '../../shared/ssh-types'
import { RUNTIME_OWNED_SSH_TARGET_ID_PREFIX } from '../../shared/execution-host'
import { loadUserSshConfig, sshConfigHostsToTargets } from './ssh-config-parser'
import {
buildRemovedSshTargetTombstone,
readoptOrphanedWorkspacesForTarget
} from './ssh-target-readoption'
export class SshConnectionStore {
constructor(private store: Store) {}
@@ -10,6 +14,17 @@ export class SshConnectionStore {
return this.store.getSshTargets().filter((target) => !isRuntimeOwnedSshTarget(target))
}
/** Map of removed-target id → its last known label, from the re-adoption
* tombstones. Lets the renderer show a friendly host name for a workspace
* still pinned to a target that no longer exists. */
listRemovedTargetLabels(): Record<string, string> {
const labels: Record<string, string> = {}
for (const tombstone of this.store.getRemovedSshTargetTombstones()) {
labels[tombstone.oldTargetId] = tombstone.label
}
return labels
}
getTarget(id: string): SshTarget | undefined {
return this.store.getSshTarget(id)
}
@@ -27,9 +42,17 @@ export class SshConnectionStore {
// keep it — lift any tombstone so config sync stops suppressing this alias.
this.reclaimAlias(full.configHost ?? full.label)
this.store.addSshTarget(full)
// Why: re-adopt workspaces that were orphaned when the same host was removed
// (repos/worktrees still point at the old, now-dead target id). Track the
// count so the IPC layer knows whether to refresh the repo list.
this.lastReadoptedRepoCount = readoptOrphanedWorkspacesForTarget(this.store, full)
return full
}
/** Repos re-adopted by the most recent addTarget/importFromSshConfig call.
* Lets the IPC layer broadcast repos:changed only when workspaces reattached. */
lastReadoptedRepoCount = 0
upsertRuntimeOwnedTarget(
runtimeId: string,
target: Omit<SshTarget, 'id' | 'owner' | 'source' | 'lastRequiredPassphrase'>
@@ -75,6 +98,13 @@ export class SshConnectionStore {
this.store.addDeletedSshConfigAlias(alias)
}
}
// Why: record the removed target's host identity (for ALL user-facing
// targets, config-managed or manual) so a later re-add of the same host can
// re-adopt any workspaces orphaned on this id. Runtime-owned targets manage
// their own lifecycle and are never re-adopted.
if (target && !isRuntimeOwnedSshTarget(target)) {
this.store.addRemovedSshTargetTombstone(buildRemovedSshTargetTombstone(target, Date.now()))
}
this.store.removeSshTarget(id)
}
@@ -90,6 +120,7 @@ export class SshConnectionStore {
* manual targets. Returns the inserted and updated targets.
*/
importFromSshConfig(options?: { reAdopt?: boolean }): SshTarget[] {
let readoptedThisImport = 0
// Why: the explicit Import action re-adopts every config host, so it clears
// all tombstones first. The passive on-open sync passes no flag and keeps
// deleted hosts suppressed.
@@ -178,10 +209,15 @@ export class SshConnectionStore {
} else {
const inserted: SshTarget = { ...candidate, source: 'ssh-config' }
this.store.addSshTarget(inserted)
// Why: a freshly-inserted config host may be one the user removed and is
// now re-importing — re-adopt its orphaned workspaces. Updated-in-place
// targets keep their id, so their repos were never orphaned.
readoptedThisImport += readoptOrphanedWorkspacesForTarget(this.store, inserted)
changed.push(inserted)
}
}
this.lastReadoptedRepoCount = readoptedThisImport
return changed
}
}
+198
View File
@@ -0,0 +1,198 @@
import { describe, it, expect } from 'vitest'
import {
buildRemovedSshTargetTombstone,
readoptOrphanedWorkspacesForTarget
} from './ssh-target-readoption'
import type { Store } from '../persistence'
import type { RemovedSshTargetTombstone, SshTarget } from '../../shared/ssh-types'
function makeTarget(overrides: Partial<SshTarget> = {}): SshTarget {
return {
id: 'ssh-new',
label: 'Dev box',
host: 'dev.example.com',
port: 22,
username: 'tim',
...overrides
}
}
/** Minimal in-memory store exposing only what re-adoption touches. */
function makeFakeStore(tombstones: RemovedSshTargetTombstone[]) {
const reassigned: { oldId: string; newId: string }[] = []
let current = [...tombstones]
const store = {
getRemovedSshTargetTombstones: () => [...current],
removeRemovedSshTargetTombstone: (oldTargetId: string) => {
current = current.filter((t) => t.oldTargetId !== oldTargetId)
},
reassignSshTargetId: (oldTargetId: string, newTargetId: string) => {
reassigned.push({ oldId: oldTargetId, newId: newTargetId })
return 1
}
} as unknown as Store
return { store, reassigned, remaining: () => current }
}
const tombstone = (
overrides: Partial<RemovedSshTargetTombstone> = {}
): RemovedSshTargetTombstone => ({
oldTargetId: 'ssh-old',
host: 'dev.example.com',
port: 22,
username: 'tim',
label: 'Dev box',
removedAt: 1,
...overrides
})
describe('readoptOrphanedWorkspacesForTarget', () => {
it('re-adopts on matching configHost alias', () => {
const fake = makeFakeStore([tombstone({ configHost: 'devbox', host: 'changed.example.com' })])
const count = readoptOrphanedWorkspacesForTarget(
fake.store,
makeTarget({ configHost: 'devbox', host: 'now.example.com' })
)
expect(count).toBe(1)
expect(fake.reassigned).toEqual([{ oldId: 'ssh-old', newId: 'ssh-new' }])
expect(fake.remaining()).toHaveLength(0) // tombstone consumed
})
it('re-adopts on matching host+user+port when no alias', () => {
const fake = makeFakeStore([tombstone()])
const count = readoptOrphanedWorkspacesForTarget(fake.store, makeTarget())
expect(count).toBe(1)
expect(fake.reassigned).toEqual([{ oldId: 'ssh-old', newId: 'ssh-new' }])
})
it('does not re-adopt when identity differs', () => {
const fake = makeFakeStore([tombstone({ host: 'other.example.com', username: 'root' })])
const count = readoptOrphanedWorkspacesForTarget(
fake.store,
makeTarget({ host: 'dev.example.com', username: 'tim' })
)
expect(count).toBe(0)
expect(fake.reassigned).toEqual([])
expect(fake.remaining()).toHaveLength(1) // tombstone left for a future match
})
it('matches host/user/port case-insensitively', () => {
const fake = makeFakeStore([tombstone({ host: 'Dev.Example.COM', username: 'Tim' })])
const count = readoptOrphanedWorkspacesForTarget(
fake.store,
makeTarget({ host: 'dev.example.com', username: 'tim' })
)
expect(count).toBe(1)
})
it('does not match alias against a different host tuple', () => {
// Different alias AND different tuple => no match.
const fake = makeFakeStore([
tombstone({ configHost: 'prod', host: 'prod.example.com', username: 'root' })
])
const count = readoptOrphanedWorkspacesForTarget(
fake.store,
makeTarget({ configHost: 'devbox', host: 'dev.example.com', username: 'tim' })
)
expect(count).toBe(0)
})
it('is a no-op when there are no tombstones', () => {
const fake = makeFakeStore([])
expect(readoptOrphanedWorkspacesForTarget(fake.store, makeTarget())).toBe(0)
})
it('does NOT re-adopt across two different aliases that share host+user+port', () => {
// prod-deploy removed; prod-admin re-added — same box, different alias.
// These are deliberately distinct targets and must not steal workspaces.
const fake = makeFakeStore([
tombstone({ configHost: 'prod-deploy', host: 'prod.example.com', username: 'deploy' })
])
const count = readoptOrphanedWorkspacesForTarget(
fake.store,
makeTarget({ configHost: 'prod-admin', host: 'prod.example.com', username: 'deploy' })
)
expect(count).toBe(0)
expect(fake.reassigned).toEqual([])
expect(fake.remaining()).toHaveLength(1) // tombstone preserved
})
it('does NOT re-adopt a different account/port on the same host (implicit alias)', () => {
// Manual adds default configHost to host, so both carry configHost === host.
// That is NOT a real alias — matching on it alone would ignore port/username
// and reattach workspaces to the wrong SSH account on the same machine.
const fake = makeFakeStore([
tombstone({
configHost: 'dev.example.com',
host: 'dev.example.com',
port: 22,
username: 'alice'
})
])
const count = readoptOrphanedWorkspacesForTarget(
fake.store,
makeTarget({
configHost: 'dev.example.com',
host: 'dev.example.com',
port: 2222,
username: 'bob'
})
)
expect(count).toBe(0)
expect(fake.reassigned).toEqual([])
})
it('re-adopts the same account/host/port even with implicit configHost === host', () => {
const fake = makeFakeStore([
tombstone({
configHost: 'dev.example.com',
host: 'dev.example.com',
port: 22,
username: 'alice'
})
])
const count = readoptOrphanedWorkspacesForTarget(
fake.store,
makeTarget({
configHost: 'dev.example.com',
host: 'dev.example.com',
port: 22,
username: 'alice'
})
)
expect(count).toBe(1)
})
it('still re-adopts via tuple when the re-added target has no alias', () => {
// Manual re-add (no configHost) of a host that was config-managed: fall back
// to the tuple since one side lacks an alias to distinguish it.
const fake = makeFakeStore([
tombstone({ configHost: 'devbox', host: 'dev.example.com', username: 'tim' })
])
const count = readoptOrphanedWorkspacesForTarget(
fake.store,
makeTarget({ configHost: undefined, host: 'dev.example.com', username: 'tim' })
)
expect(count).toBe(1)
})
})
describe('buildRemovedSshTargetTombstone', () => {
it('captures identity fields and omits configHost when absent', () => {
const t = buildRemovedSshTargetTombstone(makeTarget(), 123)
expect(t).toEqual({
oldTargetId: 'ssh-new',
host: 'dev.example.com',
port: 22,
username: 'tim',
label: 'Dev box',
removedAt: 123
})
expect('configHost' in t).toBe(false)
})
it('includes configHost when present', () => {
const t = buildRemovedSshTargetTombstone(makeTarget({ configHost: 'devbox' }), 1)
expect(t.configHost).toBe('devbox')
})
})
+99
View File
@@ -0,0 +1,99 @@
import type { Store } from '../persistence'
import type { RemovedSshTargetTombstone, SshTarget } from '../../shared/ssh-types'
/**
* Re-adoption of workspaces orphaned when an SSH target was removed.
*
* Repos/worktrees store only the (random) target id, so removing a target
* strands them on a dead id. When the user re-adds the same host, a fresh id is
* minted and nothing links the old workspaces to it. We bridge that gap using
* removal-time tombstones ({ oldTargetId, configHost, host, username, port }):
* on add/import we match the new target's identity to a tombstone and re-point
* every repo/worktree from the old id to the new one.
*
* Matching is intentionally strict — configHost (alias) first, then the
* host+username+port tuple — so we only auto-reattach on a confident identity
* match and never mislink two genuinely different hosts. Anything that doesn't
* match cleanly stays a ghost, handled by the forget flow instead.
*/
type IdentityFields = Pick<SshTarget, 'configHost' | 'host' | 'port' | 'username'>
function normalize(value: string | undefined): string {
return value?.trim().toLowerCase() ?? ''
}
function tupleKey(fields: IdentityFields): string {
return `${normalize(fields.host)}|${fields.port}|${normalize(fields.username)}`
}
// An alias only counts as a distinguishing identity when it differs from the
// host. addTarget defaults configHost to host, so a manual add with no real
// ssh-config alias has configHost === host — that's not an alias, it's just the
// hostname, and matching on it alone would ignore port/username.
function meaningfulAlias(fields: IdentityFields): string {
const alias = normalize(fields.configHost)
return alias && alias !== normalize(fields.host) ? alias : ''
}
function tombstoneMatches(tombstone: RemovedSshTargetTombstone, target: IdentityFields): boolean {
const targetAlias = meaningfulAlias(target)
const tombstoneAlias = meaningfulAlias(tombstone)
// Primary: matching ssh-config alias. Stable across remove/re-import.
if (targetAlias && tombstoneAlias) {
// Both carry a real alias — the alias is the identity. Different aliases
// mean deliberately distinct targets (e.g. prod-deploy vs prod-admin on the
// same box with different identity files); do NOT fall through to the tuple,
// or a second alias for the same endpoint would steal the first's workspaces.
return targetAlias === tombstoneAlias
}
// Fallback: identical host+user+port. Used when either side has no real alias
// (manual adds default configHost to host), so a different account or port on
// the same host is correctly treated as a different target.
return tupleKey(tombstone) === tupleKey(target)
}
/**
* Re-point orphaned repos/worktrees onto `newTarget` if a removed target with
* the same host identity is tombstoned. Consumes the matching tombstone(s).
* Returns the number of repos re-adopted (0 when there was nothing to adopt).
*/
export function readoptOrphanedWorkspacesForTarget(store: Store, newTarget: SshTarget): number {
const tombstones = store.getRemovedSshTargetTombstones()
if (tombstones.length === 0) {
return 0
}
let readopted = 0
for (const tombstone of tombstones) {
// Why: a re-added target can't share the id of one that still exists, but
// guard anyway so we never re-point a live target onto itself.
if (tombstone.oldTargetId === newTarget.id) {
store.removeRemovedSshTargetTombstone(tombstone.oldTargetId)
continue
}
if (!tombstoneMatches(tombstone, newTarget)) {
continue
}
readopted += store.reassignSshTargetId(tombstone.oldTargetId, newTarget.id)
// Consume the tombstone whether or not it re-pointed anything: the host has
// returned, so the record has served its purpose.
store.removeRemovedSshTargetTombstone(tombstone.oldTargetId)
}
return readopted
}
/** Build a tombstone from a target about to be removed. */
export function buildRemovedSshTargetTombstone(
target: SshTarget,
removedAt: number
): RemovedSshTargetTombstone {
return {
oldTargetId: target.id,
...(target.configHost ? { configHost: target.configHost } : {}),
host: target.host,
port: target.port,
username: target.username,
label: target.label,
removedAt
}
}
+9
View File
@@ -859,6 +859,9 @@ export type PreloadApi = {
kind?: 'git' | 'folder'
}) => Promise<{ repo: Repo } | { error: string }>
remove: (args: { repoId: string }) => Promise<void>
// Forget a project on one execution host only, leaving the same repo id on
// other hosts (local or a re-added SSH target) intact.
removeForHost: (args: { repoId: string; hostId: string }) => Promise<void>
reorder: (args: { orderedIds: string[] }) => Promise<{ status: 'applied' | 'rejected' }>
update: (args: {
repoId: string
@@ -1059,6 +1062,9 @@ export type PreloadApi = {
force?: boolean
skipArchive?: boolean
}) => Promise<RemoveWorktreeResult>
// Forget a workspace from Orca only — no remote Git/filesystem work. Used
// for workspaces pinned to a removed/disconnected SSH host.
forgetLocal: (args: { worktreeId: string }) => Promise<RemoveWorktreeResult>
forceDeletePreservedBranch: (args: {
worktreeId: string
branchName: string
@@ -2811,6 +2817,9 @@ export type PreloadApi = {
}
ssh: {
listTargets: () => Promise<SshTarget[]>
// Removed-target id → last known label, for showing a friendly host name on
// workspaces still pinned to a target that no longer exists.
listRemovedTargetLabels: () => Promise<Record<string, string>>
addTarget: (args: { target: Omit<SshTarget, 'id'> }) => Promise<SshTarget>
updateTarget: (args: {
id: string
+7
View File
@@ -520,6 +520,8 @@ const api = {
remove: (args) => ipcRenderer.invoke('repos:remove', args),
removeForHost: (args) => ipcRenderer.invoke('repos:removeForHost', args),
reorder: (args) => ipcRenderer.invoke('repos:reorder', args),
update: (args) => ipcRenderer.invoke('repos:update', args),
@@ -652,6 +654,8 @@ const api = {
remove: (args) => ipcRenderer.invoke('worktrees:remove', args),
forgetLocal: (args) => ipcRenderer.invoke('worktrees:forgetLocal', args),
forceDeletePreservedBranch: (args) =>
ipcRenderer.invoke('worktrees:forceDeletePreservedBranch', args),
@@ -3834,6 +3838,9 @@ const api = {
ssh: {
listTargets: (): Promise<SshTarget[]> => ipcRenderer.invoke('ssh:listTargets'),
listRemovedTargetLabels: (): Promise<Record<string, string>> =>
ipcRenderer.invoke('ssh:listRemovedTargetLabels'),
addTarget: (args: { target: Omit<SshTarget, 'id'> }): Promise<SshTarget> =>
ipcRenderer.invoke('ssh:addTarget', args),
@@ -12,6 +12,10 @@ import { SshTargetDestructiveActions } from './SshTargetDestructiveActions'
import { SshTargetForm, EMPTY_FORM, type EditingTarget } from './SshTargetForm'
import { getEditingTargetForSshTarget } from './ssh-target-draft'
import { buildSshTargetSavePayload } from './ssh-target-save-payload'
import { HostRemoveDialog } from '../sidebar/HostRemoveDialog'
import { resolveSshHostRemoval } from '../sidebar/ssh-host-remove-resolution'
import { getAllWorktreesFromState } from '@/store/selectors'
import { toSshExecutionHostId } from '../../../../shared/execution-host'
import { translate } from '@/i18n/i18n'
export { getSshPaneSearchEntries } from './ssh-search'
@@ -28,6 +32,14 @@ export function SshPane(_props: SshPaneProps): React.JSX.Element {
const [editingId, setEditingId] = useState<string | null>(null)
const [form, setForm] = useState<EditingTarget>(EMPTY_FORM)
const [testingIds, setTestingIds] = useState<Set<string>>(new Set())
// Why: when a target still has workspaces, route removal through the shared
// workspace-aware HostRemoveDialog (same as the sidebar) instead of the plain
// confirm, so the user chooses to delete or keep them rather than silently
// orphaning them.
const [hostRemoveTarget, setHostRemoveTarget] = useState<{
targetId: string
label: string
} | null>(null)
const mountedRef = useMountedRef()
const setSshTargetsMetadata = useAppStore((s) => s.setSshTargetsMetadata)
@@ -122,6 +134,25 @@ export function SshPane(_props: SshPaneProps): React.JSX.Element {
}
}
// Route removal through the workspace-aware dialog when the target still owns
// workspaces; otherwise use the plain confirm (which also ends remote PTYs).
const requestRemoveTarget = (
target: { id: string; label: string },
requestPlainRemove: (target: { id: string; label: string }) => void
): void => {
const resolution = resolveSshHostRemoval({
targetId: target.id,
repos: useAppStore.getState().repos,
worktrees: getAllWorktreesFromState(useAppStore.getState()),
sshConnectionStates: useAppStore.getState().sshConnectionStates
})
if (resolution.workspaceCount > 0) {
setHostRemoveTarget({ targetId: target.id, label: target.label })
return
}
requestPlainRemove(target)
}
const handleRemove = async (id: string): Promise<void> => {
try {
await removeSshTargetWithBestEffortCleanup(window.api.ssh, id)
@@ -366,7 +397,9 @@ export function SshPane(_props: SshPaneProps): React.JSX.Element {
onResetRelay={(id) => requestResetRelay({ id, label: target.label })}
onTest={handleTest}
onEdit={handleEdit}
onRemove={(id) => requestRemove({ id, label: target.label })}
onRemove={(id) =>
requestRemoveTarget({ id, label: target.label }, requestRemove)
}
/>
))}
</div>
@@ -385,6 +418,21 @@ export function SshPane(_props: SshPaneProps): React.JSX.Element {
</>
)}
</SshTargetDestructiveActions>
{hostRemoveTarget ? (
<HostRemoveDialog
open
onOpenChange={(open) => {
if (!open) {
setHostRemoveTarget(null)
void loadTargets()
}
}}
hostId={toSshExecutionHostId(hostRemoveTarget.targetId)}
label={hostRemoveTarget.label}
target={{ kind: 'ssh', targetId: hostRemoveTarget.targetId }}
/>
) : null}
</div>
)
}
@@ -0,0 +1,195 @@
import { useState } from 'react'
import { toast } from 'sonner'
import { Loader2, Server, ServerOff } from 'lucide-react'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { useMountedRef } from '@/hooks/useMountedRef'
import { useAppStore } from '@/store'
import { translate } from '@/i18n/i18n'
import { runWorktreeDeleteWithToast } from './delete-worktree-flow'
import type { SshWorkspaceForgetResolution } from './ssh-workspace-forget-resolution'
type ForgetSshWorkspaceModalData = {
worktreeId: string
displayName: string
resolution: SshWorkspaceForgetResolution
}
function isForgetModalData(data: unknown): data is ForgetSshWorkspaceModalData {
if (!data || typeof data !== 'object') {
return false
}
const candidate = data as Partial<ForgetSshWorkspaceModalData>
return typeof candidate.worktreeId === 'string' && candidate.resolution != null
}
export function ForgetSshWorkspaceDialog(): React.JSX.Element | null {
const modalData = useAppStore((s) => s.modalData)
const closeModal = useAppStore((s) => s.closeModal)
const hostLabel = useAppStore((s) => {
const resolution = isForgetModalData(s.modalData) ? s.modalData.resolution : null
const targetId = resolution && resolution.kind !== 'not-ssh' ? resolution.targetId : undefined
if (!targetId) {
return ''
}
// Prefer the live label, then the removed target's last known label (ghost
// host), then the raw id as a last resort.
return s.sshTargetLabels.get(targetId) ?? s.removedSshTargetLabels.get(targetId) ?? targetId
})
const [busy, setBusy] = useState<null | 'reconnect' | 'forget'>(null)
const mountedRef = useMountedRef()
if (!isForgetModalData(modalData)) {
return null
}
const { worktreeId, displayName, resolution } = modalData
const canReconnect = resolution.kind === 'disconnected'
const done = (): void => {
if (mountedRef.current) {
setBusy(null)
closeModal()
}
}
// Reconnect the SSH target, then run the normal remote worktree removal.
const handleReconnectAndDelete = async (): Promise<void> => {
if (resolution.kind !== 'disconnected') {
return
}
setBusy('reconnect')
try {
await window.api.ssh.connect({ targetId: resolution.targetId })
} catch (err) {
if (mountedRef.current) {
setBusy(null)
}
toast.error(
err instanceof Error
? err.message
: translate(
'auto.components.sidebar.ForgetSshWorkspaceDialog.reconnectFailed',
'Reconnection failed'
)
)
return
}
// Close before the delete toast fires so the two don't overlap.
closeModal()
void runWorktreeDeleteWithToast(worktreeId, displayName)
if (mountedRef.current) {
setBusy(null)
}
}
// Remove Orca's records only — never touches remote files, worktrees, or branches.
const handleForget = async (): Promise<void> => {
setBusy('forget')
try {
const result = await useAppStore
.getState()
.removeWorktree(worktreeId, false, { mode: 'forget-local' })
if (!result.ok) {
toast.error(result.error)
if (mountedRef.current) {
setBusy(null)
}
return
}
done()
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err))
if (mountedRef.current) {
setBusy(null)
}
}
}
const forgetDescription = translate(
'auto.components.sidebar.ForgetSshWorkspaceDialog.forgetBody',
'Removes this workspace from Orca only. Files, the Git worktree, and branches on {{host}} are left untouched.',
{ host: hostLabel }
)
return (
<Dialog open onOpenChange={(open) => (!open ? closeModal() : undefined)}>
<DialogContent className="sm:max-w-md gap-3 p-5" showCloseButton={false}>
<DialogHeader className="gap-1">
<DialogTitle className="flex items-center gap-2 text-sm font-semibold">
<ServerOff className="size-4 text-muted-foreground" />
{translate(
'auto.components.sidebar.ForgetSshWorkspaceDialog.title',
'Delete “{{name}}”?',
{
name: displayName
}
)}
</DialogTitle>
<DialogDescription className="text-xs">
{canReconnect
? translate(
'auto.components.sidebar.ForgetSshWorkspaceDialog.disconnectedBody',
'The SSH host for this workspace is not connected. Reconnect to delete it on the remote too, or remove it from Orca only.'
)
: translate(
'auto.components.sidebar.ForgetSshWorkspaceDialog.ghostBody',
'{{host}} is no longer a saved SSH host, so this workspace is no longer connected to a live host. It can only be removed from Orca — files and branches on the remote are left untouched.',
{ host: hostLabel }
)}
</DialogDescription>
</DialogHeader>
<div className="flex items-center gap-2.5 rounded-md border border-border/50 bg-card/40 px-3 py-2">
<Server className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-xs font-medium">{hostLabel}</span>
</div>
{/* Why: the ghost-host description already states files are untouched, so
only repeat the reassurance on the reconnect (disconnected) path. */}
{canReconnect ? (
<p className="text-[11px] leading-snug text-muted-foreground">{forgetDescription}</p>
) : null}
<DialogFooter className="gap-2 sm:gap-2">
<Button variant="outline" size="sm" onClick={() => closeModal()} disabled={busy != null}>
{translate('auto.components.sidebar.ForgetSshWorkspaceDialog.cancel', 'Cancel')}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => void handleForget()}
disabled={busy != null}
>
{busy === 'forget' ? <Loader2 className="size-3.5 animate-spin" /> : null}
{translate(
'auto.components.sidebar.ForgetSshWorkspaceDialog.forget',
'Remove from Orca'
)}
</Button>
{canReconnect ? (
<Button
size="sm"
onClick={() => void handleReconnectAndDelete()}
disabled={busy != null}
>
{busy === 'reconnect' ? <Loader2 className="size-3.5 animate-spin" /> : null}
{translate(
'auto.components.sidebar.ForgetSshWorkspaceDialog.reconnectAndDelete',
'Reconnect & Delete'
)}
</Button>
) : null}
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default ForgetSshWorkspaceDialog
@@ -1,6 +1,7 @@
import React, { useState } from 'react'
import { Loader2 } from 'lucide-react'
import React, { useMemo, useState } from 'react'
import { ChevronDown, Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'
import {
Dialog,
DialogContent,
@@ -12,12 +13,14 @@ import {
import { Button } from '@/components/ui/button'
import { useMountedRef } from '@/hooks/useMountedRef'
import { useAppStore } from '@/store'
import { getAllWorktreesFromState } from '@/store/selectors'
import { translate } from '@/i18n/i18n'
import type { ExecutionHostId } from '../../../../shared/execution-host'
import { parseExecutionHostId } from '../../../../shared/execution-host'
import { removeSshTargetWithBestEffortCleanup } from '../settings/ssh-target-remove'
import { clearHostRename } from './host-rename-remove'
import type { HostRemovalTarget } from './host-rename-remove'
import { resolveSshHostRemoval } from './ssh-host-remove-resolution'
import { clearSshHostWorkspaces } from './ssh-host-remove-workspaces'
type HostRemoveDialogProps = {
open: boolean
@@ -35,8 +38,35 @@ export function HostRemoveDialog({
target
}: HostRemoveDialogProps): React.JSX.Element {
const [busy, setBusy] = useState(false)
// Why: removing the host only (keeping workspaces) is the safe, reversible
// default. Deleting the remote workspaces is destructive, so it lives behind
// an Advanced disclosure and must be opted into explicitly.
const [advancedOpen, setAdvancedOpen] = useState(false)
const [deleteWorkspaces, setDeleteWorkspaces] = useState(false)
const mountedRef = useMountedRef()
const repos = useAppStore((s) => s.repos)
const worktreesByRepo = useAppStore((s) => s.worktreesByRepo)
const sshConnectionStates = useAppStore((s) => s.sshConnectionStates)
// Resolve which workspaces live on the target so the dialog can offer to
// delete/forget them alongside the host.
const sshResolution = useMemo(() => {
if (target.kind !== 'ssh') {
return null
}
return resolveSshHostRemoval({
targetId: target.targetId,
repos,
worktrees: getAllWorktreesFromState({ worktreesByRepo }),
sshConnectionStates
})
}, [target, repos, worktreesByRepo, sshConnectionStates])
const workspaceCount = sshResolution?.workspaceCount ?? 0
const hasWorkspaces = workspaceCount > 0
const isConnected = sshResolution?.isConnected ?? false
// Why: dropping a host should also drop its now-orphaned label override so a
// future host reusing the same id doesn't inherit a stale rename.
const dropOverridesForHost = (): void => {
@@ -46,7 +76,7 @@ export function HostRemoveDialog({
})
}
const handleRemoveSsh = async (targetId: string): Promise<void> => {
const removeSshTarget = async (targetId: string): Promise<void> => {
await removeSshTargetWithBestEffortCleanup(window.api.ssh, targetId)
// Why: clear deferred reconnect metadata so focused SSH tabs stop retrying
// the deleted target — mirrors the SSH settings pane removal flow.
@@ -64,14 +94,37 @@ export function HostRemoveDialog({
onOpenChange(false)
}
const confirm = async (): Promise<void> => {
if (target.kind === 'runtime') {
handleRemoveRuntime(target.environmentId)
const runSshRemoval = async (): Promise<void> => {
if (target.kind !== 'ssh') {
return
}
setBusy(true)
try {
await handleRemoveSsh(target.targetId)
if (deleteWorkspaces && sshResolution) {
// Connected → real remote removal; offline/ghost → local forget.
const { failedIds } = await clearSshHostWorkspaces(
sshResolution,
isConnected ? 'delete-remote' : 'forget-local'
)
// Why: don't remove the SSH target (and report success) while some of its
// workspaces failed to clear — that would strand ghost rows behind a
// now-gone host. Surface the failure and keep the target so the user can
// retry or resolve the blocking workspace first.
if (failedIds.length > 0) {
if (mountedRef.current) {
setBusy(false)
}
toast.error(
translate(
'auto.components.sidebar.HostRemoveDialog.workspacesFailed',
'Could not remove {{count}} of this host’s workspaces. The host was kept so you can retry.',
{ count: failedIds.length }
)
)
return
}
}
await removeSshTarget(target.targetId)
if (mountedRef.current) {
onOpenChange(false)
}
@@ -96,7 +149,47 @@ export function HostRemoveDialog({
}
}
const isRuntime = parseExecutionHostId(hostId)?.kind === 'runtime'
const workspaceCountLabel =
workspaceCount === 1
? translate('auto.components.sidebar.HostRemoveDialog.oneWorkspace', '1 workspace')
: translate(
'auto.components.sidebar.HostRemoveDialog.manyWorkspaces',
'{{count}} workspaces',
{
count: workspaceCount
}
)
const description =
target.kind === 'runtime'
? translate(
'auto.components.sidebar.HostRemoveDialog.4d5e6f7a8b',
'This opens the Orca servers settings where you can remove this server.'
)
: hasWorkspaces
? translate(
'auto.components.sidebar.HostRemoveDialog.hostHasWorkspacesDefault',
'Removes {{value0}} and its credentials from this computer. Its {{value1}} stay in Orca — remote files are not touched.',
{ value0: label, value1: workspaceCountLabel }
)
: translate(
'auto.components.sidebar.HostRemoveDialog.5e6f7a8b9c',
'This removes the saved SSH host and its credentials from this computer. Remote files are not deleted.'
)
// The destructive opt-in wording depends on whether we delete remote files or
// only forget Orca's records (offline/ghost host).
const deleteOptionLabel = isConnected
? translate(
'auto.components.sidebar.HostRemoveDialog.alsoDeleteRemote',
'Also delete these {{value0}} on {{value1}}',
{ value0: workspaceCountLabel, value1: label }
)
: translate(
'auto.components.sidebar.HostRemoveDialog.alsoForgetLocal',
'Also remove these {{value0}} from Orca',
{ value0: workspaceCountLabel }
)
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -111,33 +204,106 @@ export function HostRemoveDialog({
}
)}
</DialogTitle>
<DialogDescription>
{isRuntime
? translate(
'auto.components.sidebar.HostRemoveDialog.4d5e6f7a8b',
'This opens the Orca servers settings where you can remove this server.'
)
: translate(
'auto.components.sidebar.HostRemoveDialog.5e6f7a8b9c',
'This removes the saved SSH host and its credentials from this computer. Remote files are not deleted.'
)}
</DialogDescription>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
{translate('auto.components.sidebar.HostRemoveDialog.6f7a8b9c0d', 'Cancel')}
</Button>
{/* Advanced disclosure: deleting the host's workspaces is destructive, so
it's opt-in and hidden by default. Only shown when there are any.
Matches the New Workspace composer's Advanced header + switch. */}
{target.kind === 'ssh' && hasWorkspaces ? (
<div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setAdvancedOpen((v) => !v)}
aria-expanded={advancedOpen}
className="-ml-2 text-xs"
>
{translate('auto.components.sidebar.HostRemoveDialog.advanced', 'Advanced')}
<ChevronDown
className={cn('size-4 transition-transform', advancedOpen && 'rotate-180')}
/>
</Button>
<div
className={cn(
'grid overflow-hidden transition-[grid-template-rows] duration-200 ease-out',
advancedOpen ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]'
)}
aria-hidden={!advancedOpen}
>
<div className="min-h-0">
<div className="flex items-start gap-3 px-1 pt-1">
<button
type="button"
role="switch"
aria-checked={deleteWorkspaces}
onClick={() => setDeleteWorkspaces((v) => !v)}
className="group mt-0.5 flex shrink-0 cursor-pointer items-center rounded-md outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50"
>
<span
aria-hidden
className={cn(
'relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border border-transparent transition-colors',
deleteWorkspaces ? 'bg-foreground' : 'bg-muted-foreground/30'
)}
>
<span
className={cn(
'pointer-events-none block size-3.5 rounded-full bg-background shadow-sm transition-transform',
deleteWorkspaces ? 'translate-x-4' : 'translate-x-0.5'
)}
/>
</span>
</button>
<span className="min-w-0 flex-1 text-xs leading-snug">
<span className="font-medium text-foreground">{deleteOptionLabel}</span>
<span className="mt-0.5 block text-muted-foreground">
{isConnected
? translate(
'auto.components.sidebar.HostRemoveDialog.alsoDeleteRemoteHint',
'Permanently deletes the remote Git worktrees and their branches. Cannot be undone.'
)
: translate(
'auto.components.sidebar.HostRemoveDialog.alsoForgetLocalHint',
'Clears them from Orca only. Remote files, worktrees, and branches are left untouched.'
)}
</span>
</span>
</div>
</div>
</div>
</div>
) : null}
<DialogFooter className="gap-2 sm:gap-2">
<Button
type="button"
variant="destructive"
variant="outline"
disabled={busy}
onClick={() => void confirm()}
onClick={() => onOpenChange(false)}
>
{busy ? <Loader2 className="size-3.5 animate-spin" /> : null}
{isRuntime
? translate('auto.components.sidebar.HostRemoveDialog.7a8b9c0d1e', 'Open settings')
: translate('auto.components.sidebar.HostRemoveDialog.8b9c0d1e2f', 'Remove host')}
{translate('auto.components.sidebar.HostRemoveDialog.6f7a8b9c0d', 'Cancel')}
</Button>
{target.kind === 'runtime' ? (
<Button
type="button"
variant="destructive"
onClick={() => handleRemoveRuntime(target.environmentId)}
>
{translate('auto.components.sidebar.HostRemoveDialog.7a8b9c0d1e', 'Open settings')}
</Button>
) : (
<Button
type="button"
variant="destructive"
disabled={busy}
onClick={() => void runSshRemoval()}
>
{busy ? <Loader2 className="size-3.5 animate-spin" /> : null}
{translate('auto.components.sidebar.HostRemoveDialog.8b9c0d1e2f', 'Remove host')}
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
@@ -21,6 +21,22 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() {
const repoId = typeof modalData.repoId === 'string' ? modalData.repoId : ''
const displayName = typeof modalData.displayName === 'string' ? modalData.displayName : ''
// Why: for an SSH project the files live on the remote host's disk, not the
// user's — "still on your disk" would be misleading. Name the host (using the
// removed-target label when it's a ghost) so the user knows where it remains
// and that re-adding that host recovers it.
const sshHostLabel = useAppStore((s) => {
const connectionId = s.repos.find((r) => r.id === repoId)?.connectionId?.trim()
if (!connectionId) {
return null
}
return (
s.sshTargetLabels.get(connectionId) ??
s.removedSshTargetLabels.get(connectionId) ??
connectionId
)
})
const handleConfirm = useCallback(() => {
if (repoId) {
void removeProject(repoId)
@@ -50,10 +66,16 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() {
'This only removes'
)}{' '}
<span className="break-all font-medium text-foreground">{displayName}</span>{' '}
{translate(
'auto.components.sidebar.RemoveFolderDialog.8c097ef04e',
'from Orca. It is still on your disk.'
)}
{sshHostLabel
? translate(
'auto.components.sidebar.RemoveFolderDialog.fromOrcaSsh',
'from Orca. Its files stay on {{value0}} — re-add that SSH host to recover it.',
{ value0: sshHostLabel }
)
: translate(
'auto.components.sidebar.RemoveFolderDialog.8c097ef04e',
'from Orca. It is still on your disk.'
)}
</DialogDescription>
</DialogHeader>
<DialogFooter>
@@ -5,6 +5,8 @@ import { activateAndRevealWorktree } from '@/lib/worktree-activation'
import { prepareActiveWorktreeFocusAfterDelete } from './active-worktree-focus-after-delete'
import { showDeleteWorktreeFailureToast } from './delete-worktree-failure-toast'
import { getWorkspaceDeleteLineage } from './workspace-delete-lineage'
import { resolveSshWorkspaceForget } from './ssh-workspace-forget-resolution'
import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome'
import {
isPathInsideOrEqual,
normalizeRuntimePathForComparison
@@ -249,6 +251,39 @@ export function runWorktreeDelete(worktreeId: string): void {
return
}
state.clearWorktreeDeleteState(worktreeId)
// Why: a workspace on a removed/disconnected SSH host cannot go through the
// normal remote removal — its provider is gone, so worktrees:remove throws
// before any cleanup. Route to a dialog that offers reconnect-and-delete
// (when the target still exists) or a local-only forget.
//
// Skip this on paired web/mobile clients: SSH targets/labels/connection state
// are desktop-only, so those clients have empty sshTargetLabels and would
// misclassify every SSH repo as a ghost, routing to a forget dialog whose
// local-only backend is unavailable there. Their normal worktree.rm RPC path
// already handles the delete against the desktop runtime.
const repo = state.repos.find((entry) => entry.id === target.repoId) ?? null
const sshResolution = isPairedWebClientWindow()
? { kind: 'not-ssh' as const }
: resolveSshWorkspaceForget({
repo,
sshConnectionStates: state.sshConnectionStates,
sshTargetLabels: state.sshTargetLabels
})
if (sshResolution.kind === 'ghost' || sshResolution.kind === 'disconnected') {
// Why no lineage-children warning here (unlike the normal path below):
// forget-local is metadata-only and per-worktree, so it can't fail on a
// still-registered child the way a remote git removal would. Any descendants
// live on the same ghost host and remain independently visible/forgettable —
// they are not orphaned unrecoverably.
state.openModal('forget-ssh-workspace', {
worktreeId,
displayName: target.displayName,
resolution: sshResolution
})
return
}
const hasLineageChildren =
getWorkspaceDeleteLineage(target, state.allWorktrees(), state.worktreeLineageById).descendants
.length > 0
@@ -21,6 +21,7 @@ const WorktreeMetaDialog = lazyWithRetry(() => import('./WorktreeMetaDialog'))
const RemoveFolderDialog = lazyWithRetry(() => import('./RemoveFolderDialog'))
const WorktreeVisibilityDialog = lazyWithRetry(() => import('./WorktreeVisibilityDialog'))
const OrcaYamlTrustDialog = lazyWithRetry(() => import('./OrcaYamlTrustDialog'))
const ForgetSshWorkspaceDialog = lazyWithRetry(() => import('./ForgetSshWorkspaceDialog'))
const MIN_WIDTH = 220
const MAX_WIDTH = 500
@@ -207,6 +208,7 @@ function Sidebar({
{activeModal === 'confirm-remove-folder' ? <RemoveFolderDialog /> : null}
{activeModal === 'worktree-visibility' ? <WorktreeVisibilityDialog /> : null}
{activeModal === 'confirm-orca-yaml-hooks' ? <OrcaYamlTrustDialog /> : null}
{activeModal === 'forget-ssh-workspace' ? <ForgetSshWorkspaceDialog /> : null}
</React.Suspense>
{sidebarOpen ? (
<WorkspaceKanbanDrawer
@@ -0,0 +1,90 @@
import { describe, it, expect } from 'vitest'
import { resolveSshHostRemoval } from './ssh-host-remove-resolution'
import type { SshConnectionState } from '../../../../shared/ssh-types'
function connected(id: string): Map<string, SshConnectionState> {
return new Map([[id, { targetId: id, status: 'connected', error: null, reconnectAttempt: 0 }]])
}
describe('resolveSshHostRemoval', () => {
const repos = [
{ id: 'repo-a', connectionId: 'ssh-1' },
{ id: 'repo-b', connectionId: 'ssh-1' },
{ id: 'repo-local', connectionId: null }
]
const worktrees = [
{ id: 'repo-a::/wt/main', repoId: 'repo-a', isMainWorktree: true },
{ id: 'repo-a::/wt/feature', repoId: 'repo-a', isMainWorktree: false },
{ id: 'repo-b::/wt/x', repoId: 'repo-b', isMainWorktree: false },
{ id: 'repo-local::/wt/y', repoId: 'repo-local', isMainWorktree: false }
]
it('collects non-main worktrees and root repos on the target', () => {
const result = resolveSshHostRemoval({
targetId: 'ssh-1',
repos,
worktrees,
sshConnectionStates: new Map()
})
expect(result.workspaceWorktreeIds.sort()).toEqual(
['repo-a::/wt/feature', 'repo-b::/wt/x'].sort()
)
expect(result.hostRepoIds.sort()).toEqual(['repo-a', 'repo-b'])
// 2 child worktrees + 2 root repos.
expect(result.workspaceCount).toBe(4)
expect(result.isConnected).toBe(false)
})
it('ignores repos and worktrees on other hosts', () => {
const result = resolveSshHostRemoval({
targetId: 'ssh-1',
repos,
worktrees,
sshConnectionStates: new Map()
})
expect(result.workspaceWorktreeIds).not.toContain('repo-local::/wt/y')
expect(result.hostRepoIds).not.toContain('repo-local')
})
it('reports connected when the target relay is connected', () => {
const result = resolveSshHostRemoval({
targetId: 'ssh-1',
repos,
worktrees,
sshConnectionStates: connected('ssh-1')
})
expect(result.isConnected).toBe(true)
})
it('reports zero workspaces for a target nothing points at', () => {
const result = resolveSshHostRemoval({
targetId: 'ssh-unused',
repos,
worktrees,
sshConnectionStates: new Map()
})
expect(result.workspaceCount).toBe(0)
expect(result.hostRepoIds).toEqual([])
})
it('dedupes duplicate repo and worktree rows so the count is not inflated', () => {
const result = resolveSshHostRemoval({
// Store transiently holds duplicate rows (e.g. mid host merge).
targetId: 'ssh-1',
repos: [
{ id: 'repo-a', connectionId: 'ssh-1' },
{ id: 'repo-a', connectionId: 'ssh-1' } // duplicate repo row
],
worktrees: [
{ id: 'repo-a::/wt/x', repoId: 'repo-a', isMainWorktree: false },
{ id: 'repo-a::/wt/x', repoId: 'repo-a', isMainWorktree: false }, // duplicate
{ id: 'repo-a::/wt/x', repoId: 'repo-a', isMainWorktree: false } // triplicate
],
sshConnectionStates: new Map()
})
expect(result.hostRepoIds).toEqual(['repo-a'])
expect(result.workspaceWorktreeIds).toEqual(['repo-a::/wt/x'])
// 1 root repo + 1 unique child worktree.
expect(result.workspaceCount).toBe(2)
})
})
@@ -0,0 +1,55 @@
import type { Repo, Worktree } from '../../../../shared/types'
import type { SshConnectionState } from '../../../../shared/ssh-types'
/**
* Classifies what removing an SSH target means for the workspaces still on it,
* so the host-removal dialog can offer the right choice:
* - connected → can delete host AND its remote worktrees (real git removal)
* - offline → target still configured but not connected; delete would need a
* reconnect, so default to forgetting the workspaces locally
* - (no workspaces) → plain host removal, no workspace decision needed
*/
export type SshHostRemoveResolution = {
targetId: string
/** Ids of non-main worktrees on this host that a remote delete would remove. */
workspaceWorktreeIds: string[]
/** Repo ids whose main/root workspace lives on this host. */
hostRepoIds: string[]
workspaceCount: number
isConnected: boolean
}
export function resolveSshHostRemoval(args: {
targetId: string
repos: readonly Pick<Repo, 'id' | 'connectionId'>[]
worktrees: readonly Pick<Worktree, 'id' | 'repoId' | 'isMainWorktree'>[]
sshConnectionStates: ReadonlyMap<string, SshConnectionState>
}): SshHostRemoveResolution {
const hostRepoIds = [
...new Set(
args.repos
.filter((repo) => repo.connectionId?.trim() === args.targetId)
.map((repo) => repo.id)
)
]
const hostRepoIdSet = new Set(hostRepoIds)
// Why: dedupe by id — the store can transiently hold duplicate worktree rows
// (e.g. mid host merge), and a doubled row must not inflate the count shown to
// the user or cause a worktree to be removed twice.
const workspaceWorktreeIds = [
...new Set(
args.worktrees
.filter((worktree) => hostRepoIdSet.has(worktree.repoId) && !worktree.isMainWorktree)
.map((worktree) => worktree.id)
)
]
const isConnected = args.sshConnectionStates.get(args.targetId)?.status === 'connected'
return {
targetId: args.targetId,
workspaceWorktreeIds,
hostRepoIds,
// A repo's main/root workspace counts too — removing the host drops it.
workspaceCount: workspaceWorktreeIds.length + hostRepoIds.length,
isConnected
}
}
@@ -0,0 +1,70 @@
import { getRepoExecutionHostId, toSshExecutionHostId } from '../../../../shared/execution-host'
import { useAppStore } from '@/store'
import type { SshHostRemoveResolution } from './ssh-host-remove-resolution'
export type ClearSshHostWorkspacesResult = {
/** Worktree/repo removals that reported failure ({ ok: false }). Non-empty
* means the SSH target should not be reported as fully removed. */
failedIds: string[]
}
/**
* Clears the workspaces on an SSH host that is being removed, before the target
* itself is deleted. Two modes:
* - 'delete-remote': the host is connected, so run the normal remote removal
* for each worktree (deletes the remote git worktree) and the host-scoped
* project removal for each root repo.
* - 'forget-local': the host is offline/gone, so only clear Orca's records —
* no remote files, worktrees, or branches are touched.
*
* Worktrees are removed before their root repos so a root removal never races a
* still-registered child. Failures are collected (not thrown) so the caller can
* decide whether to proceed with target removal.
*/
export async function clearSshHostWorkspaces(
resolution: SshHostRemoveResolution,
mode: 'delete-remote' | 'forget-local'
): Promise<ClearSshHostWorkspacesResult> {
const store = useAppStore.getState()
const forgetLocalOnly = mode === 'forget-local'
const failedIds: string[] = []
for (const worktreeId of resolution.workspaceWorktreeIds) {
// Why: sequential, not parallel — deletes on the same repo contend on git
// ref locks, and forget is cheap enough that ordering keeps failures legible.
const result = await store.removeWorktree(
worktreeId,
false,
forgetLocalOnly ? { mode: 'forget-local' } : undefined
)
if (!result.ok) {
failedIds.push(worktreeId)
}
}
// Why: removeProject purges renderer state and (in main) is host-scoped. Pass
// the explicit SSH host id so a repo id shared with the local host resolves to
// this host's row instead of falling back to the focused host — otherwise the
// wrong (local) project could be removed and the SSH ghost left behind. For an
// offline/ghost host this hits the local backend path (no live runtime target),
// clearing Orca's records without a successful remote call.
const hostId = toSshExecutionHostId(resolution.targetId)
for (const repoId of resolution.hostRepoIds) {
try {
await store.removeProject(repoId, { hostId })
} catch {
failedIds.push(repoId)
}
// Why: removeProject swallows its own errors and returns void, so the
// try/catch above can't observe a failure. Verify the host's repo row is
// actually gone; if it lingers, the removal did not succeed.
const stillPresent = useAppStore
.getState()
.repos.some((repo) => repo.id === repoId && getRepoExecutionHostId(repo) === hostId)
if (stillPresent && !failedIds.includes(repoId)) {
failedIds.push(repoId)
}
}
return { failedIds }
}
@@ -0,0 +1,70 @@
import { describe, it, expect } from 'vitest'
import { resolveSshWorkspaceForget } from './ssh-workspace-forget-resolution'
import type { SshConnectionState } from '../../../../shared/ssh-types'
function stateMap(
entries: Record<string, SshConnectionState['status']>
): Map<string, SshConnectionState> {
return new Map(
Object.entries(entries).map(([id, status]) => [
id,
{ targetId: id, status, error: null, reconnectAttempt: 0 }
])
)
}
describe('resolveSshWorkspaceForget', () => {
it('returns not-ssh for a repo with no connectionId', () => {
const result = resolveSshWorkspaceForget({
repo: { connectionId: null },
sshConnectionStates: new Map(),
sshTargetLabels: new Map()
})
expect(result.kind).toBe('not-ssh')
})
it('returns not-ssh for a runtime-owned target', () => {
const result = resolveSshWorkspaceForget({
repo: { connectionId: 'runtime-ssh-abc' },
sshConnectionStates: new Map(),
sshTargetLabels: new Map()
})
expect(result.kind).toBe('not-ssh')
})
it('returns ghost when the target is no longer configured', () => {
const result = resolveSshWorkspaceForget({
repo: { connectionId: 'ssh-dead' },
sshConnectionStates: new Map(),
sshTargetLabels: new Map() // ssh-dead not present -> ghost
})
expect(result).toEqual({ kind: 'ghost', targetId: 'ssh-dead' })
})
it('returns connected when the configured target is connected', () => {
const result = resolveSshWorkspaceForget({
repo: { connectionId: 'ssh-live' },
sshConnectionStates: stateMap({ 'ssh-live': 'connected' }),
sshTargetLabels: new Map([['ssh-live', 'Live']])
})
expect(result).toEqual({ kind: 'connected', targetId: 'ssh-live' })
})
it('returns disconnected when configured but not connected', () => {
const result = resolveSshWorkspaceForget({
repo: { connectionId: 'ssh-live' },
sshConnectionStates: stateMap({ 'ssh-live': 'error' }),
sshTargetLabels: new Map([['ssh-live', 'Live']])
})
expect(result).toEqual({ kind: 'disconnected', targetId: 'ssh-live', status: 'error' })
})
it('defaults to disconnected status when configured target has no live state', () => {
const result = resolveSshWorkspaceForget({
repo: { connectionId: 'ssh-live' },
sshConnectionStates: new Map(),
sshTargetLabels: new Map([['ssh-live', 'Live']])
})
expect(result).toEqual({ kind: 'disconnected', targetId: 'ssh-live', status: 'disconnected' })
})
})
@@ -0,0 +1,50 @@
import type { Repo } from '../../../../shared/types'
import type { SshConnectionState } from '../../../../shared/ssh-types'
import { isRuntimeOwnedSshTargetId } from '../../../../shared/execution-host'
/**
* How a workspace on an SSH host should be deleted, given the host's live
* state. Drives whether the delete flow can go straight through the normal
* remote removal, must offer a reconnect-first choice, or can only forget the
* workspace from Orca because the SSH target is gone entirely.
*/
export type SshWorkspaceForgetResolution =
| { kind: 'not-ssh' }
// Target exists and the relay is connected — normal remote removal works.
| { kind: 'connected'; targetId: string }
// Target still configured but not connected — offer Reconnect & Delete plus
// a local-only forget fallback.
| { kind: 'disconnected'; targetId: string; status: SshConnectionState['status'] }
// Target was removed; only a project-only "ghost" host remains. Reconnect is
// impossible, so forget-from-Orca is the only path.
| { kind: 'ghost'; targetId: string }
export function resolveSshWorkspaceForget(args: {
repo: Pick<Repo, 'connectionId'> | null | undefined
sshConnectionStates: ReadonlyMap<string, SshConnectionState>
// Keys are configured SSH target ids (targets that still exist in settings).
sshTargetLabels: ReadonlyMap<string, string>
}): SshWorkspaceForgetResolution {
const connectionId = args.repo?.connectionId?.trim()
// Why: runtime-owned (ephemeral-VM) SSH targets manage their own lifecycle and
// are never user-facing ghosts, so they take the normal delete path.
if (!connectionId || isRuntimeOwnedSshTargetId(connectionId)) {
return { kind: 'not-ssh' }
}
const isConfigured = args.sshTargetLabels.has(connectionId)
const status = args.sshConnectionStates.get(connectionId)?.status
// Why: a target the user removed leaves repos pinned to a dead id with no
// configured target — the grey ghost host. Reconnect can never succeed, so
// the only escape is to forget it from Orca.
if (!isConfigured) {
return { kind: 'ghost', targetId: connectionId }
}
if (status === 'connected') {
return { kind: 'connected', targetId: connectionId }
}
return { kind: 'disconnected', targetId: connectionId, status: status ?? 'disconnected' }
}
@@ -313,9 +313,19 @@ export default function TerminalPane({
)
const sshReconnectTargetLabel = useAppStore((store) =>
sshReconnectTargetId
? (store.sshTargetLabels.get(sshReconnectTargetId) ?? sshReconnectTargetId)
? (store.sshTargetLabels.get(sshReconnectTargetId) ??
// Fall back to the removed target's last known label (ghost host) before
// the raw id, so a removed host shows its name instead of ssh-<ts>-<rand>.
store.removedSshTargetLabels.get(sshReconnectTargetId) ??
sshReconnectTargetId)
: ''
)
// Why: the target was removed entirely (a ghost) when it's no longer a known
// SSH target. Reconnecting to it can only fail ("SSH target not found"), so
// the overlay must offer to remove the workspace instead of Connect.
const sshReconnectTargetRemoved = useAppStore((store) =>
sshReconnectTargetId ? !store.sshTargetLabels.has(sshReconnectTargetId) : false
)
useVisibleTerminalTabClaim({ isVisible, tabId })
@@ -2972,6 +2982,8 @@ export default function TerminalPane({
targetId={sshReconnectTargetId}
targetLabel={sshReconnectTargetLabel}
status={sshReconnectStatus}
targetRemoved={sshReconnectTargetRemoved}
worktreeId={worktreeId}
/>
) : null}
<DaemonActionDialog api={daemonActions} />
@@ -13,12 +13,20 @@ const toastMocks = vi.hoisted(() => ({
error: vi.fn()
}))
const deleteFlowMocks = vi.hoisted(() => ({
runWorktreeDelete: vi.fn()
}))
vi.mock('sonner', () => ({
toast: {
error: toastMocks.error
}
}))
vi.mock('../sidebar/delete-worktree-flow', () => ({
runWorktreeDelete: deleteFlowMocks.runWorktreeDelete
}))
vi.mock('@/i18n/i18n', () => ({
translate: (_key: string, fallback: string, values?: Record<string, string>) =>
fallback.replace('{{value0}}', values?.value0 ?? '')
@@ -39,6 +47,7 @@ describe('TerminalSshReconnectOverlay', () => {
beforeEach(() => {
useAppStore.setState(useAppStore.getInitialState(), true)
toastMocks.error.mockReset()
deleteFlowMocks.runWorktreeDelete.mockReset()
})
afterEach(() => {
@@ -101,6 +110,30 @@ describe('TerminalSshReconnectOverlay', () => {
expect(screen.getByRole('button', { name: 'Connect' })).toBeEnabled()
})
it('offers to remove the workspace (not Connect) when the SSH target was removed', async () => {
const connect = vi.fn().mockResolvedValue(undefined)
installSshConnect(connect)
const user = userEvent.setup()
render(
<TerminalSshReconnectOverlay
targetId="ssh-dead"
targetLabel="ssh-dead"
status="disconnected"
targetRemoved
worktreeId="repo::/work/wt"
/>
)
expect(screen.getByText('SSH host removed')).toBeInTheDocument()
// No Connect button — reconnect is impossible for a removed target.
expect(screen.queryByRole('button', { name: 'Connect' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Remove workspace' }))
expect(deleteFlowMocks.runWorktreeDelete).toHaveBeenCalledWith('repo::/work/wt')
expect(connect).not.toHaveBeenCalled()
})
it('publishes the returned SSH state so deferred terminal reattach can resume', async () => {
const connectedState: SshConnectionState = {
targetId: 'ssh-target-1',
@@ -6,11 +6,16 @@ import { useMountedRef } from '@/hooks/useMountedRef'
import { useAppStore } from '@/store'
import type { SshConnectionStatus } from '../../../../shared/ssh-types'
import { translate } from '@/i18n/i18n'
import { runWorktreeDelete } from '../sidebar/delete-worktree-flow'
type TerminalSshReconnectOverlayProps = {
targetId: string
targetLabel: string
status: SshConnectionStatus
// The SSH target was removed entirely — reconnect is impossible, so offer to
// remove the workspace instead of a Connect button that can only fail.
targetRemoved?: boolean
worktreeId?: string
}
// Why: relay deployment/reconnect are host-driven transient states; the
@@ -63,13 +68,16 @@ function messageForStatus(status: SshConnectionStatus, targetLabel: string): str
export function TerminalSshReconnectOverlay({
targetId,
targetLabel,
status
status,
targetRemoved = false,
worktreeId
}: TerminalSshReconnectOverlayProps): React.JSX.Element {
const [connecting, setConnecting] = useState(false)
const mountedRef = useMountedRef()
const setSshConnectionState = useAppStore((store) => store.setSshConnectionState)
const isConnecting = connecting || isConnectingStatus(status)
const showConnect = canConnectStatus(status)
// Why: a removed target can never reconnect, so never offer Connect for it.
const showConnect = !targetRemoved && canConnectStatus(status)
const handleConnect = useCallback(async () => {
if (isConnecting) {
@@ -115,13 +123,23 @@ export function TerminalSshReconnectOverlay({
</div>
<div className="min-w-0 space-y-1">
<div className="text-sm font-semibold">
{translate(
'auto.components.terminal.pane.TerminalSshReconnectOverlay.title',
'SSH connection required'
)}
{targetRemoved
? translate(
'auto.components.terminal.pane.TerminalSshReconnectOverlay.removedTitle',
'SSH host removed'
)
: translate(
'auto.components.terminal.pane.TerminalSshReconnectOverlay.title',
'SSH connection required'
)}
</div>
<div className="text-xs leading-5 text-muted-foreground">
{messageForStatus(status, targetLabel)}
{targetRemoved
? translate(
'auto.components.terminal.pane.TerminalSshReconnectOverlay.removedBody',
'The SSH host for this workspace was removed, so it can no longer connect. Remove the workspace to clear it — remote files are left untouched.'
)
: messageForStatus(status, targetLabel)}
</div>
</div>
</div>
@@ -130,26 +148,40 @@ export function TerminalSshReconnectOverlay({
<Server className="size-3.5 shrink-0 text-muted-foreground" />
<span className="truncate text-xs font-medium">{targetLabel}</span>
</div>
<Button
size="sm"
onClick={showConnect ? () => void handleConnect() : undefined}
disabled={!showConnect || isConnecting}
>
{!showConnect || isConnecting ? (
<>
<Loader2 className="size-3.5 animate-spin" />
{translate(
'auto.components.terminal.pane.TerminalSshReconnectOverlay.connectingButton',
'Connecting...'
)}
</>
) : (
translate(
'auto.components.terminal.pane.TerminalSshReconnectOverlay.connectButton',
'Connect'
)
)}
</Button>
{targetRemoved ? (
<Button
size="sm"
variant="outline"
onClick={worktreeId ? () => runWorktreeDelete(worktreeId) : undefined}
disabled={!worktreeId}
>
{translate(
'auto.components.terminal.pane.TerminalSshReconnectOverlay.removeWorkspaceButton',
'Remove workspace'
)}
</Button>
) : (
<Button
size="sm"
onClick={showConnect ? () => void handleConnect() : undefined}
disabled={!showConnect || isConnecting}
>
{!showConnect || isConnecting ? (
<>
<Loader2 className="size-3.5 animate-spin" />
{translate(
'auto.components.terminal.pane.TerminalSshReconnectOverlay.connectingButton',
'Connecting...'
)}
</>
) : (
translate(
'auto.components.terminal.pane.TerminalSshReconnectOverlay.connectButton',
'Connect'
)
)}
</Button>
)}
</div>
</div>
</div>
@@ -9,6 +9,7 @@ import { scheduleRuntimeGraphSync } from '@/runtime/sync-runtime-graph'
import { useAppStore } from '@/store'
import { getWorktreeMapFromState } from '@/store/selectors'
import { parseWorkspaceKey } from '../../../../shared/workspace-scope'
import { isRuntimeOwnedSshTargetId } from '../../../../shared/execution-host'
import { createTerminalZeroDimensionsMessage } from '../../../../shared/terminal-zero-dimensions-diagnostic'
import { parseTerminalOscColorQuery } from '../../../../shared/terminal-osc-color-reply'
import { isTerminalQueryReply } from '../../../../shared/terminal-query-reply'
@@ -5546,6 +5547,21 @@ export function connectPanePty(
// because the SSH provider isn't registered until after connect succeeds.
if (connectionId) {
const storeState = useAppStore.getState()
// Why: the SSH target was removed entirely (a ghost workspace). Reattaching
// can only fail with "SSH target not found", which surfaces a red "file an
// issue" banner for what is an expected user action. Skip reattach — the
// terminal overlay already shows a "host removed" state with a remove
// action. Runtime-owned targets aren't user-managed, so they're exempt.
// A target map that exists but omits this id means the target was removed.
// (Guard the map's presence for minimal test stubs that omit it; an absent
// map is "not hydrated", not "target gone".)
if (
!isRuntimeOwnedSshTargetId(connectionId) &&
storeState.sshTargetLabels instanceof Map &&
!storeState.sshTargetLabels.has(connectionId)
) {
return
}
const restoredLeafSessionId =
deps.restoredLeafId && deps.restoredPtyIdByLeafId
? (deps.restoredPtyIdByLeafId[deps.restoredLeafId] ?? null)
+8
View File
@@ -2516,6 +2516,14 @@ export function useIpcEvents(): void {
try {
const targets = await window.api.ssh.listTargets()
useAppStore.getState().setSshTargetsMetadata(targets)
// Why: ghost-host UI (removed target still referenced by a workspace)
// shows a friendly name from the removal tombstones instead of the raw id.
try {
const removedLabels = await window.api.ssh.listRemovedTargetLabels()
useAppStore.getState().setRemovedSshTargetLabels(removedLabels)
} catch {
// Best-effort — a missing map just falls back to the raw target id.
}
for (const target of targets) {
const state = await window.api.ssh.getState({ targetId: target.id })
if (state) {
@@ -26,6 +26,7 @@ const remoteDuplicate: Repo = {
}
const reposRemove = vi.fn()
const reposRemoveForHost = vi.fn()
const reposUpdate = vi.fn()
const reposReorder = vi.fn()
const ptyKill = vi.fn()
@@ -59,6 +60,7 @@ function projectHostSetup(overrides: Pick<ProjectHostSetup, 'id' | 'hostId'>): P
beforeEach(() => {
clearRuntimeCompatibilityCacheForTests()
reposRemove.mockReset()
reposRemoveForHost.mockReset()
reposUpdate.mockReset()
reposReorder.mockReset()
ptyKill.mockReset()
@@ -71,6 +73,7 @@ beforeEach(() => {
api: {
repos: {
remove: reposRemove,
removeForHost: reposRemoveForHost,
update: reposUpdate,
reorder: reposReorder
},
@@ -260,11 +263,88 @@ describe('repo slice host identity routing', () => {
expect(store.getState().projects).toEqual([
expect.objectContaining({ id: 'repo:same-repo', sourceRepoIds: ['same-repo'] })
])
expect(reposRemove).toHaveBeenCalledWith({ repoId: 'same-repo' })
// Why: the id also exists on runtime:env-1, so the local-side removal must be
// host-scoped in main to avoid deleting the other host's persisted repo row.
expect(reposRemoveForHost).toHaveBeenCalledWith({ repoId: 'same-repo', hostId: 'local' })
expect(reposRemove).not.toHaveBeenCalled()
expect(ptyKill).toHaveBeenCalledWith('local-pty')
expect(ptyKill).not.toHaveBeenCalledWith('remote-pty')
})
it('removeProject with an explicit hostId routes to that host, not the focused one', async () => {
runtimeEnvironmentCall.mockResolvedValue({
id: 'rpc-explicit-host',
ok: true,
result: { status: 'removed' },
_meta: { runtimeId: 'runtime-remote' }
})
const localWorktree = makeWorktree({ id: 'same-repo::/local/wt', repoId: 'same-repo' })
const remoteWorktree = makeWorktree({
id: 'same-repo::/remote/wt',
repoId: 'same-repo',
hostId: 'runtime:env-1'
})
const store = createTestStore()
// Focus is local (no active runtime env). Without deriving the target from the
// explicit hostId, this would route to the focused (local) host and delete the
// wrong row. It must target runtime:env-1 via that host's RPC.
store.setState({
repos: [localDuplicate, remoteDuplicate],
worktreesByRepo: { 'same-repo': [localWorktree, remoteWorktree] }
})
await store.getState().removeProject('same-repo', { hostId: 'runtime:env-1' })
// Routes to the runtime host's repo.rm (not the local removeForHost/remove),
// and the local row is left intact.
expect(runtimeEnvironmentCall).toHaveBeenCalledWith({
selector: 'env-1',
method: 'repo.rm',
params: { repo: 'same-repo' },
timeoutMs: 15_000
})
expect(reposRemoveForHost).not.toHaveBeenCalled()
expect(reposRemove).not.toHaveBeenCalled()
expect(store.getState().repos).toEqual([localDuplicate])
expect(store.getState().worktreesByRepo['same-repo']).toEqual([localWorktree])
})
it('removeProject of an SSH host row routes local even when a runtime is focused', async () => {
// Regression: removing an SSH host's repo (explicit ssh hostId) must NOT route
// repo.rm to the focused runtime env. settingsForRepoOwner clears the focused
// runtime for SSH owners, so removal stays on the host-scoped local path.
const sshDuplicate: Repo = {
id: 'same-repo',
path: '/home/orca/project',
displayName: 'SSH',
badgeColor: '#222',
addedAt: 3,
connectionId: 'ssh-1',
executionHostId: 'ssh:ssh-1'
}
const sshWorktree = makeWorktree({
id: 'same-repo::/home/orca/wt',
repoId: 'same-repo',
hostId: 'ssh:ssh-1'
})
const store = createTestStore()
// A runtime env is focused, but the row being removed is SSH-owned.
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as never,
repos: [localDuplicate, sshDuplicate],
worktreesByRepo: { 'same-repo': [sshWorktree] }
})
await store.getState().removeProject('same-repo', { hostId: 'ssh:ssh-1' })
// Host-scoped local removal (id also exists on local), never the runtime RPC.
expect(reposRemoveForHost).toHaveBeenCalledWith({ repoId: 'same-repo', hostId: 'ssh:ssh-1' })
expect(runtimeEnvironmentCall).not.toHaveBeenCalledWith(
expect.objectContaining({ method: 'repo.rm' })
)
expect(store.getState().repos).toEqual([localDuplicate])
})
it('removes a runtime duplicate without purging legacy local worktrees', async () => {
runtimeEnvironmentCall.mockResolvedValue({
id: 'rpc-duplicate-remove',
+47 -11
View File
@@ -48,6 +48,7 @@ import { isPathInsideOrEqual } from '../../../../shared/cross-platform-path'
import { getRepoIdFromWorktreeId } from '../../../../shared/worktree-id'
import { selectProjectGroupRemovalTargets } from './project-group-removal-targets'
import { reconcileFetchedRepos } from './repo-identity-reconcile'
import { pruneSupersededSshRepoRows } from './superseded-ssh-repo-rows'
import { splitRepoReorderByHost } from './repo-reorder-host-split'
import { omitSparsePresetsForRepos } from './sparse-presets'
import {
@@ -74,7 +75,8 @@ import {
LOCAL_EXECUTION_HOST_ID,
parseExecutionHostId,
toRuntimeExecutionHostId,
toSshExecutionHostId
toSshExecutionHostId,
type ExecutionHostId
} from '../../../../shared/execution-host'
import { cleanupEphemeralVmRuntimesForDeleted } from '@/lib/ephemeral-vm-runtime-cleanup'
import { folderWorkspaceKey, parseWorkspaceKey } from '../../../../shared/workspace-scope'
@@ -1038,8 +1040,12 @@ async function listRuntimeEnvironmentsForAllHostLoad(): Promise<{ id: string }[]
}
}
function settingsForRepoOwner(state: Pick<AppState, 'repos' | 'settings'>, repoId: string) {
const repo = findRepoForHost(state.repos, repoId, { settings: state.settings })
function settingsForRepoOwner(
state: Pick<AppState, 'repos' | 'settings'>,
repoId: string,
hostId?: ExecutionHostId
) {
const repo = findRepoForHost(state.repos, repoId, { settings: state.settings, hostId })
if (!repo) {
return state.settings
}
@@ -1371,7 +1377,9 @@ export type RepoSlice = {
groupId: string | null,
order?: number
) => Promise<boolean>
removeProject: (projectId: string) => Promise<void>
// options.hostId disambiguates which host's row to remove when the same repo
// id exists on multiple hosts; without it the focused host is assumed.
removeProject: (projectId: string, options?: { hostId?: ExecutionHostId }) => Promise<void>
updateProject: (projectId: string, updates: ProjectUpdate) => Promise<boolean>
updateRepo: (projectId: string, updates: RepoUpdate) => Promise<boolean>
setActiveRepo: (projectId: string | null) => void
@@ -1408,18 +1416,26 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
return
}
set((s) => {
const validRepoIds = new Set(reconciledRepos.map((repo) => repo.id))
// Why: after re-adoption re-points a repo onto a re-added SSH target, the
// per-host merge leaves the stale row on the old (removed) target id — a
// ghost a terminal pane can bind to and fail with "SSH target not found".
// Drop rows on unknown SSH targets that a live-host sibling supersedes.
const prunedRepos = pruneSupersededSshRepoRows(
reconciledRepos,
new Set(s.sshTargetLabels.keys())
)
const validRepoIds = new Set(prunedRepos.map((repo) => repo.id))
const mergedProjectCompatibility = mergeFetchedProjectCompatibilityForHost({
previous: {
projects: s.projects,
projectHostSetups: s.projectHostSetups
},
fetched: projectCompatibility,
repos: reconciledRepos,
repos: prunedRepos,
hostId
})
return {
repos: reconciledRepos,
repos: prunedRepos,
...mergedProjectCompatibility,
folderWorkspacePathStatuses: {},
activeRepoId: s.activeRepoId && validRepoIds.has(s.activeRepoId) ? s.activeRepoId : null,
@@ -2539,9 +2555,15 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
}
},
removeProject: async (projectId) => {
removeProject: async (projectId, options) => {
try {
const ownerRepo = findRepoForHost(get().repos, projectId, { settings: get().settings })
// Why: pass an explicit hostId (e.g. when removing an SSH host's root repo)
// so a duplicate id across hosts resolves to the intended row instead of
// falling back to the focused host.
const ownerRepo = findRepoForHost(get().repos, projectId, {
settings: get().settings,
hostId: options?.hostId
})
if (!ownerRepo) {
return
}
@@ -2556,9 +2578,23 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
runtimeOwnedSshTargetIds: [ownerRepo.connectionId as string]
})
}
const target = getActiveRuntimeTarget(settingsForRepoOwner(get(), projectId))
// Why: derive the runtime target from the owner's own settings, passing the
// explicit options.hostId so a duplicate repo id across hosts resolves to the
// intended row. settingsForRepoOwner clears the focused runtime for SSH/local
// owners (routing local) and pins runtime owners to their environment, so an
// SSH host removal never routes repo.rm to the focused runtime.
const target = getActiveRuntimeTarget(settingsForRepoOwner(get(), projectId, options?.hostId))
// Why: the same repo id can exist on multiple hosts (local + an SSH target,
// or a re-added SSH target). Main's repos:remove is repo-id-only and would
// delete every host's row. Scope the local-side removal to the owning host
// so a cross-host duplicate id keeps its other rows.
const idExistsOnOtherHost = get().repos.some(
(repo) => repo.id === projectId && getRepoExecutionHostId(repo) !== ownerHostId
)
await (target.kind === 'local'
? window.api.repos.remove({ repoId: projectId })
? idExistsOnOtherHost
? window.api.repos.removeForHost({ repoId: projectId, hostId: ownerHostId })
: window.api.repos.remove({ repoId: projectId })
: callRuntimeRpc(target, 'repo.rm', { repo: projectId }, { timeoutMs: 15_000 }))
get().clearOrcaHookTrustForRepo(projectId)
+8
View File
@@ -33,6 +33,10 @@ export type SshSlice = {
/** Maps target IDs to their user-facing labels. Populated during hydration
* so components can look up labels without per-component IPC calls. */
sshTargetLabels: Map<string, string>
/** Maps REMOVED target IDs to their last known label (from re-adoption
* tombstones). Lets ghost-host UI show a friendly name instead of the raw id
* for a workspace still pinned to a deleted target. */
removedSshTargetLabels: Map<string, string>
remoteWorkspaceHydratedTargetIds: Set<string>
remoteWorkspaceSyncStatusByTargetId: Record<string, RemoteWorkspaceSyncStatus>
sshCredentialQueue: SshCredentialRequest[]
@@ -50,6 +54,7 @@ export type SshSlice = {
detectedPortsByConnection: Record<string, EnrichedDetectedPort[]>
setSshConnectionState: (targetId: string, state: SshConnectionState) => void
setSshTargetLabels: (labels: Map<string, string>) => void
setRemovedSshTargetLabels: (labels: Record<string, string>) => void
setSshTargetsMetadata: (targets: Pick<SshTarget, 'id' | 'label'>[]) => void
clearRemovedSshTargetState: (targetId: string) => void
markRemoteWorkspaceHydrated: (targetId: string) => void
@@ -65,6 +70,7 @@ export type SshSlice = {
export const createSshSlice: StateCreator<AppState, [], [], SshSlice> = (set) => ({
sshConnectionStates: new Map(),
sshTargetLabels: new Map(),
removedSshTargetLabels: new Map(),
remoteWorkspaceHydratedTargetIds: new Set(),
remoteWorkspaceSyncStatusByTargetId: {},
sshCredentialQueue: [],
@@ -90,6 +96,8 @@ export const createSshSlice: StateCreator<AppState, [], [], SshSlice> = (set) =>
}),
setSshTargetLabels: (labels) => set({ sshTargetLabels: labels }),
setRemovedSshTargetLabels: (labels) =>
set({ removedSshTargetLabels: new Map(Object.entries(labels)) }),
setSshTargetsMetadata: (targets) =>
set((s) => {
if (sshTargetLabelsEqual(s.sshTargetLabels, targets)) {
@@ -0,0 +1,56 @@
import { describe, it, expect } from 'vitest'
import { pruneSupersededSshRepoRows } from './superseded-ssh-repo-rows'
import type { Repo } from '../../../../shared/types'
function repo(overrides: Partial<Repo>): Repo {
return {
id: 'r',
path: '/p',
displayName: 'r',
badgeColor: '#000',
addedAt: 1,
...overrides
}
}
describe('pruneSupersededSshRepoRows', () => {
it('drops a stale dead-SSH row when a live-host sibling shares the id', () => {
// The re-adoption leftover: same id on a dead target + a live one.
const repos = [
repo({ id: 'shared', connectionId: 'ssh-dead' }),
repo({ id: 'shared', connectionId: 'ssh-live' })
]
const result = pruneSupersededSshRepoRows(repos, new Set(['ssh-live']))
expect(result.map((r) => r.connectionId)).toEqual(['ssh-live'])
})
it('KEEPS a lone project-only ghost (no live sibling) so it can still be forgotten', () => {
const repos = [repo({ id: 'ghost', connectionId: 'ssh-dead' })]
const result = pruneSupersededSshRepoRows(repos, new Set())
expect(result).toHaveLength(1)
expect(result[0].connectionId).toBe('ssh-dead')
})
it('drops a dead-SSH row superseded by a LOCAL sibling', () => {
// A repo id on both local and a removed SSH host: the local row is the live
// sibling, so the SSH ghost is a re-adoption/duplicate leftover → drop it.
const repos = [repo({ id: 'shared' }), repo({ id: 'shared', connectionId: 'ssh-dead' })]
const result = pruneSupersededSshRepoRows(repos, new Set())
expect(result.map((r) => r.connectionId ?? 'local')).toEqual(['local'])
})
it('leaves live SSH rows untouched', () => {
const repos = [repo({ id: 'a', connectionId: 'ssh-live' }), repo({ id: 'b' })]
const result = pruneSupersededSshRepoRows(repos, new Set(['ssh-live']))
expect(result).toHaveLength(2)
})
it('never prunes runtime-owned SSH rows', () => {
const repos = [
repo({ id: 'shared', connectionId: 'runtime-ssh-abc' }),
repo({ id: 'shared', connectionId: 'ssh-live' })
]
const result = pruneSupersededSshRepoRows(repos, new Set(['ssh-live']))
expect(result).toHaveLength(2)
})
})
@@ -0,0 +1,50 @@
import type { Repo } from '../../../../shared/types'
import { isRuntimeOwnedSshTargetId } from '../../../../shared/execution-host'
/**
* Drops repo rows left stranded on a removed SSH target after re-adoption
* re-pointed the same repo onto a re-added host.
*
* Re-adoption (main) rewrites a repo's connectionId from the old (dead) target
* id to the new one, but the renderer's per-host repo merge preserves rows on
* "other hosts" — and the dead SSH host still looks like another host, so its
* stale row lingers. A terminal pane bound to that ghost row then fails with
* "SSH target not found".
*
* A row is superseded (and pruned) only when ALL hold:
* - it targets an SSH connection that is NOT a currently-known target, and
* - the same repo id also exists on a DIFFERENT host that IS known/live.
*
* This never removes a legitimate lone project-only ghost host (its repo id
* exists only on the dead host, so there is no live sibling to supersede it) —
* those are kept on purpose so the sidebar can still surface and forget them.
*/
export function pruneSupersededSshRepoRows(
repos: readonly Repo[],
knownSshTargetIds: ReadonlySet<string>
): Repo[] {
const isDeadSshRow = (repo: Repo): boolean => {
const connectionId = repo.connectionId?.trim()
if (!connectionId || isRuntimeOwnedSshTargetId(connectionId)) {
return false
}
return !knownSshTargetIds.has(connectionId)
}
// Repo ids that have at least one row on a known/live host (local or a live
// SSH/runtime target). Only these can supersede a dead-host sibling.
const idsWithLiveHost = new Set<string>()
for (const repo of repos) {
if (!isDeadSshRow(repo)) {
idsWithLiveHost.add(repo.id)
}
}
return repos.filter((repo) => {
if (!isDeadSshRow(repo)) {
return true
}
// Keep a lone ghost (no live sibling); drop only a superseded leftover.
return !idsWithLiveHost.has(repo.id)
})
}
+1
View File
@@ -745,6 +745,7 @@ export type UISlice = {
| 'create-worktree'
| 'edit-meta'
| 'delete-worktree'
| 'forget-ssh-workspace'
| 'confirm-add-project-from-folder'
| 'confirm-non-git-folder'
| 'confirm-remove-folder'
@@ -177,7 +177,11 @@ export type WorktreeSlice = {
prefetchWorktreeCreateBase: (repoId: string, baseBranch?: string) => Promise<void>
removeWorktree: (
worktreeId: string,
force?: boolean
force?: boolean,
// 'forget-local' drops the workspace from Orca only (no remote Git/FS work)
// for workspaces pinned to a removed/disconnected SSH host. Reuses the same
// renderer-side teardown/purge as a normal remove.
options?: { mode?: 'remove' | 'forget-local' }
) => Promise<({ ok: true } & RemoveWorktreeResult) | { ok: false; error: string }>
markWorktreesDeleting: (worktreeIds: readonly string[]) => void
forceDeletePreservedBranch: (
+21 -12
View File
@@ -3144,7 +3144,8 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
})
},
removeWorktree: async (worktreeId, force) => {
removeWorktree: async (worktreeId, force, options) => {
const forgetLocalOnly = options?.mode === 'forget-local'
set((s) => ({
deleteStateByWorktreeId: {
...s.deleteStateByWorktreeId,
@@ -3157,22 +3158,30 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
}))
try {
const repoIdForTrust = getRepoIdFromWorktreeId(worktreeId)
const trustDecision = await ensureHooksConfirmed(get(), repoIdForTrust, 'archive')
const skipArchive = trustDecision === 'skip'
// Why: forget-local touches no remote, so there is no archive hook to run
// and no need to prompt for hook trust.
const skipArchive = forgetLocalOnly
? true
: (await ensureHooksConfirmed(get(), getRepoIdFromWorktreeId(worktreeId), 'archive')) ===
'skip'
const worktreeBeforeRemoval = get()
.allWorktrees()
.find((entry) => entry.id === worktreeId)
// Why: forget-local always clears Orca's own records via the local IPC
// handler regardless of the workspace's execution host — the whole point
// is that the remote (SSH relay / runtime) is gone or unreachable.
const target = getActiveRuntimeTarget(settingsForWorktreeOwner(get(), worktreeId))
const removalResult = await (target.kind === 'local'
? window.api.worktrees.remove({ worktreeId, force, skipArchive })
: callRuntimeRpc<RemoveWorktreeResult>(
target,
'worktree.rm',
{ worktree: toRuntimeWorktreeSelector(worktreeId), force, runHooks: !skipArchive },
{ timeoutMs: 60_000 }
))
const removalResult = await (forgetLocalOnly
? window.api.worktrees.forgetLocal({ worktreeId })
: target.kind === 'local'
? window.api.worktrees.remove({ worktreeId, force, skipArchive })
: callRuntimeRpc<RemoveWorktreeResult>(
target,
'worktree.rm',
{ worktree: toRuntimeWorktreeSelector(worktreeId), force, runHooks: !skipArchive },
{ timeoutMs: 60_000 }
))
const worktreeDisplayName = worktreeBeforeRemoval?.displayName?.trim()
if (worktreeDisplayName) {
+12
View File
@@ -1127,6 +1127,12 @@ function createReposApi(): NonNullable<Partial<PreloadApi>['repos']> {
await callRuntimeResult('repo.rm', { repo: repoId })
invalidateRuntimeWorktreeCaches()
},
// Why: host-scoped forget targets a disconnected/removed SSH host owned by
// the desktop app. A paired web client talks to a single Orca runtime and
// has no ghost-host state to reconcile.
removeForHost: () => {
throw new Error('Forgetting a host is unavailable in paired web clients.')
},
reorder: async ({ orderedIds }) => callRuntimeResult('repo.reorder', { orderedIds }),
update: async ({ repoId, updates }) =>
(await callRuntimeResult<{ repo: Repo }>('repo.update', { repo: repoId, updates })).repo,
@@ -1290,6 +1296,11 @@ function createWorktreesApi(): NonNullable<Partial<PreloadApi>['worktrees']> {
force
})
},
// Why: forget-locally clears a workspace pinned to a disconnected/removed
// SSH host on the desktop app; a paired web client has no such ghost state.
forgetLocal: () => {
throw new Error('Forgetting a workspace is unavailable in paired web clients.')
},
forceDeletePreservedBranch: ({ worktreeId, branchName, expectedHead }) =>
callRuntimeResult<ForceDeleteWorktreeBranchResult>('worktree.forceDeleteBranch', {
worktree: toRuntimeWorktreeSelector(worktreeId),
@@ -2608,6 +2619,7 @@ function createPtyApi(): NonNullable<Partial<PreloadApi>['pty']> {
function createSshApi(): NonNullable<Partial<PreloadApi>['ssh']> {
return {
listTargets: () => Promise.resolve([]),
listRemovedTargetLabels: () => Promise.resolve({}),
addTarget: () =>
Promise.reject(new Error('SSH target management is unavailable in the web client.')),
updateTarget: () =>
+17
View File
@@ -51,6 +51,23 @@ export type SshTarget = {
systemSshConnectionReuse?: boolean
}
/** Identity of a removed SSH target, recorded so that re-adding the same host
* can re-point orphaned repos/worktrees from the old (deleted) target id to
* the new one. Repos store only the target id, so without this record the old
* workspaces are stranded on a dead id when the target is removed. */
export type RemovedSshTargetTombstone = {
/** The id the removed target had — what orphaned repos/worktrees still point at. */
oldTargetId: string
/** ssh-config alias, if any — the most stable re-adoption key. */
configHost?: string
host: string
port: number
username: string
label: string
/** ms epoch when the target was removed, for pruning old tombstones. */
removedAt: number
}
export type SavedPortForward = {
localPort: number
remoteHost: string
+4 -1
View File
@@ -1,6 +1,6 @@
/* eslint-disable max-lines */
import type { ExecutionHostId } from './execution-host'
import type { SshRemotePtyLease, SshTarget } from './ssh-types'
import type { RemovedSshTargetTombstone, SshRemotePtyLease, SshTarget } from './ssh-types'
import type { Automation, AutomationExecutionTargetType, AutomationRun } from './automations-types'
import type { WorkspaceSource } from './workspace-source'
import type { GitHubProjectSettings } from './github-project-types'
@@ -3515,6 +3515,9 @@ export type PersistedState = {
* matching ~/.ssh/config host on the next sync so a deleted host does not
* reappear. Cleared for an alias when the user re-adds it or re-adopts config. */
deletedSshConfigAliases: string[]
/** Identity records for removed SSH targets. Lets a re-added host re-adopt
* workspaces that were orphaned on the old target id. Pruned by age/count. */
removedSshTargetTombstones?: RemovedSshTargetTombstone[]
sshRemotePtyLeases: SshRemotePtyLease[]
/** Daemon session ids of live local Claude launches. Seeds the Claude
* live-PTY gate on startup so an early OAuth refresh cannot rotate the