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..59bddb34e56f 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,15 +265,22 @@ describe('deep-link resolution', () => { }) describe('removeSettingsProjectFromAllHosts', () => { + beforeEach(() => { + 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(undefined) + const removeProject = vi.fn().mockResolvedValue({ status: 'removed' }) const setups = [ makeSetup({ hostId: 'local', repoId: 'local-1' }), makeSetup({ hostId: 'ssh:box', repoId: ' ' }), 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([ @@ -285,17 +295,17 @@ 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' }) ] - const pending = removeSettingsProjectFromAllHosts(setups, removeProject) + const pending = removeSettingsProjectFromAllHosts(setups, removeProject, resolveHostLabel) await Promise.resolve() expect(removeProject).toHaveBeenCalledTimes(1) @@ -303,4 +313,25 @@ 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, resolveHostLabel) + + expect(toast.error).toHaveBeenCalledTimes(1) + // 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 14de9f8d848f..d3d8d6d85434 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,37 @@ 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) { // 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. + // 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( + 'auto.components.settings.settingsProjectList.removeOwnerUnverifiable', + 'Could not reach the host that owns this project' + ), + { + description: translate( + 'auto.components.settings.settingsProjectList.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.', + { 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 7a5ac841d536..559743415fb9 100644 --- a/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx +++ b/src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx @@ -1,23 +1,34 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' +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 { 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[], + // Read by selectExecutionHostDisplayLabel: a per-host rename override wins over the name. + settings: null, + 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 +45,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 +81,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 +114,167 @@ 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() + // 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() + // 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' })) + + expect(mocks.state.removeProject).toHaveBeenLastCalledWith('repo-1', { + hostId: 'runtime:env-1', + errorFeedback: 'toast', + mode: 'forget-local' + }) + 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 () => { + 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 0b5bd3cdb46f..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 } from 'react' +import React, { useCallback, useEffect, useRef, useState } from 'react' +import { Loader2 } from 'lucide-react' import { Dialog, DialogContent, @@ -13,13 +14,21 @@ import { translate } from '@/i18n/i18n' import { getRepoExecutionHostId, isRuntimeOwnedSshTargetId, + parseExecutionHostId, 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) @@ -31,6 +40,31 @@ 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: 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) + 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) + useEffect(() => { + setOwnerUnverifiable(false) + setIsRemoving(false) + return () => { + removalTokenRef.current += 1 + } + }, [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 @@ -51,38 +85,94 @@ const RemoveFolderDialog = React.memo(function RemoveFolderDialog() { sshConnectionId ) }) + // 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 = isRuntimeOwnedSshTargetId(sshConnectionId) - ? 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 } - ) - : sshHostLabel + const description = ownerUnverifiable + ? canForgetLocally ? 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 } + '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.removeDescriptionLocal', - 'This only removes {{name}} from Orca. It is still on your disk.', + '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', + '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 + } + 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. + if (outcome.status === 'owner-unverifiable') { + setOwnerUnverifiable(true) + return } closeModal() - }, [closeModal, hostId, removeProject, repoId]) + }, [closeModal, hostId, ownerUnverifiable, removeProject, repoId]) const handleOpenChange = useCallback( (open: boolean) => { @@ -110,9 +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 e08a454f4244..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,18 +49,25 @@ 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 { - 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) + } } 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..6c90d65abada 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -5286,7 +5286,11 @@ "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": "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" @@ -12041,6 +12045,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": "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.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 new file mode 100644 index 000000000000..957ecc224a16 --- /dev/null +++ b/src/renderer/src/store/repos/project-removal-outcome.ts @@ -0,0 +1,61 @@ +import { + isRecoverableRemoteRuntimeConnectionError, + toRemoteRuntimeClientErrorLike, + type RemoteRuntimeClientErrorLike +} from '../../../../shared/remote-runtime-client-error-classification' + +/** + * What `removeProject` actually did. + * + * `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' } + | { 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, 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 { + 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 43525c3bba8c..979c255945ac 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, 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. const ownerRepo = findRepoForHost(get().repos, projectId, { @@ -59,12 +63,21 @@ export function createRepoRemovalActions( hostId: options?.hostId }) if (!ownerRepo) { - return + return { status: 'removed' } } const ownerHostId = getRepoExecutionHostId(ownerRepo) 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] @@ -83,15 +96,25 @@ 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 — 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 ? 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: 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' } + } throw err } } @@ -130,7 +153,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 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) => callRuntimeRpc( @@ -269,6 +294,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 +307,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-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') }) + ) +}) 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..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 @@ -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,56 @@ 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() + }) + + // 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]) + + 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]) 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.') },