From a47417c4399dd3f34436a142aa76f9eeb01ac41d Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 23 Sep 2026 10:30:27 -0400 Subject: [PATCH 1/3] fix(repos): a project on an unreachable host can still leave Orca MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Removing a project dispatches to the host that owns it. When that host never answered, the RPC rejection aborted the whole removal before the local purge and the user got a bare "Failed to remove project" — the row could not be removed at all while the host stayed down. Split that outcome out. A host that answers and refuses is still a failure. A host that never answers is `owner-unverifiable`: its catalog is untouched, so the row is kept and the caller is told, rather than the store spending a dead-end toast on it. The confirm dialog then stays open, names the host, and re-offers the removal as `mode: 'forget-local'` — which clears this client's records and dispatches nothing to the owner, terminal teardown included. Loss of contact is never evidence of absence, so the copy says plainly that nothing on the host is touched and the project returns if that host reconnects (docs/reference/ssh-execution-boundary.md). Co-Authored-By: Claude Opus 5 (1M context) --- .../settings/settings-project-list.test.ts | 35 ++++++- .../settings/settings-project-list.ts | 27 +++++- .../sidebar/RemoveFolderDialog.test.tsx | 93 +++++++++++++++---- .../components/sidebar/RemoveFolderDialog.tsx | 88 +++++++++++++----- .../sidebar/ssh-host-remove-workspaces.ts | 11 ++- src/renderer/src/i18n/locales/en.json | 8 +- .../store/repos/project-removal-outcome.ts | 26 ++++++ src/renderer/src/store/repos/repo-removal.ts | 29 ++++-- src/renderer/src/store/repos/repo-state.ts | 11 ++- ...epos-remove-missing-remote-project.test.ts | 49 +++++++++- 10 files changed, 314 insertions(+), 63 deletions(-) create mode 100644 src/renderer/src/store/repos/project-removal-outcome.ts diff --git a/src/renderer/src/components/settings/settings-project-list.test.ts b/src/renderer/src/components/settings/settings-project-list.test.ts index 2b60d077ef33..0050df2ffc34 100644 --- a/src/renderer/src/components/settings/settings-project-list.test.ts +++ b/src/renderer/src/components/settings/settings-project-list.test.ts @@ -1,4 +1,5 @@ -import { describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { toast } from 'sonner' import type { ProjectHostSetup } from '../../../../shared/project-types' import type { Repo } from '../../../../shared/repo-types' import { @@ -13,6 +14,8 @@ import { resolveSettingsTargetRepoId } from './settings-project-list' +vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) + function makeRepo(overrides: Partial & Pick): Repo { return { path: `/repos/${overrides.id}`, @@ -262,8 +265,12 @@ describe('deep-link resolution', () => { }) describe('removeSettingsProjectFromAllHosts', () => { + beforeEach(() => { + vi.mocked(toast.error).mockReset() + }) + it('removes every host setup with its own hostId and skips setups without a repo row', async () => { - const removeProject = vi.fn().mockResolvedValue(undefined) + const removeProject = vi.fn().mockResolvedValue({ status: 'removed' }) const setups = [ makeSetup({ hostId: 'local', repoId: 'local-1' }), makeSetup({ hostId: 'ssh:box', repoId: ' ' }), @@ -285,11 +292,11 @@ describe('removeSettingsProjectFromAllHosts', () => { .fn() .mockImplementationOnce( () => - new Promise((resolve) => { - resolveFirst = resolve + new Promise<{ status: 'removed' }>((resolve) => { + resolveFirst = () => resolve({ status: 'removed' }) }) ) - .mockResolvedValue(undefined) + .mockResolvedValue({ status: 'removed' }) const setups = [ makeSetup({ hostId: 'local', repoId: 'local-1' }), makeSetup({ hostId: 'runtime:home-mac', repoId: 'remote-9' }) @@ -303,4 +310,22 @@ describe('removeSettingsProjectFromAllHosts', () => { await pending expect(removeProject).toHaveBeenCalledTimes(2) }) + + // The store keeps its toast for failures only, so this pane has to voice the unanswered host + // itself — otherwise a removal that changed nothing looks like it worked. + it('says which host went unanswered instead of looking successful', async () => { + const removeProject = vi + .fn() + .mockResolvedValueOnce({ status: 'removed' }) + .mockResolvedValueOnce({ status: 'owner-unverifiable' }) + const setups = [ + makeSetup({ hostId: 'local', repoId: 'local-1' }), + makeSetup({ hostId: 'runtime:home-mac', repoId: 'remote-9' }) + ] + + await removeSettingsProjectFromAllHosts(setups, removeProject) + + expect(toast.error).toHaveBeenCalledTimes(1) + expect(vi.mocked(toast.error).mock.calls[0]?.[1]?.description).toContain('runtime:home-mac') + }) }) diff --git a/src/renderer/src/components/settings/settings-project-list.ts b/src/renderer/src/components/settings/settings-project-list.ts index 14de9f8d848f..4153bfad4f95 100644 --- a/src/renderer/src/components/settings/settings-project-list.ts +++ b/src/renderer/src/components/settings/settings-project-list.ts @@ -1,5 +1,8 @@ +import { toast } from 'sonner' import type { Project, ProjectHostSetup } from '../../../../shared/project-types' import type { Repo } from '../../../../shared/repo-types' +import type { RemoveProjectOutcome } from '../../store/repos/project-removal-outcome' +import { translate } from '@/i18n/i18n' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID, @@ -177,12 +180,32 @@ export async function removeSettingsProjectFromAllHosts( removeProject: ( repoId: string, options: { hostId: ExecutionHostId; errorFeedback?: 'toast' | 'silent' } - ) => Promise + ) => Promise ): Promise { for (const setup of setups) { if (setup.repoId.trim().length > 0) { // Why: user-initiated single-project removal, so a failure must be visible rather than silent (#11994). - await removeProject(setup.repoId, { hostId: setup.hostId, errorFeedback: 'toast' }) + const outcome = await removeProject(setup.repoId, { + hostId: setup.hostId, + errorFeedback: 'toast' + }) + // Why: an unanswered host is not a store failure, so it carries no toast of its own. This + // pane has no per-host forget affordance, so say what happened rather than look successful. + if (outcome.status === 'owner-unverifiable') { + toast.error( + translate( + 'auto.components.settings.settingsProjectList.removeOwnerUnverifiable', + 'Could not reach the host that owns this project' + ), + { + description: translate( + 'auto.components.settings.settingsProjectList.removeOwnerUnverifiableDescription', + 'It is still registered on {{host}}. Reconnect that host and try again, or remove the project from the sidebar to clear this computer’s records only.', + { host: setup.hostId } + ) + } + ) + } } } } diff --git a/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx b/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx index 7a5ac841d536..b81eced1f56f 100644 --- a/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx +++ b/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx @@ -1,23 +1,32 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' +import { cleanup, render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' import { renderToStaticMarkup } from 'react-dom/server' -import type { ReactNode } from 'react' +import type { ButtonHTMLAttributes, ReactNode } from 'react' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { Repo } from '../../../../shared/repo-types' -const mocks = vi.hoisted(() => ({ - state: { - activeModal: 'confirm-remove-folder' as string | null, - modalData: { - repoId: 'repo-1', - displayName: 'Example', - hostId: 'ssh:target-1' - } as Record, - repos: [] as Repo[], - sshTargetLabels: new Map(), - removedSshTargetLabels: new Map(), - closeModal: vi.fn(), - removeProject: vi.fn() +const mocks = vi.hoisted(() => { + const runtimeEnvironments: { id: string; name: string }[] = [] + return { + state: { + activeModal: 'confirm-remove-folder' as string | null, + modalData: { + repoId: 'repo-1', + displayName: 'Example', + hostId: 'ssh:target-1' + } as Record, + repos: [] as Repo[], + runtimeEnvironments, + sshTargetLabels: new Map(), + removedSshTargetLabels: new Map(), + closeModal: vi.fn(), + removeProject: vi.fn() + } } -})) +}) vi.mock('@/store', () => ({ useAppStore: (selector: (state: typeof mocks.state) => unknown) => selector(mocks.state) @@ -34,13 +43,21 @@ vi.mock('@/components/ui/dialog', () => ({ })) vi.mock('@/components/ui/button', () => ({ - Button: ({ children }: { children: ReactNode }) => + Button: ({ + children, + onClick, + disabled + }: ButtonHTMLAttributes & { children: ReactNode }) => ( + + ) })) vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string, values?: Record) => Object.entries(values ?? {}).reduce( - (text, [key, value]) => text.replace(`{{${key}}}`, value), + (text, [key, value]) => text.replaceAll(`{{${key}}}`, value), fallback ) })) @@ -62,14 +79,18 @@ function repo(connectionId: string | null, executionHostId: Repo['executionHostI describe('RemoveFolderDialog', () => { beforeEach(() => { + cleanup() vi.clearAllMocks() mocks.state.modalData = { repoId: 'repo-1', displayName: 'Example', hostId: 'ssh:target-1' } + mocks.state.repos = [] + mocks.state.runtimeEnvironments = [] mocks.state.sshTargetLabels = new Map([['target-1', 'Persistent host']]) mocks.state.removedSshTargetLabels = new Map() + mocks.state.removeProject.mockResolvedValue({ status: 'removed' }) }) it('warns that VM recipe cleanup controls file deletion', () => { @@ -91,4 +112,42 @@ describe('RemoveFolderDialog', () => { expect(html).toContain('Its files stay on Persistent host') expect(html).not.toContain('VM recipe') }) + + it('closes on a removal the owning host confirmed', async () => { + mocks.state.repos = [repo('target-1', 'ssh:target-1')] + render() + + await userEvent.click(screen.getByRole('button', { name: 'Remove' })) + + expect(mocks.state.removeProject).toHaveBeenCalledWith('repo-1', { + hostId: 'ssh:target-1', + errorFeedback: 'toast' + }) + expect(mocks.state.closeModal).toHaveBeenCalledTimes(1) + }) + + // The owning runtime never answered, so the project is still registered there. The + // dialog must stay open and name the host rather than close on a removal that did not happen. + it('re-offers a client-only forget when the owning host never answers', async () => { + mocks.state.modalData.hostId = 'runtime:env-1' + mocks.state.repos = [repo(null, 'runtime:env-1')] + mocks.state.runtimeEnvironments = [{ id: 'env-1', name: 'alexdevbox2' }] + mocks.state.removeProject.mockResolvedValueOnce({ status: 'owner-unverifiable' }) + render() + + await userEvent.click(screen.getByRole('button', { name: 'Remove' })) + + expect(mocks.state.closeModal).not.toHaveBeenCalled() + expect(screen.getByText(/alexdevbox2 did not answer/)).toBeInTheDocument() + expect(screen.getByText(/returns if that host reconnects/)).toBeInTheDocument() + + await userEvent.click(screen.getByRole('button', { name: 'Remove from Orca' })) + + expect(mocks.state.removeProject).toHaveBeenLastCalledWith('repo-1', { + hostId: 'runtime:env-1', + errorFeedback: 'toast', + mode: 'forget-local' + }) + expect(mocks.state.closeModal).toHaveBeenCalledTimes(1) + }) }) diff --git a/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx index 0b5bd3cdb46f..c559620d275e 100644 --- a/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx +++ b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx @@ -1,4 +1,4 @@ -import React, { useCallback } from 'react' +import React, { useCallback, useEffect, useState } from 'react' import { Dialog, DialogContent, @@ -13,6 +13,7 @@ import { translate } from '@/i18n/i18n' import { getRepoExecutionHostId, isRuntimeOwnedSshTargetId, + parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' @@ -31,6 +32,15 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { const displayName = typeof modalData.displayName === 'string' ? modalData.displayName : '' const hostId = typeof modalData.hostId === 'string' ? (modalData.hostId as ExecutionHostId) : null + // Why: the owning host never answered the first attempt, so it still holds the project. The + // dialog stays open on that answer and re-offers the removal as a client-only forget. + const [ownerUnverifiable, setOwnerUnverifiable] = useState(false) + const [isRemoving, setIsRemoving] = useState(false) + useEffect(() => { + setOwnerUnverifiable(false) + setIsRemoving(false) + }, [isOpen, repoId, hostId]) + // 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 @@ -51,38 +61,67 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { sshConnectionId ) }) + // Only a `runtime:` owner can answer `owner-unverifiable`, so its name is the one the + // forget copy needs; fall back to the environment id when the catalog has no row for it. + const runtimeOwnerLabel = useAppStore((s) => { + const parsed = parseExecutionHostId(hostId) + if (parsed?.kind !== 'runtime') { + return null + } + return ( + s.runtimeEnvironments.find((environment) => environment.id === parsed.environmentId)?.name || + parsed.environmentId + ) + }) // Why: fragment concatenation around the styled name cannot be reordered by // SOV locales (#9294). Translate one full sentence with the name as a // sentinel token, then split on it to re-apply the inline emphasis. - const description = isRuntimeOwnedSshTargetId(sshConnectionId) + const description = ownerUnverifiable ? translate( - 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionVmRecipe', - 'This removes {{name}} from Orca. Its VM recipe determines whether the environment and its files are permanently deleted.', - { name: NAME_TOKEN } + 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionOwnerUnverifiable', + '{{host}} did not answer, so {{name}} is still registered there. Removing it now only clears this computer’s records — nothing on {{host}} is touched, and the project returns if that host reconnects.', + { name: NAME_TOKEN, host: runtimeOwnerLabel ?? '' } ) - : sshHostLabel + : isRuntimeOwnedSshTargetId(sshConnectionId) ? translate( - 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionSsh', - 'This only removes {{name}} from Orca. Its files stay on {{host}} — re-add that SSH host to recover it.', - { name: NAME_TOKEN, host: sshHostLabel } - ) - : translate( - 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionLocal', - 'This only removes {{name}} from Orca. It is still on your disk.', + 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionVmRecipe', + 'This removes {{name}} from Orca. Its VM recipe determines whether the environment and its files are permanently deleted.', { name: NAME_TOKEN } ) + : sshHostLabel + ? translate( + 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionSsh', + 'This only removes {{name}} from Orca. Its files stay on {{host}} — re-add that SSH host to recover it.', + { name: NAME_TOKEN, host: sshHostLabel } + ) + : translate( + 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionLocal', + 'This only removes {{name}} from Orca. It is still on your disk.', + { name: NAME_TOKEN } + ) const [descriptionBeforeName, descriptionAfterName] = description.split(NAME_TOKEN) - const handleConfirm = useCallback(() => { - if (repoId) { - void removeProject(repoId, { - ...(hostId ? { hostId } : {}), - errorFeedback: 'toast' - }) + const handleConfirm = useCallback(async () => { + if (!repoId) { + closeModal() + return + } + setIsRemoving(true) + const outcome = await removeProject(repoId, { + ...(hostId ? { hostId } : {}), + errorFeedback: 'toast', + ...(ownerUnverifiable ? { mode: 'forget-local' as const } : {}) + }) + setIsRemoving(false) + // Why: an unanswered host is not a failure to report and not a removal to celebrate — keep + // the dialog open so the only honest remaining action is the one the user now sees. + if (outcome.status === 'owner-unverifiable') { + setOwnerUnverifiable(true) + return } closeModal() - }, [closeModal, hostId, removeProject, repoId]) + }, [closeModal, hostId, ownerUnverifiable, removeProject, repoId]) const handleOpenChange = useCallback( (open: boolean) => { @@ -110,8 +149,13 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { - diff --git a/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts b/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts index e08a454f4244..bf47a547b541 100644 --- a/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts +++ b/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts @@ -54,13 +54,16 @@ export async function clearSshHostWorkspaces( // clearing Orca's records without a successful remote call. for (const repoId of resolution.hostRepoIds) { try { - await store.removeProject(repoId, { hostId }) + const outcome = await store.removeProject(repoId, { hostId }) + if (outcome.status !== 'removed') { + failedIds.push(repoId) + } } 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. + // Why: removeProject reports its own outcome, but a returned status is not proof of the + // durable change. 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) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 6a8d0b8a0302..ee060bd76085 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -5286,7 +5286,9 @@ "b79b39d865": "Remove Project", "removeDescriptionSsh": "This only removes {{name}} from Orca. Its files stay on {{host}} — re-add that SSH host to recover it.", "removeDescriptionLocal": "This only removes {{name}} from Orca. It is still on your disk.", - "removeDescriptionVmRecipe": "This removes {{name}} from Orca. Its VM recipe determines whether the environment and its files are permanently deleted." + "removeDescriptionVmRecipe": "This removes {{name}} from Orca. Its VM recipe determines whether the environment and its files are permanently deleted.", + "removeDescriptionOwnerUnverifiable": "{{host}} did not answer, so {{name}} is still registered there. Removing it now only clears this computer’s records — nothing on {{host}} is touched, and the project returns if that host reconnects.", + "removeFromOrcaOnly": "Remove from Orca" }, "ScrollToCurrentWorkspaceToolbarButton": { "23989bb663": "Reveal active workspace" @@ -12041,6 +12043,10 @@ "TerminalRenderingSection": { "6d4c55bacc": "Inline Images", "fffab5890b": "Display images directly in the terminal using SIXEL, iTerm2 (IIP), and Kitty graphics protocols." + }, + "settingsProjectList": { + "removeOwnerUnverifiable": "Could not reach the host that owns this project", + "removeOwnerUnverifiableDescription": "It is still registered on {{host}}. Reconnect that host and try again, or remove the project from the sidebar to clear this computer’s records only." } }, "right": { diff --git a/src/renderer/src/store/repos/project-removal-outcome.ts b/src/renderer/src/store/repos/project-removal-outcome.ts new file mode 100644 index 000000000000..cca1940992bb --- /dev/null +++ b/src/renderer/src/store/repos/project-removal-outcome.ts @@ -0,0 +1,26 @@ +import { + isRecoverableRemoteRuntimeConnectionError, + toRemoteRuntimeClientErrorLike +} from '../../../../shared/remote-runtime-client-error-classification' + +/** + * What `removeProject` actually did. + * + * `owner-unverifiable` is its own answer, not a flavour of failure: the owning host never + * answered, so its catalog is untouched and the project is still registered there. Loss of + * contact is never evidence of absence (docs/reference/ssh-execution-boundary.md), so a caller + * must not report the project as removed — it may instead offer the client-only forget, which + * clears Orca's records here and claims nothing about the host. + */ +export type RemoveProjectOutcome = + | { status: 'removed' } + | { status: 'owner-unverifiable' } + | { status: 'failed' } + +/** + * True only when the owning host never answered. A host that answers and refuses — unauthorized, + * protocol mismatch, an error from its own catalog — is positive evidence and stays a failure. + */ +export function isOwnerContactFailure(error: unknown): boolean { + return isRecoverableRemoteRuntimeConnectionError(toRemoteRuntimeClientErrorLike(error)) +} diff --git a/src/renderer/src/store/repos/repo-removal.ts b/src/renderer/src/store/repos/repo-removal.ts index 43525c3bba8c..94a44a1b0136 100644 --- a/src/renderer/src/store/repos/repo-removal.ts +++ b/src/renderer/src/store/repos/repo-removal.ts @@ -22,6 +22,7 @@ import type { RepoSlice } from './repo-state' import { ERROR_TOAST_DURATION } from './repo-state' import { mergeProjectCompatibilityForHostRepoChange } from './repo-catalog-identity' import { settingsForRepoOwner } from './owner-routing' +import { isOwnerContactFailure } from './project-removal-outcome' export function worktreeBelongsToHost(worktree: { hostId?: string }, hostId: string): boolean { return (worktree.hostId ?? LOCAL_EXECUTION_HOST_ID) === hostId @@ -52,6 +53,9 @@ export function createRepoRemovalActions( ): Pick { return { removeProject: async (projectId, options) => { + // Why: forget-local never dispatches to the owning host — it clears this client's records + // only, so a host that cannot acknowledge keeps its own catalog. + const forgetLocalOnly = options?.mode === 'forget-local' try { // Why: pass an explicit hostId so a duplicate id across hosts resolves to the intended row, not the focused-host fallback. const ownerRepo = findRepoForHost(get().repos, projectId, { @@ -59,7 +63,7 @@ export function createRepoRemovalActions( hostId: options?.hostId }) if (!ownerRepo) { - return + return { status: 'removed' } } const ownerHostId = getRepoExecutionHostId(ownerRepo) const runtimeSshTargetId = ownerRepo.connectionId @@ -83,15 +87,24 @@ export function createRepoRemovalActions( const idExistsOnOtherHost = get().repos.some( (repo) => repo.id === projectId && getRepoExecutionHostId(repo) !== ownerHostId ) + const dispatchesToOwningRuntime = target.kind !== 'local' && !forgetLocalOnly try { - await (target.kind === 'local' - ? idExistsOnOtherHost + // A forget always addresses one host's row, so it takes the host-scoped local call even + // when the id is unique — the catalog it belongs to is deliberately left alone. + await (dispatchesToOwningRuntime + ? callRuntimeRpc(target, 'repo.rm', { repo: projectId }, { timeoutMs: 15_000 }) + : idExistsOnOtherHost || forgetLocalOnly ? window.api.repos.removeForHost({ repoId: projectId, hostId: ownerHostId }) - : window.api.repos.remove({ repoId: projectId }) - : callRuntimeRpc(target, 'repo.rm', { repo: projectId }, { timeoutMs: 15_000 })) + : window.api.repos.remove({ repoId: projectId })) } catch (err) { // Why: the owner already dropped this project, so purge the local ghost row instead of aborting (#11994). if (!hasRuntimeRpcErrorCode(err, 'repo_not_found')) { + // Why: the host never answered, so its catalog still holds the project. Purging here + // would claim a removal that never happened; report it so the caller can offer the + // client-only forget instead (docs/reference/ssh-execution-boundary.md). + if (dispatchesToOwningRuntime && isOwnerContactFailure(err)) { + return { status: 'owner-unverifiable' } + } throw err } } @@ -130,7 +143,9 @@ export function createRepoRemovalActions( ] : [] const killedTabIds = new Set() - if (target.kind === 'environment') { + // Why: a forget touches nothing on the owning host, terminals included — those PTYs stay + // live and unverifiable, and asking a host that never answered would only stall the purge. + if (target.kind === 'environment' && !forgetLocalOnly) { await Promise.allSettled( worktreeIds.map((worktreeId) => callRuntimeRpc( @@ -269,6 +284,7 @@ export function createRepoRemovalActions( : {}) } }) + return { status: 'removed' } } catch (err) { console.error('Failed to remove repo:', err) // Why: bulk and background callers aggregate their own failures, so only opted-in single-project entry points toast (#11994). @@ -281,6 +297,7 @@ export function createRepoRemovalActions( } ) } + return { status: 'failed' } } } } diff --git a/src/renderer/src/store/repos/repo-state.ts b/src/renderer/src/store/repos/repo-state.ts index 2223626f44bb..71343c66017a 100644 --- a/src/renderer/src/store/repos/repo-state.ts +++ b/src/renderer/src/store/repos/repo-state.ts @@ -26,6 +26,7 @@ import type { FolderWorkspacePathStatusRequest } from '../../../../shared/folder-workspace-path-status' import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { RemoveProjectOutcome } from './project-removal-outcome' export const ERROR_TOAST_DURATION = 60_000 @@ -248,10 +249,16 @@ export type RepoSlice = { ) => Promise // options.hostId disambiguates which host's row to remove when the id exists on multiple hosts; else the focused host is assumed. // options.errorFeedback defaults to 'silent' so bulk/background callers keep their own aggregate reporting. + // options.mode 'forget-local' clears this client's records without calling the owning host; the + // returned 'owner-unverifiable' is what earns a caller the right to offer it. removeProject: ( projectId: string, - options?: { hostId?: ExecutionHostId; errorFeedback?: 'toast' | 'silent' } - ) => Promise + options?: { + hostId?: ExecutionHostId + errorFeedback?: 'toast' | 'silent' + mode?: 'delete-on-host' | 'forget-local' + } + ) => Promise updateProject: (projectId: string, updates: ProjectUpdate) => Promise // options.hostId targets a specific host's row + RPC target when the id exists on multiple hosts; else the focused host is assumed. updateRepo: ( diff --git a/src/renderer/src/store/slices/repos-remove-missing-remote-project.test.ts b/src/renderer/src/store/slices/repos-remove-missing-remote-project.test.ts index 78e7896f7c5d..b35dbc677cb7 100644 --- a/src/renderer/src/store/slices/repos-remove-missing-remote-project.test.ts +++ b/src/renderer/src/store/slices/repos-remove-missing-remote-project.test.ts @@ -5,6 +5,11 @@ * aborted the local purge before the `set()` — the ghost row survived and nothing was * surfaced to the user. Only `repo_not_found` is tolerated; any other failure must keep * the row, and the error toast is opt-in so bulk/background callers stay silent. + * + * A later pass splits "any other failure" in two. A host that answers and refuses is a failure and + * toasts as before. A host that never answers is `owner-unverifiable`: the row is still kept — + * its catalog was not touched — but the caller is told so it can offer the client-only forget, + * so the store does not spend a dead-end toast on it. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import { toast } from 'sonner' @@ -109,18 +114,19 @@ describe('removeProject when the owning host already dropped the project', () => expect(store.getState().repos.map((repo) => repo.id)).toEqual(['project-a']) }) - it('keeps the row and stays silent when the remote fails for another reason', async () => { - answerRepoRmWith('runtime_unavailable') + it('keeps the row and stays silent when the remote refuses', async () => { + answerRepoRmWith('unauthorized') const store = seedRemoteProjects([liveRemoteRepo, staleRemoteRepo]) - await store.getState().removeProject('project-b', { hostId: 'runtime:env-1' }) + const outcome = await store.getState().removeProject('project-b', { hostId: 'runtime:env-1' }) + expect(outcome).toEqual({ status: 'failed' }) expect(store.getState().repos.map((repo) => repo.id)).toEqual(['project-a', 'project-b']) expect(toast.error).not.toHaveBeenCalled() }) it('toasts once for a genuine failure when the caller opts in', async () => { - answerRepoRmWith('runtime_unavailable') + answerRepoRmWith('unauthorized') const store = seedRemoteProjects([liveRemoteRepo, staleRemoteRepo]) await store @@ -130,6 +136,41 @@ describe('removeProject when the owning host already dropped the project', () => expect(toast.error).toHaveBeenCalledTimes(1) }) + it('reports owner-unverifiable without a toast when the host never answers', async () => { + answerRepoRmWith('runtime_unavailable') + const store = seedRemoteProjects([liveRemoteRepo, staleRemoteRepo]) + + const outcome = await store + .getState() + .removeProject('project-b', { hostId: 'runtime:env-1', errorFeedback: 'toast' }) + + // The host's catalog was never reached, so the row must survive: a purge here would claim + // a removal that did not happen. + expect(outcome).toEqual({ status: 'owner-unverifiable' }) + expect(store.getState().repos.map((repo) => repo.id)).toEqual(['project-a', 'project-b']) + expect(toast.error).not.toHaveBeenCalled() + }) + + it('forget-local clears the row without ever calling the unreachable host', async () => { + answerRepoRmWith('runtime_unavailable') + const store = seedRemoteProjects([liveRemoteRepo, staleRemoteRepo]) + + const outcome = await store + .getState() + .removeProject('project-b', { hostId: 'runtime:env-1', mode: 'forget-local' }) + + expect(outcome).toEqual({ status: 'removed' }) + expect(store.getState().repos.map((repo) => repo.id)).toEqual(['project-a']) + // Nothing at all is asked of the host — not the removal, not the terminal teardown. + expect(runtimeEnvironmentCall).not.toHaveBeenCalled() + // Host-scoped so a same-id row on another host keeps its own records. + expect(reposRemoveForHost).toHaveBeenCalledWith({ + repoId: 'project-b', + hostId: 'runtime:env-1' + }) + expect(reposRemove).not.toHaveBeenCalled() + }) + it('leaves a same-id project on another host untouched', async () => { answerRepoRmWith('repo_not_found') const store = seedRemoteProjects([liveRemoteRepo, staleRemoteRepo, localTwinRepo]) From 8e7e40611512e79b7794142403ed903b67ca5045 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 23 Sep 2026 10:46:15 -0400 Subject: [PATCH 2/3] fix(repos): address review on the unreachable-host removal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - forget-local no longer reaches the ephemeral-VM teardown. That branch destroys the project's VM, which contradicts "clears this client's records only", so the mode is refused for a runtime-owned SSH target rather than leaking a live VM or quietly breaking the promise. Unreachable in practice — those repos dispatch locally and never answer owner-unverifiable — so this pins the invariant instead of relying on it. - Stop asserting what a lost answer cannot establish. A timeout proves only that no reply arrived; the host may already have removed the project. The outcome doc and the dialog now say the result is unknown and make the return conditional, and note that retrying is safe because a removal that did land comes back as the tolerated repo_not_found. - Guard a late removal against the dialog that replaced it. Cancel stays live during the host call and closeModal is global, so a stale completion could dismiss the next dialog. The reset effect bumps a token on teardown and the completion fences on it. - The settings toast names the host instead of printing a raw runtime: id, via the existing selectExecutionHostDisplayLabel — which also honours a user's per-host rename. Co-Authored-By: Claude Opus 5 (1M context) --- .../settings/settings-project-list.test.ts | 14 +++++-- .../settings/settings-project-list.ts | 11 +++-- .../settings/use-settings-store-model.ts | 7 +++- .../sidebar/RemoveFolderDialog.test.tsx | 29 +++++++++++++- .../components/sidebar/RemoveFolderDialog.tsx | 40 +++++++++++-------- src/renderer/src/i18n/locales/en.json | 4 +- .../store/repos/project-removal-outcome.ts | 20 ++++++---- src/renderer/src/store/repos/repo-removal.ts | 19 ++++++--- ...pos-ephemeral-vm-cleanup-retention.test.ts | 22 ++++++++++ 9 files changed, 126 insertions(+), 40 deletions(-) diff --git a/src/renderer/src/components/settings/settings-project-list.test.ts b/src/renderer/src/components/settings/settings-project-list.test.ts index 0050df2ffc34..59bddb34e56f 100644 --- a/src/renderer/src/components/settings/settings-project-list.test.ts +++ b/src/renderer/src/components/settings/settings-project-list.test.ts @@ -269,6 +269,9 @@ describe('removeSettingsProjectFromAllHosts', () => { vi.mocked(toast.error).mockReset() }) + const resolveHostLabel = (hostId: string): string => + hostId === 'runtime:home-mac' ? 'Home Mac' : hostId + it('removes every host setup with its own hostId and skips setups without a repo row', async () => { const removeProject = vi.fn().mockResolvedValue({ status: 'removed' }) const setups = [ @@ -277,7 +280,7 @@ describe('removeSettingsProjectFromAllHosts', () => { makeSetup({ hostId: 'runtime:home-mac', repoId: 'remote-9' }) ] - await removeSettingsProjectFromAllHosts(setups, removeProject) + await removeSettingsProjectFromAllHosts(setups, removeProject, resolveHostLabel) // errorFeedback: this is a user-initiated removal, so a failure must surface (#11994). expect(removeProject.mock.calls).toEqual([ @@ -302,7 +305,7 @@ describe('removeSettingsProjectFromAllHosts', () => { makeSetup({ hostId: 'runtime:home-mac', repoId: 'remote-9' }) ] - const pending = removeSettingsProjectFromAllHosts(setups, removeProject) + const pending = removeSettingsProjectFromAllHosts(setups, removeProject, resolveHostLabel) await Promise.resolve() expect(removeProject).toHaveBeenCalledTimes(1) @@ -323,9 +326,12 @@ describe('removeSettingsProjectFromAllHosts', () => { makeSetup({ hostId: 'runtime:home-mac', repoId: 'remote-9' }) ] - await removeSettingsProjectFromAllHosts(setups, removeProject) + await removeSettingsProjectFromAllHosts(setups, removeProject, resolveHostLabel) expect(toast.error).toHaveBeenCalledTimes(1) - expect(vi.mocked(toast.error).mock.calls[0]?.[1]?.description).toContain('runtime:home-mac') + // The host's own name, never the raw `runtime:` routing id. + const description = vi.mocked(toast.error).mock.calls[0]?.[1]?.description + expect(description).toContain('Home Mac') + expect(description).not.toContain('runtime:home-mac') }) }) diff --git a/src/renderer/src/components/settings/settings-project-list.ts b/src/renderer/src/components/settings/settings-project-list.ts index 4153bfad4f95..d3d8d6d85434 100644 --- a/src/renderer/src/components/settings/settings-project-list.ts +++ b/src/renderer/src/components/settings/settings-project-list.ts @@ -180,7 +180,10 @@ export async function removeSettingsProjectFromAllHosts( removeProject: ( repoId: string, options: { hostId: ExecutionHostId; errorFeedback?: 'toast' | 'silent' } - ) => Promise + ) => Promise, + // Why: required, not defaulted — the fallback label is a raw host id, which means nothing to a + // reader, and a caller that forgets to pass this would ship it into the toast below. + resolveHostLabel: (hostId: ExecutionHostId) => string ): Promise { for (const setup of setups) { if (setup.repoId.trim().length > 0) { @@ -191,6 +194,8 @@ export async function removeSettingsProjectFromAllHosts( }) // Why: an unanswered host is not a store failure, so it carries no toast of its own. This // pane has no per-host forget affordance, so say what happened rather than look successful. + // Retrying is safe once the host answers: a removal that did land reports `repo_not_found`, + // which the store reconciles instead of failing on. if (outcome.status === 'owner-unverifiable') { toast.error( translate( @@ -200,8 +205,8 @@ export async function removeSettingsProjectFromAllHosts( { description: translate( 'auto.components.settings.settingsProjectList.removeOwnerUnverifiableDescription', - 'It is still registered on {{host}}. Reconnect that host and try again, or remove the project from the sidebar to clear this computer’s records only.', - { host: setup.hostId } + 'Orca could not confirm the removal with {{host}}. Reconnect that host and try again, or remove the project from the sidebar to clear this computer’s records only.', + { host: resolveHostLabel(setup.hostId) } ) } ) diff --git a/src/renderer/src/components/settings/use-settings-store-model.ts b/src/renderer/src/components/settings/use-settings-store-model.ts index fa48d63d2cca..7bea52c82a86 100644 --- a/src/renderer/src/components/settings/use-settings-store-model.ts +++ b/src/renderer/src/components/settings/use-settings-store-model.ts @@ -3,6 +3,7 @@ import type { OrcaHooks } from '../../../../shared/orca-yaml-hook-types' import type { ProjectHostSetup } from '../../../../shared/project-types' import { DEFAULT_APP_FONT_FAMILY } from '../../../../shared/constants' import { useAppStore } from '../../store' +import { selectExecutionHostDisplayLabel } from '@/lib/execution-host-display-label' import { useSystemPrefersDark } from '@/components/terminal-pane/use-system-prefers-dark' import { isMacUserAgent, isWindowsUserAgent } from '@/components/terminal-pane/pane-helpers' import { useConfirmationDialog } from '@/components/confirmation-dialog-context' @@ -72,7 +73,11 @@ export function useSettingsStoreModel() { // Why: pane-level "Remove Project" removes every host setup, not just the selected host (per-host remove lives in "Available Hosts"). const removeProjectAllHosts = useCallback( (setups: readonly ProjectHostSetup[]): Promise => - removeSettingsProjectFromAllHosts(setups, removeProject), + // Why: read the host catalogs when the removal reports back, not at render — a rename or a + // newly-hydrated environment landing mid-removal should still name the host correctly. + removeSettingsProjectFromAllHosts(setups, removeProject, (hostId) => + selectExecutionHostDisplayLabel(useAppStore.getState(), hostId) + ), [removeProject] ) diff --git a/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx b/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx index b81eced1f56f..0b2de3dea02d 100644 --- a/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx +++ b/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx @@ -19,6 +19,8 @@ const mocks = vi.hoisted(() => { hostId: 'ssh:target-1' } as Record, repos: [] as Repo[], + // Read by selectExecutionHostDisplayLabel: a per-host rename override wins over the name. + settings: null, runtimeEnvironments, sshTargetLabels: new Map(), removedSshTargetLabels: new Map(), @@ -138,8 +140,11 @@ describe('RemoveFolderDialog', () => { await userEvent.click(screen.getByRole('button', { name: 'Remove' })) expect(mocks.state.closeModal).not.toHaveBeenCalled() - expect(screen.getByText(/alexdevbox2 did not answer/)).toBeInTheDocument() - expect(screen.getByText(/returns if that host reconnects/)).toBeInTheDocument() + // Names the host, and claims nothing about what it did — a lost answer is not a removal that + // did not happen. + expect(screen.getByText(/Orca could not reach alexdevbox2/)).toBeInTheDocument() + expect(screen.getByText(/was removed there is unknown/)).toBeInTheDocument() + expect(screen.getByText(/if it is still registered on alexdevbox2/)).toBeInTheDocument() await userEvent.click(screen.getByRole('button', { name: 'Remove from Orca' })) @@ -150,4 +155,24 @@ describe('RemoveFolderDialog', () => { }) expect(mocks.state.closeModal).toHaveBeenCalledTimes(1) }) + + // Cancel stays live during the ~15s host call. closeModal is global, so a late answer from a + // dismissed invocation must not dismiss whichever dialog the user opened next. + it('ignores a removal that finishes after its dialog was dismissed', async () => { + mocks.state.repos = [repo('target-1', 'ssh:target-1')] + let finishRemoval: ((outcome: { status: string }) => void) | undefined + mocks.state.removeProject.mockReturnValueOnce( + new Promise((resolve) => { + finishRemoval = resolve + }) + ) + const view = render() + + await userEvent.click(screen.getByRole('button', { name: 'Remove' })) + view.unmount() + finishRemoval?.({ status: 'removed' }) + await Promise.resolve() + + expect(mocks.state.closeModal).not.toHaveBeenCalled() + }) }) diff --git a/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx index c559620d275e..ce129359b605 100644 --- a/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx +++ b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useState } from 'react' +import React, { useCallback, useEffect, useRef, useState } from 'react' import { Dialog, DialogContent, @@ -16,6 +16,7 @@ import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import { selectExecutionHostDisplayLabel } from '@/lib/execution-host-display-label' // Why: interpolated into the sentence so locales control where the name sits; // U+0000 cannot appear in a real project name, so the split is unambiguous. @@ -32,13 +33,19 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { const displayName = typeof modalData.displayName === 'string' ? modalData.displayName : '' const hostId = typeof modalData.hostId === 'string' ? (modalData.hostId as ExecutionHostId) : null - // Why: the owning host never answered the first attempt, so it still holds the project. The - // dialog stays open on that answer and re-offers the removal as a client-only forget. + // Why: no answer arrived from the owning host on the first attempt, so what it did is unknown. + // The dialog stays open on that answer and re-offers the removal as a client-only forget. const [ownerUnverifiable, setOwnerUnverifiable] = useState(false) const [isRemoving, setIsRemoving] = useState(false) + // Why: Cancel stays live while the host is being asked, and this dialog unmounts when the modal + // closes. Bumping on teardown fences a late answer out of the invocation that replaced it. + const removalTokenRef = useRef(0) useEffect(() => { setOwnerUnverifiable(false) setIsRemoving(false) + return () => { + removalTokenRef.current += 1 + } }, [isOpen, repoId, hostId]) // Why: for an SSH project the files live on the remote host's disk, not the @@ -61,18 +68,13 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { sshConnectionId ) }) - // Only a `runtime:` owner can answer `owner-unverifiable`, so its name is the one the - // forget copy needs; fall back to the environment id when the catalog has no row for it. - const runtimeOwnerLabel = useAppStore((s) => { - const parsed = parseExecutionHostId(hostId) - if (parsed?.kind !== 'runtime') { - return null - } - return ( - s.runtimeEnvironments.find((environment) => environment.id === parsed.environmentId)?.name || - parsed.environmentId - ) - }) + // Only a `runtime:` owner can answer `owner-unverifiable`, so its name is the one the forget + // copy needs. + const runtimeOwnerLabel = useAppStore((s) => + hostId && parseExecutionHostId(hostId)?.kind === 'runtime' + ? selectExecutionHostDisplayLabel(s, hostId) + : null + ) // Why: fragment concatenation around the styled name cannot be reordered by // SOV locales (#9294). Translate one full sentence with the name as a @@ -80,7 +82,7 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { const description = ownerUnverifiable ? translate( 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionOwnerUnverifiable', - '{{host}} did not answer, so {{name}} is still registered there. Removing it now only clears this computer’s records — nothing on {{host}} is touched, and the project returns if that host reconnects.', + 'Orca could not reach {{host}}, so whether {{name}} was removed there is unknown. Removing it now only clears this computer’s records — if it is still registered on {{host}}, it returns when that host reconnects.', { name: NAME_TOKEN, host: runtimeOwnerLabel ?? '' } ) : isRuntimeOwnedSshTargetId(sshConnectionId) @@ -107,12 +109,18 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { closeModal() return } + const token = removalTokenRef.current setIsRemoving(true) const outcome = await removeProject(repoId, { ...(hostId ? { hostId } : {}), errorFeedback: 'toast', ...(ownerUnverifiable ? { mode: 'forget-local' as const } : {}) }) + // Why: this invocation was cancelled or replaced while the host was being asked. closeModal is + // global, so acting now would dismiss whichever dialog the user opened next. + if (token !== removalTokenRef.current) { + return + } setIsRemoving(false) // Why: an unanswered host is not a failure to report and not a removal to celebrate — keep // the dialog open so the only honest remaining action is the one the user now sees. diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index ee060bd76085..4d9f8b1b90f5 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -5287,7 +5287,7 @@ "removeDescriptionSsh": "This only removes {{name}} from Orca. Its files stay on {{host}} — re-add that SSH host to recover it.", "removeDescriptionLocal": "This only removes {{name}} from Orca. It is still on your disk.", "removeDescriptionVmRecipe": "This removes {{name}} from Orca. Its VM recipe determines whether the environment and its files are permanently deleted.", - "removeDescriptionOwnerUnverifiable": "{{host}} did not answer, so {{name}} is still registered there. Removing it now only clears this computer’s records — nothing on {{host}} is touched, and the project returns if that host reconnects.", + "removeDescriptionOwnerUnverifiable": "Orca could not reach {{host}}, so whether {{name}} was removed there is unknown. Removing it now only clears this computer’s records — if it is still registered on {{host}}, it returns when that host reconnects.", "removeFromOrcaOnly": "Remove from Orca" }, "ScrollToCurrentWorkspaceToolbarButton": { @@ -12046,7 +12046,7 @@ }, "settingsProjectList": { "removeOwnerUnverifiable": "Could not reach the host that owns this project", - "removeOwnerUnverifiableDescription": "It is still registered on {{host}}. Reconnect that host and try again, or remove the project from the sidebar to clear this computer’s records only." + "removeOwnerUnverifiableDescription": "Orca could not confirm the removal with {{host}}. Reconnect that host and try again, or remove the project from the sidebar to clear this computer’s records only." } }, "right": { diff --git a/src/renderer/src/store/repos/project-removal-outcome.ts b/src/renderer/src/store/repos/project-removal-outcome.ts index cca1940992bb..9619a46fc05d 100644 --- a/src/renderer/src/store/repos/project-removal-outcome.ts +++ b/src/renderer/src/store/repos/project-removal-outcome.ts @@ -6,11 +6,16 @@ import { /** * What `removeProject` actually did. * - * `owner-unverifiable` is its own answer, not a flavour of failure: the owning host never - * answered, so its catalog is untouched and the project is still registered there. Loss of - * contact is never evidence of absence (docs/reference/ssh-execution-boundary.md), so a caller - * must not report the project as removed — it may instead offer the client-only forget, which - * clears Orca's records here and claims nothing about the host. + * `owner-unverifiable` is its own answer, not a flavour of failure: no answer arrived from the + * owning host, so what that host did is **unknown**. It may never have seen the request, or it may + * have removed the project and lost the reply past the timeout. Neither reading may be asserted + * (docs/reference/ssh-execution-boundary.md), so a caller must not report the project as removed, + * must not claim the host still holds it, and must keep its own row — a purge here would state an + * outcome nobody observed. The one honest action left is the client-only forget, which clears + * Orca's records and says nothing about the host either way. + * + * Retrying once the host answers is safe: `repo.rm` reporting `repo_not_found` is tolerated, so a + * removal that did land is reconciled instead of failing the second attempt. */ export type RemoveProjectOutcome = | { status: 'removed' } @@ -18,8 +23,9 @@ export type RemoveProjectOutcome = | { status: 'failed' } /** - * True only when the owning host never answered. A host that answers and refuses — unauthorized, - * protocol mismatch, an error from its own catalog — is positive evidence and stays a failure. + * True only when no answer reached us — a dropped transport, a timeout, an unreachable runtime. + * A host that answers and refuses — unauthorized, protocol mismatch, an error from its own + * catalog — is positive evidence and stays a failure. */ export function isOwnerContactFailure(error: unknown): boolean { return isRecoverableRemoteRuntimeConnectionError(toRemoteRuntimeClientErrorLike(error)) diff --git a/src/renderer/src/store/repos/repo-removal.ts b/src/renderer/src/store/repos/repo-removal.ts index 94a44a1b0136..2275c1e319d2 100644 --- a/src/renderer/src/store/repos/repo-removal.ts +++ b/src/renderer/src/store/repos/repo-removal.ts @@ -54,7 +54,7 @@ export function createRepoRemovalActions( return { removeProject: async (projectId, options) => { // Why: forget-local never dispatches to the owning host — it clears this client's records - // only, so a host that cannot acknowledge keeps its own catalog. + // only, and states nothing about what that host holds. const forgetLocalOnly = options?.mode === 'forget-local' try { // Why: pass an explicit hostId so a duplicate id across hosts resolves to the intended row, not the focused-host fallback. @@ -69,6 +69,15 @@ export function createRepoRemovalActions( const runtimeSshTargetId = ownerRepo.connectionId // Why: an SSH per-workspace-env's workspace is the repo's main worktree, so removal routes here; tear down its ephemeral runtime first so it doesn't leak. if (runtimeSshTargetId && isRuntimeOwnedSshTargetId(runtimeSshTargetId)) { + // Why: this project's removal exists to destroy that VM, and forget-local is defined as + // touching nothing outside this client — both cannot hold, so refuse rather than leak a + // live VM or quietly break the promise. Unreachable today: an ephemeral-VM project is + // SSH-owned, so its removal dispatches locally and never answers `owner-unverifiable`. + if (forgetLocalOnly) { + throw new Error( + 'This project runs on a cloud VM, so it can only be removed by destroying that VM.' + ) + } const cleanup = await cleanupEphemeralVmRuntimesForDeleted({ workspaceIds: getKnownRepoWorktreeIds(get(), projectId, ownerHostId), runtimeOwnedSshTargetIds: [runtimeSshTargetId] @@ -99,8 +108,8 @@ export function createRepoRemovalActions( } catch (err) { // Why: the owner already dropped this project, so purge the local ghost row instead of aborting (#11994). if (!hasRuntimeRpcErrorCode(err, 'repo_not_found')) { - // Why: the host never answered, so its catalog still holds the project. Purging here - // would claim a removal that never happened; report it so the caller can offer the + // Why: no answer arrived, so whether the host removed it is unknown. Purging here + // would assert an outcome nobody observed; report it so the caller can offer the // client-only forget instead (docs/reference/ssh-execution-boundary.md). if (dispatchesToOwningRuntime && isOwnerContactFailure(err)) { return { status: 'owner-unverifiable' } @@ -143,8 +152,8 @@ export function createRepoRemovalActions( ] : [] const killedTabIds = new Set() - // Why: a forget touches nothing on the owning host, terminals included — those PTYs stay - // live and unverifiable, and asking a host that never answered would only stall the purge. + // Why: a forget touches nothing on the owning host, terminals included — those PTYs are + // left unverifiable, and asking a host that never answered would only stall the purge. if (target.kind === 'environment' && !forgetLocalOnly) { await Promise.allSettled( worktreeIds.map((worktreeId) => diff --git a/src/renderer/src/store/slices/repos-ephemeral-vm-cleanup-retention.test.ts b/src/renderer/src/store/slices/repos-ephemeral-vm-cleanup-retention.test.ts index afc54b88af16..220941615336 100644 --- a/src/renderer/src/store/slices/repos-ephemeral-vm-cleanup-retention.test.ts +++ b/src/renderer/src/store/slices/repos-ephemeral-vm-cleanup-retention.test.ts @@ -47,3 +47,25 @@ it('retains a runtime-owned SSH project when VM cleanup fails', async () => { expect.objectContaining({ description: expect.stringContaining('Retry cleanup') }) ) }) + +// forget-local promises to touch nothing outside this client, and this project's removal exists +// to destroy its VM — both cannot hold, so the mode is refused rather than silently leaking a +// live VM or quietly breaking the promise. +it('refuses forget-local for a runtime-owned SSH project instead of leaking its VM', async () => { + const runtimeRepo: Repo = { ...sshRepo, connectionId: 'runtime-ssh-runtime-1' } + const store = createTestStore() + store.setState({ repos: [runtimeRepo], activeRepoId: runtimeRepo.id }) + + const outcome = await store + .getState() + .removeProject(runtimeRepo.id, { errorFeedback: 'toast', mode: 'forget-local' }) + + expect(outcome).toEqual({ status: 'failed' }) + expect(store.getState().repos).toEqual([runtimeRepo]) + expect(ephemeralVmCleanup).not.toHaveBeenCalled() + expect(reposRemove).not.toHaveBeenCalled() + expect(toast.error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: expect.stringContaining('destroying that VM') }) + ) +}) From 98031b307e4bc9d83ae6bd217b8e2e01ea66abf8 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 23 Sep 2026 13:03:44 -0400 Subject: [PATCH 3/3] fix(repos): say what a silent owner actually proves MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Six review findings on the unreachable-owner removal path. A manual disconnect is the client refusing to dispatch, so the host never answered — it now reads as owner-unverifiable instead of a flat failure. The classification lives here rather than in RECOVERABLE_CODES, which means "retry or reconnect" and drives loops that would spin against an environment the user deliberately switched off. A lost answer proves nothing either way, so the copy stops promising the catalog is untouched and says the request may never have arrived or may have been carried out with the reply lost. The host name in that sentence now resolves the way removeProject does, so an ssh row or a modal opened without a hostId no longer renders a blank, and a missing environment record falls back to "that host" instead of a routing slug. A forget-local host clear forwards its mode for repo rows, so it can no longer dispatch repo.rm or tear down an ephemeral VM during an operation defined as touching nothing outside this client. A paired web client has no records of its own to clear, so it gets the explanation without a button whose only outcome was a throw. The removal spinner appears after 200ms, so a slow remote call reads as pending while a local one does not flicker. Co-Authored-By: Claude Opus 5 (1M context) --- .../sidebar/RemoveFolderDialog.test.tsx | 106 ++++++++++++- .../components/sidebar/RemoveFolderDialog.tsx | 90 ++++++++--- .../ssh-host-remove-workspaces.test.ts | 140 ++++++++++++++++++ .../sidebar/ssh-host-remove-workspaces.ts | 12 +- src/renderer/src/i18n/locales/en.json | 6 +- .../repos/project-removal-outcome.test.ts | 53 +++++++ .../store/repos/project-removal-outcome.ts | 39 ++++- src/renderer/src/store/repos/repo-removal.ts | 3 +- ...epos-remove-missing-remote-project.test.ts | 15 ++ .../web/preload-api/web-repositories-api.ts | 3 + 10 files changed, 433 insertions(+), 34 deletions(-) create mode 100644 src/renderer/src/components/sidebar/ssh-host-remove-workspaces.test.ts create mode 100644 src/renderer/src/store/repos/project-removal-outcome.test.ts diff --git a/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx b/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx index 0b2de3dea02d..559743415fb9 100644 --- a/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx +++ b/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import '@testing-library/jest-dom/vitest' -import { cleanup, render, screen } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { renderToStaticMarkup } from 'react-dom/server' import type { ButtonHTMLAttributes, ReactNode } from 'react' @@ -144,7 +144,10 @@ describe('RemoveFolderDialog', () => { // did not happen. expect(screen.getByText(/Orca could not reach alexdevbox2/)).toBeInTheDocument() expect(screen.getByText(/was removed there is unknown/)).toBeInTheDocument() - expect(screen.getByText(/if it is still registered on alexdevbox2/)).toBeInTheDocument() + // A timeout proves only that no reply arrived, so the copy must not present the host's + // catalog as provably untouched. + expect(screen.getByText(/may have been carried out and the reply lost/)).toBeInTheDocument() + expect(screen.getByText(/if the project is still registered there/)).toBeInTheDocument() await userEvent.click(screen.getByRole('button', { name: 'Remove from Orca' })) @@ -156,6 +159,105 @@ describe('RemoveFolderDialog', () => { expect(mocks.state.closeModal).toHaveBeenCalledTimes(1) }) + // The owner-unverifiable sentence interpolated a label that only a `runtime:` hostId produced, + // so every other opener rendered "Orca could not reach , so whether …". + it('names an ssh owner that never answered', async () => { + mocks.state.repos = [repo('target-1', 'ssh:target-1')] + mocks.state.removeProject.mockResolvedValueOnce({ status: 'owner-unverifiable' }) + render() + + await userEvent.click(screen.getByRole('button', { name: 'Remove' })) + + expect(screen.getByText(/Orca could not reach Persistent host/)).toBeInTheDocument() + expect(screen.queryByText(/could not reach ,/)).not.toBeInTheDocument() + }) + + it('names the owner when the modal was opened without a hostId', async () => { + delete mocks.state.modalData.hostId + mocks.state.repos = [repo('target-1', 'ssh:target-1')] + mocks.state.removeProject.mockResolvedValueOnce({ status: 'owner-unverifiable' }) + render() + + await userEvent.click(screen.getByRole('button', { name: 'Remove' })) + + expect(screen.getByText(/Orca could not reach Persistent host/)).toBeInTheDocument() + }) + + // The unreachable runtime is exactly the case whose environment record may be gone, and the + // label resolver answers the raw routing id when it is. + it('falls back to a generic host name instead of a raw runtime id', async () => { + mocks.state.modalData.hostId = 'runtime:env-a1b2' + mocks.state.repos = [repo(null, 'runtime:env-a1b2')] + mocks.state.runtimeEnvironments = [] + mocks.state.removeProject.mockResolvedValueOnce({ status: 'owner-unverifiable' }) + const view = render() + + await userEvent.click(screen.getByRole('button', { name: 'Remove' })) + + expect(screen.getByText(/Orca could not reach that host/)).toBeInTheDocument() + expect(view.container.textContent).not.toContain('env-a1b2') + }) + + // A paired web client's records are the runtime's own catalog, so repos.removeForHost throws + // there and the forget could only ever fail. Explain, do not offer. + it('withholds the client-only forget in a paired web client', async () => { + vi.stubGlobal('__ORCA_WEB_CLIENT__', true) + try { + mocks.state.modalData.hostId = 'runtime:env-1' + mocks.state.repos = [repo(null, 'runtime:env-1')] + mocks.state.runtimeEnvironments = [{ id: 'env-1', name: 'alexdevbox2' }] + mocks.state.removeProject.mockResolvedValueOnce({ status: 'owner-unverifiable' }) + render() + + await userEvent.click(screen.getByRole('button', { name: 'Remove' })) + + expect(screen.queryByRole('button', { name: 'Remove from Orca' })).not.toBeInTheDocument() + expect(screen.getByText(/keeps no records of its own to clear/)).toBeInTheDocument() + expect(mocks.state.removeProject).toHaveBeenCalledTimes(1) + expect(mocks.state.closeModal).not.toHaveBeenCalled() + } finally { + vi.unstubAllGlobals() + } + }) + + // An unreachable owner can hold the call for the full 15s timeout, but a local removal returns + // instantly — bind the disabled state now and the visible one on a timer (docs/STYLEGUIDE.md). + it('delays the pending spinner so a fast removal does not flicker', async () => { + vi.useFakeTimers() + try { + mocks.state.repos = [repo('target-1', 'ssh:target-1')] + let finishRemoval: ((outcome: { status: string }) => void) | undefined + mocks.state.removeProject.mockReturnValueOnce( + new Promise((resolve) => { + finishRemoval = resolve + }) + ) + const view = render() + + fireEvent.click(screen.getByRole('button', { name: 'Remove' })) + + expect(screen.getByRole('button', { name: 'Remove' })).toBeDisabled() + expect(view.container.querySelector('.animate-spin')).toBeNull() + + await act(async () => { + vi.advanceTimersByTime(199) + }) + expect(view.container.querySelector('.animate-spin')).toBeNull() + + await act(async () => { + vi.advanceTimersByTime(1) + }) + expect(view.container.querySelector('.animate-spin')).not.toBeNull() + + await act(async () => { + finishRemoval?.({ status: 'removed' }) + }) + expect(view.container.querySelector('.animate-spin')).toBeNull() + } finally { + vi.useRealTimers() + } + }) + // Cancel stays live during the ~15s host call. closeModal is global, so a late answer from a // dismissed invocation must not dismiss whichever dialog the user opened next. it('ignores a removal that finishes after its dialog was dismissed', async () => { diff --git a/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx index ce129359b605..351aa62d92a8 100644 --- a/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx +++ b/src/renderer/src/components/sidebar/RemoveFolderDialog.tsx @@ -1,4 +1,5 @@ import React, { useCallback, useEffect, useRef, useState } from 'react' +import { Loader2 } from 'lucide-react' import { Dialog, DialogContent, @@ -17,11 +18,17 @@ import { type ExecutionHostId } from '../../../../shared/execution-host' import { selectExecutionHostDisplayLabel } from '@/lib/execution-host-display-label' +import { findRepoForHost } from '@/store/slices/repo-host-identity' +import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' // Why: interpolated into the sentence so locales control where the name sits; // U+0000 cannot appear in a real project name, so the split is unambiguous. const NAME_TOKEN = '\u0000' +// Why: a local removal returns in milliseconds, so show the spinner only once the call is slow +// enough to read as one — a remote host, not a flicker (docs/STYLEGUIDE.md). +const REMOVING_SPINNER_DELAY_MS = 200 + const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { const activeModal = useAppStore((s) => s.activeModal) const modalData = useAppStore((s) => s.modalData) @@ -37,6 +44,7 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { // The dialog stays open on that answer and re-offers the removal as a client-only forget. const [ownerUnverifiable, setOwnerUnverifiable] = useState(false) const [isRemoving, setIsRemoving] = useState(false) + const [showRemovingSpinner, setShowRemovingSpinner] = useState(false) // Why: Cancel stays live while the host is being asked, and this dialog unmounts when the modal // closes. Bumping on teardown fences a late answer out of the invocation that replaced it. const removalTokenRef = useRef(0) @@ -48,6 +56,15 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { } }, [isOpen, repoId, hostId]) + useEffect(() => { + if (!isRemoving) { + setShowRemovingSpinner(false) + return + } + const timer = window.setTimeout(() => setShowRemovingSpinner(true), REMOVING_SPINNER_DELAY_MS) + return () => window.clearTimeout(timer) + }, [isRemoving]) + // 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 @@ -68,23 +85,49 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { sshConnectionId ) }) - // Only a `runtime:` owner can answer `owner-unverifiable`, so its name is the one the forget - // copy needs. - const runtimeOwnerLabel = useAppStore((s) => - hostId && parseExecutionHostId(hostId)?.kind === 'runtime' - ? selectExecutionHostDisplayLabel(s, hostId) - : null - ) + // Why: an `ssh:` row answers owner-unverifiable too, and the modal can be opened without a + // hostId (delete-worktree-flow), so resolve the owner the way removeProject will. + const ownerHostId = useAppStore((s) => { + if (hostId) { + return hostId + } + const ownerRepo = findRepoForHost(s.repos, repoId, { settings: s.settings }) + return ownerRepo ? getRepoExecutionHostId(ownerRepo) : null + }) + const resolvedOwnerLabel = useAppStore((s) => { + if (!ownerHostId) { + return null + } + const label = selectExecutionHostDisplayLabel(s, ownerHostId) + const parsed = parseExecutionHostId(ownerHostId) + // Why: with the environment record gone — the very case this copy describes — the resolver + // answers the routing id itself, and a slug like `env-a1b2` names nothing to the user. + return parsed?.kind === 'runtime' && label === parsed.environmentId ? null : label + }) + const ownerLabel = + resolvedOwnerLabel ?? + translate('auto.components.sidebar.RemoveFolderDialog.unnamedOwnerHost', 'that host') + + // Why: the client-only forget goes through repos.removeForHost, which a paired web client does + // not implement — it has one runtime and no records of its own to clear. Offering the button + // there would guarantee a failure, so that client gets the explanation without the action. + const canForgetLocally = !isPairedWebClientWindow() // Why: fragment concatenation around the styled name cannot be reordered by // SOV locales (#9294). Translate one full sentence with the name as a // sentinel token, then split on it to re-apply the inline emphasis. const description = ownerUnverifiable - ? translate( - 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionOwnerUnverifiable', - 'Orca could not reach {{host}}, so whether {{name}} was removed there is unknown. Removing it now only clears this computer’s records — if it is still registered on {{host}}, it returns when that host reconnects.', - { name: NAME_TOKEN, host: runtimeOwnerLabel ?? '' } - ) + ? canForgetLocally + ? translate( + 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionOwnerUnverifiable', + 'Orca could not reach {{host}}, so whether {{name}} was removed there is unknown — the request may never have arrived, or it may have been carried out and the reply lost. Removing it now clears this computer’s records only and sends nothing to {{host}}; if the project is still registered there, it comes back when that host reconnects.', + { name: NAME_TOKEN, host: ownerLabel } + ) + : translate( + 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionOwnerUnverifiableWeb', + 'Orca could not reach {{host}}, so whether {{name}} was removed there is unknown — the request may never have arrived, or it may have been carried out and the reply lost. This client keeps no records of its own to clear, so reconnect {{host}} and try again.', + { name: NAME_TOKEN, host: ownerLabel } + ) : isRuntimeOwnedSshTargetId(sshConnectionId) ? translate( 'auto.components.sidebar.RemoveFolderDialog.removeDescriptionVmRecipe', @@ -157,14 +200,21 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { - + {ownerUnverifiable && !canForgetLocally ? null : ( + + )} diff --git a/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.test.ts b/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.test.ts new file mode 100644 index 000000000000..602857e29496 --- /dev/null +++ b/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.test.ts @@ -0,0 +1,140 @@ +/** + * A `forget-local` host clear is defined as touching nothing outside this client. The repo loop + * used to drop the mode, so `removeProject` fell back to its default delete-on-host behaviour: + * for a repo whose owner is a runtime-owned SSH target that means destroying the project's + * ephemeral VM, and for a runtime-owned project it means dispatching `repo.rm` to a host the user + * asked not to contact (docs/reference/ssh-execution-boundary.md). + */ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { toast } from 'sonner' +import { createTestStore } from '@/store/slices/store-test-helpers' +import type { Repo } from '../../../../shared/repo-types' +import { + createCompatibleRuntimeStatusResponseIfNeeded, + type RuntimeEnvironmentCallRequest +} from '../../runtime/runtime-compatibility-test-fixture' +import { clearRuntimeCompatibilityCacheForTests } from '../../runtime/runtime-rpc-client' +import { clearSshHostWorkspaces } from './ssh-host-remove-workspaces' +import type { SshHostRemoveResolution } from './ssh-host-remove-resolution' + +vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) + +const cleanupEphemeralVmRuntimesForDeleted = vi.fn() +vi.mock('@/lib/ephemeral-vm-runtime-cleanup', () => ({ + cleanupEphemeralVmRuntimesForDeleted: (...args: unknown[]) => + cleanupEphemeralVmRuntimesForDeleted(...args) +})) + +const storeRef: { current: ReturnType | null } = { current: null } +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => storeRef.current?.getState() + } +})) + +const reposRemove = vi.fn() +const reposRemoveForHost = vi.fn() +const runtimeEnvironmentCall = vi.fn<(args: RuntimeEnvironmentCallRequest) => unknown>() + +// An ephemeral-VM project: its SSH target is owned by a runtime, so delete-on-host tears the VM down. +const vmRepo: Repo = { + id: 'project-vm', + path: '/home/dev/project-vm', + displayName: 'VM project', + badgeColor: '#000', + addedAt: 1, + connectionId: 'runtime-ssh-env-1', + executionHostId: 'ssh:runtime-ssh-env-1' +} + +function resolutionFor(repoId: string, targetId: string): SshHostRemoveResolution { + return { + targetId, + workspaceWorktreeIds: [], + hostRepoIds: [repoId], + workspaceCount: 1, + isConnected: false + } +} + +beforeEach(() => { + clearRuntimeCompatibilityCacheForTests() + for (const mock of [ + reposRemove, + reposRemoveForHost, + runtimeEnvironmentCall, + cleanupEphemeralVmRuntimesForDeleted + ]) { + mock.mockReset() + } + cleanupEphemeralVmRuntimesForDeleted.mockResolvedValue({ retainedSshTargetIds: [] }) + runtimeEnvironmentCall.mockImplementation( + (args) => + createCompatibleRuntimeStatusResponseIfNeeded(args) ?? { + id: 'rpc', + ok: true, + result: {}, + _meta: { runtimeId: 'runtime-remote' } + } + ) + vi.stubGlobal('window', { + api: { + repos: { remove: reposRemove, removeForHost: reposRemoveForHost }, + pty: { kill: vi.fn() }, + runtimeEnvironments: { call: runtimeEnvironmentCall }, + ui: { set: vi.fn().mockResolvedValue(undefined) } + } + }) + const store = createTestStore() + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + repos: [vmRepo] + }) + storeRef.current = store +}) + +describe('clearSshHostWorkspaces in forget-local mode', () => { + it('never destroys an ephemeral VM while forgetting a host', async () => { + const result = await clearSshHostWorkspaces( + resolutionFor('project-vm', 'runtime-ssh-env-1'), + 'forget-local' + ) + + expect(cleanupEphemeralVmRuntimesForDeleted).not.toHaveBeenCalled() + // A forget cannot both leave the host untouched and destroy its VM, so the removal refuses + // and the caller keeps the host rather than losing the VM to an operation that promised not to. + expect(result.failedIds).toEqual(['project-vm']) + expect(storeRef.current?.getState().repos.map((repo) => repo.id)).toEqual(['project-vm']) + }) + + it('dispatches no repo.rm to the host being forgotten', async () => { + storeRef.current?.setState({ + repos: [ + { ...vmRepo, id: 'project-ssh', connectionId: 'host-1', executionHostId: 'ssh:host-1' } + ] + }) + + const result = await clearSshHostWorkspaces( + resolutionFor('project-ssh', 'host-1'), + 'forget-local' + ) + + const dispatchedMethods = runtimeEnvironmentCall.mock.calls.map(([args]) => args.method) + expect(dispatchedMethods).not.toContain('repo.rm') + expect(result.failedIds).toEqual([]) + // Host-scoped, so a same-id project on another host keeps its own row. + expect(reposRemoveForHost).toHaveBeenCalledWith({ + repoId: 'project-ssh', + hostId: 'ssh:host-1' + }) + expect(reposRemove).not.toHaveBeenCalled() + expect(storeRef.current?.getState().repos).toEqual([]) + }) +}) + +it('keeps destroying the VM when the host clear is a real delete', async () => { + await clearSshHostWorkspaces(resolutionFor('project-vm', 'runtime-ssh-env-1'), 'delete-remote') + + expect(cleanupEphemeralVmRuntimesForDeleted).toHaveBeenCalledTimes(1) + expect(toast.error).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts b/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts index bf47a547b541..cd14bdbfb291 100644 --- a/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts +++ b/src/renderer/src/components/sidebar/ssh-host-remove-workspaces.ts @@ -49,12 +49,16 @@ export async function clearSshHostWorkspaces( // 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. + // wrong (local) project could be removed and the SSH ghost left behind. + // Why: forward the mode too. Without it a repo whose owner settings resolve a runtime target + // would dispatch repo.rm (and, for a runtime-owned SSH target, destroy its ephemeral VM) during + // an operation defined as touching nothing outside this client. for (const repoId of resolution.hostRepoIds) { try { - const outcome = await store.removeProject(repoId, { hostId }) + const outcome = await store.removeProject( + repoId, + forgetLocalOnly ? { hostId, mode: 'forget-local' as const } : { hostId } + ) if (outcome.status !== 'removed') { failedIds.push(repoId) } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 4d9f8b1b90f5..6c90d65abada 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -5287,8 +5287,10 @@ "removeDescriptionSsh": "This only removes {{name}} from Orca. Its files stay on {{host}} — re-add that SSH host to recover it.", "removeDescriptionLocal": "This only removes {{name}} from Orca. It is still on your disk.", "removeDescriptionVmRecipe": "This removes {{name}} from Orca. Its VM recipe determines whether the environment and its files are permanently deleted.", - "removeDescriptionOwnerUnverifiable": "Orca could not reach {{host}}, so whether {{name}} was removed there is unknown. Removing it now only clears this computer’s records — if it is still registered on {{host}}, it returns when that host reconnects.", - "removeFromOrcaOnly": "Remove from Orca" + "removeDescriptionOwnerUnverifiable": "Orca could not reach {{host}}, so whether {{name}} was removed there is unknown — the request may never have arrived, or it may have been carried out and the reply lost. Removing it now clears this computer’s records only and sends nothing to {{host}}; if the project is still registered there, it comes back when that host reconnects.", + "removeFromOrcaOnly": "Remove from Orca", + "removeDescriptionOwnerUnverifiableWeb": "Orca could not reach {{host}}, so whether {{name}} was removed there is unknown — the request may never have arrived, or it may have been carried out and the reply lost. This client keeps no records of its own to clear, so reconnect {{host}} and try again.", + "unnamedOwnerHost": "that host" }, "ScrollToCurrentWorkspaceToolbarButton": { "23989bb663": "Reveal active workspace" diff --git a/src/renderer/src/store/repos/project-removal-outcome.test.ts b/src/renderer/src/store/repos/project-removal-outcome.test.ts new file mode 100644 index 000000000000..a92ece50daf7 --- /dev/null +++ b/src/renderer/src/store/repos/project-removal-outcome.test.ts @@ -0,0 +1,53 @@ +/** + * `isOwnerContactFailure` decides whether a failed `repo.rm` is a refusal the owning host made + * (a failure) or silence (`owner-unverifiable`). Under docs/reference/ssh-execution-boundary.md + * only an answer is evidence, so a request that never left this machine must classify as silence. + */ +import { describe, expect, it } from 'vitest' +import { isOwnerContactFailure } from './project-removal-outcome' + +describe('isOwnerContactFailure', () => { + it.each([ + 'remote_runtime_unavailable', + 'runtime_rpc_queue_overloaded', + 'runtime_timeout', + 'runtime_unavailable', + 'timeout' + ])('treats the transport code %s as no answer', (code) => { + expect(isOwnerContactFailure({ code, message: 'transport failed' })).toBe(true) + }) + + // The client short-circuits before dispatching, so the host never saw the request. Classifying + // it as a refusal reported `failed` and hid the client-only forget this outcome exists for. + it('treats a manually disconnected environment as no answer', () => { + expect( + isOwnerContactFailure({ + code: 'runtime_manually_disconnected', + message: 'Runtime environment is manually disconnected.' + }) + ).toBe(true) + }) + + it.each([ + new Error('runtime_manually_disconnected'), + new Error('Runtime environment is manually disconnected.') + ])('treats an untyped manual disconnect as no answer: %s', (error) => { + expect(isOwnerContactFailure(error)).toBe(true) + }) + + it('keeps a host that answered and refused a failure', () => { + expect(isOwnerContactFailure({ code: 'unauthorized', message: 'bad token' })).toBe(false) + expect(isOwnerContactFailure({ code: 'repo_in_use', message: 'project is busy' })).toBe(false) + }) + + // A code is authoritative here exactly as it is in the shared classifier: a host that refused + // must not be re-read as silence because its prose mentions a disconnect. + it('trusts a refusal code over disconnect-sounding prose', () => { + expect( + isOwnerContactFailure({ + code: 'unauthorized', + message: 'Runtime environment is manually disconnected.' + }) + ).toBe(false) + }) +}) diff --git a/src/renderer/src/store/repos/project-removal-outcome.ts b/src/renderer/src/store/repos/project-removal-outcome.ts index 9619a46fc05d..957ecc224a16 100644 --- a/src/renderer/src/store/repos/project-removal-outcome.ts +++ b/src/renderer/src/store/repos/project-removal-outcome.ts @@ -1,6 +1,7 @@ import { isRecoverableRemoteRuntimeConnectionError, - toRemoteRuntimeClientErrorLike + toRemoteRuntimeClientErrorLike, + type RemoteRuntimeClientErrorLike } from '../../../../shared/remote-runtime-client-error-classification' /** @@ -22,11 +23,39 @@ export type RemoveProjectOutcome = | { status: 'owner-unverifiable' } | { status: 'failed' } +const MANUAL_DISCONNECT_CODE = 'runtime_manually_disconnected' +// Producers that raise this untyped put the code or the sentence in the message instead. +const MANUAL_DISCONNECT_MESSAGE_FRAGMENTS: readonly string[] = [ + MANUAL_DISCONNECT_CODE, + 'manually disconnected' +] + +/** + * The client refused to dispatch because the user disconnected this environment, so the request + * never left the machine and the host answered nothing. + * + * Deliberately not added to `RECOVERABLE_CODES`: that set means "retry or reconnect", and it + * drives the terminal multiplexer's resubscribe, the PTY transport's recovery loop and the remote + * skill installer's retries. A manual disconnect holds until the user undoes it, so those callers + * would spin against an environment the user switched off. + */ +function isManuallyDisconnectedOwner(error: RemoteRuntimeClientErrorLike): boolean { + if (error.code) { + return error.code === MANUAL_DISCONNECT_CODE + } + const message = error.message.toLowerCase() + return MANUAL_DISCONNECT_MESSAGE_FRAGMENTS.some((fragment) => message.includes(fragment)) +} + /** - * True only when no answer reached us — a dropped transport, a timeout, an unreachable runtime. - * A host that answers and refuses — unauthorized, protocol mismatch, an error from its own - * catalog — is positive evidence and stays a failure. + * True only when no answer reached us — a dropped transport, a timeout, an unreachable runtime, or + * a client-side short circuit that never sent the request. A host that answers and refuses — + * unauthorized, protocol mismatch, an error from its own catalog — is positive evidence and stays + * a failure. */ export function isOwnerContactFailure(error: unknown): boolean { - return isRecoverableRemoteRuntimeConnectionError(toRemoteRuntimeClientErrorLike(error)) + const classified = toRemoteRuntimeClientErrorLike(error) + return ( + isRecoverableRemoteRuntimeConnectionError(classified) || isManuallyDisconnectedOwner(classified) + ) } diff --git a/src/renderer/src/store/repos/repo-removal.ts b/src/renderer/src/store/repos/repo-removal.ts index 2275c1e319d2..979c255945ac 100644 --- a/src/renderer/src/store/repos/repo-removal.ts +++ b/src/renderer/src/store/repos/repo-removal.ts @@ -99,7 +99,8 @@ export function createRepoRemovalActions( const dispatchesToOwningRuntime = target.kind !== 'local' && !forgetLocalOnly try { // A forget always addresses one host's row, so it takes the host-scoped local call even - // when the id is unique — the catalog it belongs to is deliberately left alone. + // when the id is unique — this client sends that host nothing. What its catalog holds is + // whatever it held before, which after a lost answer is not something we know. await (dispatchesToOwningRuntime ? callRuntimeRpc(target, 'repo.rm', { repo: projectId }, { timeoutMs: 15_000 }) : idExistsOnOtherHost || forgetLocalOnly diff --git a/src/renderer/src/store/slices/repos-remove-missing-remote-project.test.ts b/src/renderer/src/store/slices/repos-remove-missing-remote-project.test.ts index b35dbc677cb7..ba48b7fa6e93 100644 --- a/src/renderer/src/store/slices/repos-remove-missing-remote-project.test.ts +++ b/src/renderer/src/store/slices/repos-remove-missing-remote-project.test.ts @@ -151,6 +151,21 @@ describe('removeProject when the owning host already dropped the project', () => expect(toast.error).not.toHaveBeenCalled() }) + // The client refuses to dispatch to an environment the user disconnected, so the host answered + // nothing. Classified as a refusal this reported `failed` and the dialog offered no way out. + it('reports owner-unverifiable when the client never dispatched to a disconnected host', async () => { + answerRepoRmWith('runtime_manually_disconnected') + const store = seedRemoteProjects([liveRemoteRepo, staleRemoteRepo]) + + const outcome = await store + .getState() + .removeProject('project-b', { hostId: 'runtime:env-1', errorFeedback: 'toast' }) + + expect(outcome).toEqual({ status: 'owner-unverifiable' }) + expect(store.getState().repos.map((repo) => repo.id)).toEqual(['project-a', 'project-b']) + expect(toast.error).not.toHaveBeenCalled() + }) + it('forget-local clears the row without ever calling the unreachable host', async () => { answerRepoRmWith('runtime_unavailable') const store = seedRemoteProjects([liveRemoteRepo, staleRemoteRepo]) diff --git a/src/renderer/src/web/preload-api/web-repositories-api.ts b/src/renderer/src/web/preload-api/web-repositories-api.ts index beea1ecf193a..3b93cdf9c4a1 100644 --- a/src/renderer/src/web/preload-api/web-repositories-api.ts +++ b/src/renderer/src/web/preload-api/web-repositories-api.ts @@ -30,6 +30,9 @@ export function createReposApi(): NonNullable['repos']> { invalidateRuntimeWorktreeCaches() }, // Why: host-scoped forget targets a desktop-owned SSH host; a paired web client has one runtime and no ghost-host state. + // Its records are the runtime's own catalog, so there is nothing client-only to drop — a + // forget here could only appear to succeed until the next repo.list. RemoveFolderDialog + // therefore withholds the client-only forget on this client rather than offering this throw. removeForHost: () => { throw new Error('Forgetting a host is unavailable in paired web clients.') },