From 239e17f84fc920bc2be62b6a73336dc57fc0150b Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:23:46 -0800 Subject: [PATCH] feat(cli): add orca host rm, and clean up after every SSH target removal in main (#38774) * feat(cli): add orca host rm for saved SSH targets orca host rm --host ssh: calls the runtime RPC ssh.removeTarget, the same removeSshTarget the Settings UI reaches, so the tombstone keeps the passive ~/.ssh/config import from adding the alias back. Also document how the import treats Match blocks and Include files. * fix(ssh): clear a removed target's live state and rename in main for every removal path Removing an SSH target through ssh.removeTarget (orca host rm, paired clients) left open tabs with stale reconnect state and kept the host's rename, because only the Settings dialogs cleaned up after their own IPC call. The shared removal mutation now drops the display-label override and tells the renderer, which clears the target's state once for all callers. Fixes #37949 * fix(ssh): clean up after a removed target in the teardown every removal ends in A recipe VM's cleanup removes its SSH target through removeRegisteredSshTarget directly, so the window kept that target's live state. The broadcast and the rename drop now run there, after the target is gone. Fixes #37949 * test(cli): keep host rm's retarget-flag refusal next to its other cases Its old file was removed on main. Fixes #37949 * refactor(cli): give the host, managed-server and VM handler groups their own module Keeps the handler manifest under the file-length limit. Fixes #37949 --------- Co-authored-by: Florin Timbuc --- docs/site/content/docs/cli/reference.mdx | 8 + docs/site/content/docs/ssh.mdx | 4 + src/cli/handler-group-manifest.ts | 32 +--- src/cli/handlers/environment.ts | 61 ++++++- src/cli/host-handler-groups.ts | 37 ++++ src/cli/index-host-rm.test.ts | 168 ++++++++++++++++++ src/cli/remote-selection-scope.ts | 2 + src/cli/root-help-text-primary.ts | 1 + src/cli/root-help-text-secondary.ts | 1 + src/cli/specs/environment.ts | 18 +- src/main/ipc/ssh/ssh-ipc-test-harness.ts | 4 +- src/main/ipc/ssh/ssh-renderer-broadcast.ts | 11 ++ .../ssh/ssh-session-teardown-removal.test.ts | 70 ++++++++ src/main/ipc/ssh/ssh-session-teardown.ts | 26 ++- src/preload/api/ssh-api.ts | 1 + src/preload/api/ssh-bridge.ts | 7 + .../components/settings/ssh/SshPane.test.tsx | 1 - .../src/components/settings/ssh/SshPane.tsx | 3 - .../components/sidebar/HostRemoveDialog.tsx | 11 +- ...vents-agent-status-window-test-fixtures.ts | 1 + .../hooks/ipc-events-ssh-api-test-fixtures.ts | 1 + ...ts-terminal-create-window-test-fixtures.ts | 1 + .../src/hooks/ipc-events-test-harness.ts | 1 + .../direct-ssh-hydration-fanout.test.ts | 1 + ...rect-ssh-hydration-target-metadata.test.ts | 1 + .../ipc-events/direct-ssh-state-ipc-bridge.ts | 7 + ...cEvents-agent-status-ssh-authority.test.ts | 3 +- ...eIpcEvents-cli-worktree-activation.test.ts | 2 + ...Events-close-routing-browser-pages.test.ts | 3 + .../useIpcEvents-rate-limit-hydration.test.ts | 3 +- ...seIpcEvents-ssh-disconnect-cleanup.test.ts | 14 +- .../src/web/preload-api/web-terminal-api.ts | 1 + 32 files changed, 455 insertions(+), 50 deletions(-) create mode 100644 src/cli/host-handler-groups.ts create mode 100644 src/cli/index-host-rm.test.ts create mode 100644 src/main/ipc/ssh/ssh-session-teardown-removal.test.ts diff --git a/docs/site/content/docs/cli/reference.mdx b/docs/site/content/docs/cli/reference.mdx index 38fe54f6a7b..d4daa82586d 100644 --- a/docs/site/content/docs/cli/reference.mdx +++ b/docs/site/content/docs/cli/reference.mdx @@ -67,6 +67,14 @@ The result includes this machine, its registered [SSH targets](/docs/ssh), and p `--host` also takes the bare name shown in the `name` column, on either axis — `--host trader-local` reaches the same machine as `--host ssh:ssh-1783599077486-fyasux`. Names resolve only when they are unique: a name held by two SSH targets, by two paired servers, or by one of each is refused, and the error hands back the id form for each candidate — `--host ssh:` for an SSH target and `--host runtime:` for a paired server. Use those to settle it, since `--environment ` cannot separate two servers sharing a name. +Remove a saved SSH target with the id `orca host list` prints: + +```bash +orca host rm --host ssh: --json +``` + +It removes the target the same way Settings does, so the passive `~/.ssh/config` import does not add the alias back on the next launch. It takes only the `ssh:` form, not the bare name, because it deletes data. It refuses `--host local`, paired servers (use `orca environment rm`), and an id this Orca host does not have. + ## Runtime commands ```bash diff --git a/docs/site/content/docs/ssh.mdx b/docs/site/content/docs/ssh.mdx index e723aceaede..1d2fbbca597 100644 --- a/docs/site/content/docs/ssh.mdx +++ b/docs/site/content/docs/ssh.mdx @@ -23,6 +23,10 @@ Dirty add/edit forms ignore outside clicks so an accidental click away does not Orca won't add a second target for a machine already in Orca. When it imports `~/.ssh/config` (on launch, from **Add all**, or from Settings), it asks OpenSSH (`ssh -G`) where each new alias connects: host, port, user, and jump host or proxy command. It skips an alias that resolves to the same place as a saved target, and the picker shows that alias as **In Orca**. A different port, user, `ProxyJump`, or `ProxyCommand` stays a separate target. Hostnames are compared case-insensitively; SSH usernames keep their case. An alias without `HostName` connects to its own name, so it matches an IP target only if you set `HostName` to that IP. Orca doesn't look names up in DNS. If `ssh -G` isn't available, aliases are matched by name only. +The import reads `Host` blocks only. It adds each concrete alias of a `Host` line and skips patterns with `*`, `?`, or `!`. A `Match` block adds no target: a `Match` line ends the `Host` block above it, and the import ignores its lines until the next `Host` line. A tool that writes its own SSH config blocks can use `Match originalhost ` instead of `Host ` to keep a machine out of the import. Orca expands `Include` files in place before it parses, so a `Host` block in an included file is imported even when the `Include` line is inside a `Match` block. + +When you remove a target that came from `~/.ssh/config` (in Settings, or with `orca host rm`), the passive import (on launch, **Sync ~/.ssh/config**, or **Add all**) does not add its alias back. **Restore removed hosts…** in Settings → SSH brings it back. + ## Host key verification Orca checks built-in SSH connections against your effective OpenSSH `known_hosts` files and keys it previously saved. Existing matches connect silently. With the default policy, Orca accepts and remembers a host on first contact and shows its fingerprint; `StrictHostKeyChecking yes` rejects unknown hosts, while `no` / `off` accepts without saving a trust record. diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index cc476953a1a..b53b64e624e 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -4,6 +4,7 @@ import { JIRA_HANDLER_GROUP } from './jira-handler-group' import { LINEAR_HANDLER_GROUP } from './linear-handler-group' import { REFERENCE_HANDLER_GROUP } from './reference-handler-group' import { PLUGIN_HANDLER_GROUPS } from './plugin-handler-groups' +import { HOST_HANDLER_GROUPS } from './host-handler-groups' export type HandlerGroup = { name: string @@ -250,36 +251,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ keys: ['agent-context'], load: async () => (await import('./handlers/introspection.js')).INTROSPECTION_HANDLERS }, - { - name: 'environment', - keys: [ - 'host name', - 'host list', - 'environment add', - 'environment list', - 'environment show', - 'environment rm' - ], - load: async () => (await import('./handlers/environment.js')).ENVIRONMENT_HANDLERS - }, - { - name: 'managed-server', - keys: [ - 'environment status', - 'environment update', - 'environment rollback', - 'environment recover', - 'environment stop', - 'environment cancel-stop', - 'environment forget' - ], - load: async () => (await import('./handlers/managed-server.js')).MANAGED_SERVER_HANDLERS - }, - { - name: 'vm', - keys: ['vm recipe doctor'], - load: async () => (await import('./handlers/vm.js')).VM_HANDLERS - }, + ...HOST_HANDLER_GROUPS, { name: 'skill-sharing', keys: ['skills installed', 'skills share'], diff --git a/src/cli/handlers/environment.ts b/src/cli/handlers/environment.ts index f86936d703d..66ff498bade 100644 --- a/src/cli/handlers/environment.ts +++ b/src/cli/handlers/environment.ts @@ -7,7 +7,14 @@ import { printResult, type HostNameResult } from '../format' -import { listSshTargets, LOCAL_HOST_LIST_NAME } from '../host-selector-alternatives' +import { parseHostFlag } from '../execution-host-flag' +import { + fetchSshTargetSummaries, + listSshTargets, + LOCAL_HOST_LIST_NAME, + normalizeTypedName, + type SshTargetSummary +} from '../host-selector-alternatives' import { getDefaultUserDataPath, RuntimeClientError, @@ -101,6 +108,36 @@ export const ENVIRONMENT_HANDLERS: Record = { ] printResult(localSuccess({ hosts }), json, formatHostList) }, + 'host rm': async ({ client, flags, json }) => { + rejectLocalPairingStoreRetargeting( + flags, + '`orca host rm`. It removes an SSH target from this machine\u2019s own Orca runtime, the same one `orca host list` reads.', + 'Run `orca host rm` on that machine to remove an SSH target registered there.' + ) + const targetId = requireSshHostFlag(flags) + // Unlike listSshTargets, this keeps runtime_unavailable instead of reporting an unknown target. + const { targets } = await fetchSshTargetSummaries(client) + const target = targets.find((candidate) => candidate.id === targetId) + if (!target) { + throw new RuntimeClientError( + 'invalid_argument', + `Unknown SSH target in --host ssh:${targetId}: this Orca host has no SSH target with that id.`, + { + knownSshTargets: targets, + nextSteps: ['Run `orca host list` to see each SSH target and its --host ssh: flag.'] + } + ) + } + // Same RPC as the UI: the runtime tombstones the alias so the ~/.ssh/config import skips it. + const response = await client.call('ssh.removeTarget', { targetId }) + const removed = { kind: 'ssh' as const, name: target.label, id: target.id } + printResult( + { ...response, result: { removed } }, + json, + (result: { removed: typeof removed }) => + `Removed SSH target ${result.removed.name} (${result.removed.id}).` + ) + }, 'environment list': async ({ flags, json }) => { rejectLocalPairingStoreRetargeting( flags, @@ -158,6 +195,28 @@ function rejectLocalPairingStoreRetargeting( }) } +function requireSshHostFlag(flags: Map): string { + const host = parseHostFlag(flags) + if (host?.kind === 'ssh') { + return host.targetId + } + if (!host) { + throw new RuntimeClientError('invalid_argument', 'Missing required --host ssh:') + } + const named = host.kind === 'alias' ? host.alias : host.id + const nextStep = + host.kind === 'runtime' + ? 'A paired Orca server is removed with `orca environment rm --environment `.' + : host.kind === 'local' || normalizeTypedName(named) === LOCAL_HOST_LIST_NAME + ? 'This machine is always listed and cannot be removed.' + : 'Pass the SSH target id as --host ssh:; `orca host list` prints it.' + throw new RuntimeClientError( + 'invalid_argument', + `\`orca host rm\` removes saved SSH targets only, and --host ${named} is not one.`, + { nextSteps: [nextStep, 'Run `orca host list` to see each SSH target and its --host flag.'] } + ) +} + function getRequiredStringFlag(flags: Map, name: string): string { const value = flags.get(name) if (typeof value !== 'string' || value.length === 0) { diff --git a/src/cli/host-handler-groups.ts b/src/cli/host-handler-groups.ts new file mode 100644 index 00000000000..160656e60ba --- /dev/null +++ b/src/cli/host-handler-groups.ts @@ -0,0 +1,37 @@ +import type { HandlerGroup } from './handler-group-manifest' + +// The machines Orca reaches: saved hosts and paired environments, the Orca servers it manages on +// them, and recipe VMs. +export const HOST_HANDLER_GROUPS: readonly HandlerGroup[] = [ + { + name: 'environment', + keys: [ + 'host name', + 'host list', + 'host rm', + 'environment add', + 'environment list', + 'environment show', + 'environment rm' + ], + load: async () => (await import('./handlers/environment.js')).ENVIRONMENT_HANDLERS + }, + { + name: 'managed-server', + keys: [ + 'environment status', + 'environment update', + 'environment rollback', + 'environment recover', + 'environment stop', + 'environment cancel-stop', + 'environment forget' + ], + load: async () => (await import('./handlers/managed-server.js')).MANAGED_SERVER_HANDLERS + }, + { + name: 'vm', + keys: ['vm recipe doctor'], + load: async () => (await import('./handlers/vm.js')).VM_HANDLERS + } +] diff --git a/src/cli/index-host-rm.test.ts b/src/cli/index-host-rm.test.ts new file mode 100644 index 00000000000..2cc461f9a39 --- /dev/null +++ b/src/cli/index-host-rm.test.ts @@ -0,0 +1,168 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +const { + callMock, + runtimeClientConstructorMock, + serveOrcaAppMock, + getDefaultUserDataPathMock, + addEnvironmentFromPairingCodeMock, + listEnvironmentsMock, + spawnMock +} = vi.hoisted(() => ({ + callMock: vi.fn(), + runtimeClientConstructorMock: vi.fn(), + serveOrcaAppMock: vi.fn(), + getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), + addEnvironmentFromPairingCodeMock: vi.fn(), + listEnvironmentsMock: vi.fn(), + spawnMock: vi.fn() +})) + +vi.mock('./runtime-client', async () => { + const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') + return createRuntimeClientModuleMock({ + callMock, + runtimeClientConstructorMock, + serveOrcaAppMock, + getDefaultUserDataPathMock + }) +}) + +vi.mock('./runtime/environments', () => ({ + addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, + listEnvironments: listEnvironmentsMock, + removeEnvironment: vi.fn(), + resolveEnvironment: vi.fn() +})) + +vi.mock('child_process', async () => { + const { createChildProcessModuleMock } = await import('./index-test-harness.js') + return createChildProcessModuleMock(spawnMock) +}) + +import { main } from './index' +import { okFixture } from './test-fixtures' +import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness' + +const KEPT = { id: 'ssh-1783599077486-fyasux', label: 'trader-local' } +const STALE = { id: 'ssh-1783600000000-abcdef', label: 'ticket-vm-42' } + +/** Serve the target list and record removals, as the runtime's ssh RPC methods do. */ +function fakeSshRuntime(): { removed: string[] } { + const removed: string[] = [] + callMock.mockImplementation(async (method: string, params?: { targetId: string }) => { + if (method === 'ssh.listTargetSummaries') { + return okFixture('req_ssh_targets', { targets: [KEPT, STALE] }) + } + if (method === 'ssh.removeTarget' && params) { + removed.push(params.targetId) + return okFixture('req_ssh_remove', { removed: true }) + } + throw new Error(`unexpected call ${method}`) + }) + return { removed } +} + +function printedJson(logSpy: { mock: { calls: unknown[][] } }): { + ok: boolean + result?: unknown + error?: { code: string; message: string } +} { + return JSON.parse(String(logSpy.mock.calls[0]?.[0])) +} + +describe('orca host rm', () => { + const priorExitCode = process.exitCode + afterEach(() => { + process.exitCode = priorExitCode + }) + useWorktreeAwarenessEnvironment({ + callMock, + serveOrcaAppMock, + getDefaultUserDataPathMock, + addEnvironmentFromPairingCodeMock, + listEnvironmentsMock, + spawnMock + }) + + it('removes only the named SSH target through ssh.removeTarget and prints it', async () => { + const runtime = fakeSshRuntime() + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['host', 'rm', '--host', `ssh:${STALE.id}`, '--json'], '/tmp/repo') + + expect(runtime.removed).toEqual([STALE.id]) + expect(printedJson(logSpy)).toMatchObject({ + ok: true, + result: { removed: { kind: 'ssh', name: STALE.label, id: STALE.id } }, + _meta: { runtimeId: 'runtime-1' } + }) + }) + + it.each([ + ['local', 'This machine is always listed'], + ['this machine', 'This machine is always listed'], + ['runtime:env-m4air', 'orca environment rm'], + ['m4air', '--host ssh:'] + ])('refuses --host %s before it reaches the runtime', async (host, nextStep) => { + pairRuntimeEnvironment(listEnvironmentsMock, 'env-m4air', 'm4air') + const runtime = fakeSshRuntime() + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['host', 'rm', '--host', host, '--json'], '/tmp/repo') + + const printed = printedJson(logSpy) + expect(printed.ok).toBe(false) + expect(printed.error?.code).toBe('invalid_argument') + expect(printed.error?.message).toContain('removes saved SSH targets only') + expect(JSON.stringify(printed)).toContain(nextStep) + expect(runtime.removed).toEqual([]) + expect(callMock).not.toHaveBeenCalled() + expect(process.exitCode).toBe(1) + }) + + it.each([ + ['environment', 'm4air'], + ['pairing-code', 'orca://pair?code=x'] + ])('refuses --%s rather than removing the target on another machine', async (flag, value) => { + pairRuntimeEnvironment(listEnvironmentsMock, 'env-m4air', 'm4air') + const runtime = fakeSshRuntime() + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main( + ['host', 'rm', '--host', `ssh:${STALE.id}`, `--${flag}`, value, '--json'], + '/tmp/repo' + ) + + const printed = printedJson(logSpy) + expect(printed.error?.code).toBe('invalid_argument') + expect(printed.error?.message).toContain(`\`--${flag}\` does not retarget \`orca host rm\``) + expect(runtime.removed).toEqual([]) + expect(process.exitCode).toBe(1) + }) + + it('refuses an id the runtime does not have, and does not match a label', async () => { + const runtime = fakeSshRuntime() + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['host', 'rm', '--host', `ssh:${STALE.label}`, '--json'], '/tmp/repo') + + const printed = printedJson(logSpy) + expect(printed.error?.code).toBe('invalid_argument') + expect(printed.error?.message).toContain(`Unknown SSH target in --host ssh:${STALE.label}`) + expect(runtime.removed).toEqual([]) + expect(process.exitCode).toBe(1) + }) + + it('reports a stopped runtime instead of an unknown target', async () => { + const { RuntimeClientError } = await import('./runtime/types.js') + callMock.mockRejectedValue(new RuntimeClientError('runtime_unavailable', 'Orca is not running')) + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['host', 'rm', '--host', `ssh:${STALE.id}`, '--json'], '/tmp/repo') + + expect(printedJson(logSpy).error?.code).toBe('runtime_unavailable') + expect(callMock).not.toHaveBeenCalledWith('ssh.removeTarget', expect.anything()) + expect(process.exitCode).toBe(1) + }) +}) diff --git a/src/cli/remote-selection-scope.ts b/src/cli/remote-selection-scope.ts index 633a7b6635e..7c31dae0b73 100644 --- a/src/cli/remote-selection-scope.ts +++ b/src/cli/remote-selection-scope.ts @@ -6,6 +6,8 @@ export function ignoresRemoteSelection(commandPath: readonly string[]): boolean commandPath[0] === 'environment' || // Paired servers come from the local store; routing SSH lookup would mix two machines in one list. commandPath.join(' ') === 'host list' || + // Removes ids that `host list` printed from this runtime; an ambient selection must not retarget it. + commandPath.join(' ') === 'host rm' || commandPath[0] === 'serve' || (commandPath[0] === 'agent' && commandPath[1] !== 'launch') || commandPath[0] === 'vm' || diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index cbf1619a915..a92b0367fec 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -39,6 +39,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [ '', 'Hosts:', ' host list List targetable machines and how to name each one', + ' host rm Remove a saved SSH target', '', 'Environments:', ' environment add Save a remote Orca runtime from a pairing code', diff --git a/src/cli/root-help-text-secondary.ts b/src/cli/root-help-text-secondary.ts index 90ea4cb2e01..6fd12be1f95 100644 --- a/src/cli/root-help-text-secondary.ts +++ b/src/cli/root-help-text-secondary.ts @@ -46,6 +46,7 @@ export const ROOT_HELP_TEXT_SECONDARY = [ ' orca account list [--json]', ' orca account select --agent claude --account [--json]', ' orca host list [--json]', + ' orca host rm --host ssh: [--json]', ' orca environment add --name --pairing-code [--json]', ' orca environment list [--json]', ' orca environment show --environment [--json]', diff --git a/src/cli/specs/environment.ts b/src/cli/specs/environment.ts index 760c9d0486e..f44a0fa5e56 100644 --- a/src/cli/specs/environment.ts +++ b/src/cli/specs/environment.ts @@ -21,7 +21,7 @@ export const ENVIRONMENT_COMMAND_SPECS: CommandSpec[] = [ notes: [ 'Answers "what can I target and what do I pass" in one place: this machine, the SSH targets registered on it, and the Orca servers paired with it.', 'The three kinds are reached differently. A paired Orca server is a connection, selected with --environment . An SSH target is a machine the connected Orca host reaches, selected with --host ssh:. Passing one where the other belongs is the most common way to get an empty or missing-host answer.', - 'Commands that take --host also accept any name this list prints, such as --host "this machine" or --host . A name two hosts share is refused with the exact flag for each.', + 'Commands that take --host also accept any name this list prints, such as --host "this machine" or --host (except `orca host rm`, which takes only the ssh: form). A name two hosts share is refused with the exact flag for each.', 'SSH rows include the detected remote platform after that target has connected (linux, darwin, or win32); disconnected or older targets report platform unknown.', 'SSH rows also include whether the target is currently connected and its lifecycle status when known.', 'Paired-server rows come from the pairing store and report platform unknown; ask one server directly with `orca host name --environment `.', @@ -30,6 +30,22 @@ export const ENVIRONMENT_COMMAND_SPECS: CommandSpec[] = [ ], examples: ['orca host list', 'orca host list --json'] }, + { + path: ['host', 'rm'], + destructive: true, + summary: 'Remove one saved SSH target from this Orca host', + usage: 'orca host rm --host ssh: [--json]', + allowedFlags: [...LOCAL_COMMAND_FLAGS, 'host'], + notes: [ + 'Removes the target the same way Settings does: its connection closes, and the passive ~/.ssh/config import does not add the alias back. Restore removed hosts in Settings brings it back.', + 'Takes only the --host ssh: form that `orca host list` prints. This machine and paired Orca servers are refused; remove a paired server with `orca environment rm`.', + '--environment and --pairing-code are rejected rather than ignored: SSH targets are removed from this machine\u2019s own Orca runtime.' + ], + examples: [ + 'orca host rm --host ssh:ssh-1783599077486-fyasux', + 'orca host rm --host ssh:ssh-1783599077486-fyasux --json' + ] + }, { path: ['environment', 'add'], summary: 'Save a remote Orca runtime environment from a pairing code', diff --git a/src/main/ipc/ssh/ssh-ipc-test-harness.ts b/src/main/ipc/ssh/ssh-ipc-test-harness.ts index 83809ea46eb..de2be485a17 100644 --- a/src/main/ipc/ssh/ssh-ipc-test-harness.ts +++ b/src/main/ipc/ssh/ssh-ipc-test-harness.ts @@ -45,7 +45,9 @@ export function createSshIpcHarness(mocks: SshIpcMocks): SshIpcHarness { getRepos: () => [], getSshRemotePtyLeases: vi.fn().mockReturnValue([]), markSshRemotePtyLease: vi.fn(), - removeSshRemotePtyLeases: vi.fn() + removeSshRemotePtyLeases: vi.fn(), + getSettings: () => ({}), + updateSettings: vi.fn() } const mockWindow = { isDestroyed: () => false, diff --git a/src/main/ipc/ssh/ssh-renderer-broadcast.ts b/src/main/ipc/ssh/ssh-renderer-broadcast.ts index e5028c01de3..bbf7efd6f35 100644 --- a/src/main/ipc/ssh/ssh-renderer-broadcast.ts +++ b/src/main/ipc/ssh/ssh-renderer-broadcast.ts @@ -73,6 +73,17 @@ export function getPublicSshState(targetId: string): SshConnectionState | undefi return state ? withSshRemotePlatform(targetId, state) : undefined } +/** Settings, CLI and paired-client removals all publish this so the renderer drops the target's live state once. */ +export function broadcastSshTargetRemoved( + getMainWindow: () => BrowserWindow | null, + targetId: string +): void { + const win = getMainWindow() + if (win && !win.isDestroyed()) { + win.webContents.send('ssh:target-removed', { targetId }) + } +} + export function broadcastPortForwards( getMainWindow: () => BrowserWindow | null, targetId: string diff --git a/src/main/ipc/ssh/ssh-session-teardown-removal.test.ts b/src/main/ipc/ssh/ssh-session-teardown-removal.test.ts new file mode 100644 index 00000000000..b3ca18d94ac --- /dev/null +++ b/src/main/ipc/ssh/ssh-session-teardown-removal.test.ts @@ -0,0 +1,70 @@ +// #37949: every removal of a saved SSH target (Settings, `orca host rm`, a paired client, a recipe +// VM's cleanup) ends in removeRegisteredSshTarget, so the window's cleanup must happen there. +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => { + const settings: { hostSettingOverrides?: Record> } = {} + return { + removeTarget: vi.fn(), + send: vi.fn(), + settings, + updateSettings: vi.fn() + } +}) + +vi.mock('../../ssh/targets/ssh-target-registry', () => ({ + getSshTargetRegistryStore: () => ({ removeTarget: mocks.removeTarget }) +})) +vi.mock('./ssh-ipc-context', () => ({ + getCurrentMainWindow: () => ({ isDestroyed: () => false, webContents: { send: mocks.send } }), + connectionManager: { disconnect: vi.fn(async () => {}) }, + portForwardManager: null, + persistedStore: { + getSettings: () => mocks.settings, + updateSettings: mocks.updateSettings, + removeSshRemotePtyLeases: vi.fn() + } +})) +vi.mock('./ssh-target-lifecycle-queue', () => ({ + runTargetLifecycle: (_targetId: string, run: () => Promise) => run() +})) +vi.mock('../../managed-server/lifecycle/orcad-managed-tunnel', () => ({ + closeOrcadManagedTunnelsForTarget: vi.fn(async () => {}) +})) +vi.mock('../../browser/routing/local-host-partitions/local-ssh-browser-partitions', () => ({ + releaseLocalSshBrowserPartitionsForTarget: vi.fn(async () => {}) +})) +vi.mock('../../browser/routing/partitions/browser-route-partition-storage-runtime', () => ({ + clearBrowserRoutePartitionStorageForLocalSshTarget: vi.fn(async () => {}) +})) + +const { removeRegisteredSshTarget } = await import('./ssh-session-teardown') + +describe('removing a saved SSH target', () => { + beforeEach(() => { + vi.clearAllMocks() + mocks.settings.hostSettingOverrides = { + 'ssh:ssh-1': { displayLabel: 'Renamed', defaultWorktreeLocation: '/srv' }, + 'ssh:ssh-2': { displayLabel: 'Other' } + } + }) + + it("tells the window and drops the host's rename after the target is gone", async () => { + await removeRegisteredSshTarget('ssh-1') + + expect(mocks.removeTarget).toHaveBeenCalledWith('ssh-1') + expect(mocks.send).toHaveBeenCalledWith('ssh:target-removed', { targetId: 'ssh-1' }) + expect(mocks.removeTarget.mock.invocationCallOrder[0]).toBeLessThan( + mocks.send.mock.invocationCallOrder[0]! + ) + expect(mocks.updateSettings).toHaveBeenCalledWith( + { + hostSettingOverrides: { + 'ssh:ssh-1': { defaultWorktreeLocation: '/srv' }, + 'ssh:ssh-2': { displayLabel: 'Other' } + } + }, + { notifyListeners: true } + ) + }) +}) diff --git a/src/main/ipc/ssh/ssh-session-teardown.ts b/src/main/ipc/ssh/ssh-session-teardown.ts index 97223d5c93b..9e0629ab241 100644 --- a/src/main/ipc/ssh/ssh-session-teardown.ts +++ b/src/main/ipc/ssh/ssh-session-teardown.ts @@ -8,7 +8,15 @@ import { invalidateConnectAttempt, isCurrentConnectAttempt } from './ssh-connect-attempt-registry' -import { connectionManager, persistedStore, portForwardManager } from './ssh-ipc-context' +import { + connectionManager, + getCurrentMainWindow, + persistedStore, + portForwardManager +} from './ssh-ipc-context' +import { broadcastSshTargetRemoved } from './ssh-renderer-broadcast' +import { clearHostSettingOverride } from '../../../shared/host-setting-overrides' +import { toSshExecutionHostId } from '../../../shared/execution-host' import { runTargetLifecycle } from './ssh-target-lifecycle-queue' import { forgetPortForwardRestoreState } from './ssh-managed-port-forward-restore' import { errorMessage } from '../../../shared/error-message' @@ -58,6 +66,22 @@ export async function removeRegisteredSshTarget(targetId: string): Promise ) } }) + // Every removal (Settings, CLI, paired client, a recipe VM's cleanup) ends here: the window + // drops the target's live state, and its rename must not outlive it. + broadcastSshTargetRemoved(getCurrentMainWindow, targetId) + dropRemovedSshTargetDisplayLabel(targetId) +} + +function dropRemovedSshTargetDisplayLabel(targetId: string): void { + if (!persistedStore) { + return + } + const settings = persistedStore.getSettings() + const current = settings.hostSettingOverrides + const next = clearHostSettingOverride(settings, toSshExecutionHostId(targetId), 'displayLabel') + if (current && next !== current) { + persistedStore.updateSettings({ hostSettingOverrides: next }, { notifyListeners: true }) + } } export async function teardownSshTargetTransport(targetId: string): Promise { diff --git a/src/preload/api/ssh-api.ts b/src/preload/api/ssh-api.ts index 78dd54a2876..d10247c0355 100644 --- a/src/preload/api/ssh-api.ts +++ b/src/preload/api/ssh-api.ts @@ -35,6 +35,7 @@ export type SshApi = { onStateChanged: ( callback: (data: { targetId: string; state: SshConnectionState }) => void ) => () => void + onTargetRemoved: (callback: (data: { targetId: string }) => void) => () => void addPortForward: (args: { targetId: string localPort: number diff --git a/src/preload/api/ssh-bridge.ts b/src/preload/api/ssh-bridge.ts index e78ba759c94..9429ff80c80 100644 --- a/src/preload/api/ssh-bridge.ts +++ b/src/preload/api/ssh-bridge.ts @@ -92,6 +92,13 @@ export const sshApi = { return () => ipcRenderer.removeListener('ssh:state-changed', listener) }, + onTargetRemoved: (callback: (data: { targetId: string }) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, data: { targetId: string }): void => + callback(data) + ipcRenderer.on('ssh:target-removed', listener) + return () => ipcRenderer.removeListener('ssh:target-removed', listener) + }, + addPortForward: (args: { targetId: string localPort: number diff --git a/src/renderer/src/components/settings/ssh/SshPane.test.tsx b/src/renderer/src/components/settings/ssh/SshPane.test.tsx index c63c337ea23..cdcaf07a6f6 100644 --- a/src/renderer/src/components/settings/ssh/SshPane.test.tsx +++ b/src/renderer/src/components/settings/ssh/SshPane.test.tsx @@ -28,7 +28,6 @@ vi.mock('@/store/index', () => { sshConnectionStates: mocks.connectionStates, recordFeatureInteraction: mocks.recordInteraction, setSshTargetsMetadata: vi.fn(), - clearRemovedSshTargetState: vi.fn(), recordSshRepoReadoptions: mocks.recordReadoptions, openSettingsTarget: mocks.openSettingsTarget, repos: [], diff --git a/src/renderer/src/components/settings/ssh/SshPane.tsx b/src/renderer/src/components/settings/ssh/SshPane.tsx index 50468250511..761b2e66eca 100644 --- a/src/renderer/src/components/settings/ssh/SshPane.tsx +++ b/src/renderer/src/components/settings/ssh/SshPane.tsx @@ -82,7 +82,6 @@ export function SshPane({ addTargetIntentSignal }: SshPaneProps): React.JSX.Elem const totalBySource = useMemo(() => countSshTargetsBySource(targets), [targets]) const setSshTargetsMetadata = useAppStore((s) => s.setSshTargetsMetadata) - const clearRemovedSshTargetState = useAppStore((s) => s.clearRemovedSshTargetState) const loadTargets = useCallback( async (opts?: { signal?: AbortSignal }) => { @@ -195,8 +194,6 @@ export function SshPane({ addTargetIntentSignal }: SshPaneProps): React.JSX.Elem const removeTargetQuietly = async (id: string): Promise => { await window.api.ssh.removeTarget({ id }) - // Clear deferred reconnect metadata after removal so passphrase-gated tabs stop retrying the target. - clearRemovedSshTargetState(id) } const handleRemove = async (id: string): Promise => { diff --git a/src/renderer/src/components/sidebar/HostRemoveDialog.tsx b/src/renderer/src/components/sidebar/HostRemoveDialog.tsx index de613c87d28..ac0fb2c1b7e 100644 --- a/src/renderer/src/components/sidebar/HostRemoveDialog.tsx +++ b/src/renderer/src/components/sidebar/HostRemoveDialog.tsx @@ -108,14 +108,6 @@ function HostRemoveDialogBody({ }) } - const removeSshTarget = async (targetId: string): Promise => { - // Main refuses a managed server's host; the error says why. - await window.api.ssh.removeTarget({ id: targetId }) - // Clear deferred reconnect state so focused tabs stop retrying the removed target. - useAppStore.getState().clearRemovedSshTargetState(targetId) - dropOverridesForHost() - } - // Reuse server Settings’ active-host switching and error handling through a preselected deep link. const handleRemoveRuntime = (environmentId: string): void => { const state = useAppStore.getState() @@ -151,7 +143,8 @@ function HostRemoveDialogBody({ await removeWslHost(target.environmentId) dropOverridesForHost() } else { - await removeSshTarget(target.targetId) + // Main refuses a managed server's host, and on success clears the target's live state and rename. + await window.api.ssh.removeTarget({ id: target.targetId }) } if (mountedRef.current) { onOpenChange(false) diff --git a/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts b/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts index 8333a815918..48034cc31c9 100644 --- a/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts +++ b/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts @@ -126,6 +126,7 @@ export function buildWindowApi(args: { onCredentialRequest: () => () => {}, onCredentialResolved: () => () => {}, onPortForwardsChanged: () => () => {}, + onTargetRemoved: () => () => {}, onDetectedPortsChanged: () => () => {}, ...args.ssh }, diff --git a/src/renderer/src/hooks/ipc-events-ssh-api-test-fixtures.ts b/src/renderer/src/hooks/ipc-events-ssh-api-test-fixtures.ts index 9102362b21f..ec59bc98518 100644 --- a/src/renderer/src/hooks/ipc-events-ssh-api-test-fixtures.ts +++ b/src/renderer/src/hooks/ipc-events-ssh-api-test-fixtures.ts @@ -7,6 +7,7 @@ export function createIdleSshApiStub() { listDetectedPorts: () => Promise.resolve([]), getState: () => Promise.resolve(null), onStateChanged: () => () => {}, + onTargetRemoved: () => () => {}, onCredentialRequest: () => () => {}, onPortForwardsChanged: () => () => {}, onDetectedPortsChanged: () => () => {}, diff --git a/src/renderer/src/hooks/ipc-events-terminal-create-window-test-fixtures.ts b/src/renderer/src/hooks/ipc-events-terminal-create-window-test-fixtures.ts index 0bff83924f0..a31e78e4265 100644 --- a/src/renderer/src/hooks/ipc-events-terminal-create-window-test-fixtures.ts +++ b/src/renderer/src/hooks/ipc-events-terminal-create-window-test-fixtures.ts @@ -181,6 +181,7 @@ export function buildTerminalCreateWindow(args: { onStateChanged: () => () => {}, onCredentialRequest: () => () => {}, onPortForwardsChanged: () => () => {}, + onTargetRemoved: () => () => {}, onDetectedPortsChanged: () => () => {}, onCredentialResolved: () => () => {} }, diff --git a/src/renderer/src/hooks/ipc-events-test-harness.ts b/src/renderer/src/hooks/ipc-events-test-harness.ts index d20590eb7a5..f20f524d4ae 100644 --- a/src/renderer/src/hooks/ipc-events-test-harness.ts +++ b/src/renderer/src/hooks/ipc-events-test-harness.ts @@ -216,6 +216,7 @@ export async function loadIpcEventsHarness( listRemovedTargetLabels: () => Promise.resolve({}), getState: () => Promise.resolve(null), onStateChanged: () => () => {}, + onTargetRemoved: () => () => {}, onCredentialRequest: () => () => {}, onCredentialResolved: () => () => {}, onPortForwardsChanged: () => () => {}, diff --git a/src/renderer/src/hooks/ipc-events/direct-ssh-hydration-fanout.test.ts b/src/renderer/src/hooks/ipc-events/direct-ssh-hydration-fanout.test.ts index 63299e533db..8632e70299c 100644 --- a/src/renderer/src/hooks/ipc-events/direct-ssh-hydration-fanout.test.ts +++ b/src/renderer/src/hooks/ipc-events/direct-ssh-hydration-fanout.test.ts @@ -59,6 +59,7 @@ describe('direct SSH hydration fanout', () => { onCredentialResolved: () => () => {}, onPortForwardsChanged: () => () => {}, onDetectedPortsChanged: () => () => {}, + onTargetRemoved: () => () => {}, onStateChanged: () => () => {} } } diff --git a/src/renderer/src/hooks/ipc-events/direct-ssh-hydration-target-metadata.test.ts b/src/renderer/src/hooks/ipc-events/direct-ssh-hydration-target-metadata.test.ts index 82d9d5e1524..252cf060256 100644 --- a/src/renderer/src/hooks/ipc-events/direct-ssh-hydration-target-metadata.test.ts +++ b/src/renderer/src/hooks/ipc-events/direct-ssh-hydration-target-metadata.test.ts @@ -39,6 +39,7 @@ function stubWindow(ssh: SshApiStub): void { onCredentialResolved: () => () => {}, onPortForwardsChanged: () => () => {}, onDetectedPortsChanged: () => () => {}, + onTargetRemoved: () => () => {}, onStateChanged: (handler: (data: { targetId: string; state: unknown }) => void) => { onStateChangedHandler = handler return () => {} diff --git a/src/renderer/src/hooks/ipc-events/direct-ssh-state-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/direct-ssh-state-ipc-bridge.ts index 2f954358736..db03f003195 100644 --- a/src/renderer/src/hooks/ipc-events/direct-ssh-state-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/direct-ssh-state-ipc-bridge.ts @@ -81,6 +81,13 @@ export function registerDirectSshStateIpcBridge(unsubs: (() => void)[]): () => v }) ) + unsubs.push( + window.api.ssh.onTargetRemoved(({ targetId }) => { + // Stop deferred reconnects and drop live state whichever client removed the target. + useAppStore.getState().clearRemovedSshTargetState(targetId) + }) + ) + unsubs.push( window.api.ssh.onPortForwardsChanged(({ targetId, forwards, unrestored }) => { const pendingPortHydration = pendingPortHydrationByTargetId.get(targetId) diff --git a/src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts b/src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts index d04b9275fb3..872584e3abd 100644 --- a/src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts @@ -290,7 +290,8 @@ describe('useIpcEvents agent status snapshot integration', () => { ) => { detectedListener = listener return () => {} - } + }, + onTargetRemoved: () => () => {} } }) ) diff --git a/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts b/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts index 92fc1141645..fc5ce98f60f 100644 --- a/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts @@ -205,6 +205,7 @@ describe('useIpcEvents CLI-created worktree activation', () => { onCredentialRequest: () => () => {}, onPortForwardsChanged: () => () => {}, onDetectedPortsChanged: () => () => {}, + onTargetRemoved: () => () => {}, onCredentialResolved: () => () => {} }, runtime: { @@ -468,6 +469,7 @@ describe('useIpcEvents CLI-created worktree activation', () => { onCredentialRequest: () => () => {}, onPortForwardsChanged: () => () => {}, onDetectedPortsChanged: () => () => {}, + onTargetRemoved: () => () => {}, onCredentialResolved: () => () => {} }, runtime: { diff --git a/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts b/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts index 0b4048245d6..6926d383344 100644 --- a/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts @@ -217,6 +217,7 @@ describe('useIpcEvents browser tab close routing', () => { onCredentialRequest: () => () => {}, onPortForwardsChanged: () => () => {}, onDetectedPortsChanged: () => () => {}, + onTargetRemoved: () => () => {}, onCredentialResolved: () => () => {} }, runtime: { @@ -447,6 +448,7 @@ describe('useIpcEvents browser tab close routing', () => { onCredentialRequest: () => () => {}, onPortForwardsChanged: () => () => {}, onDetectedPortsChanged: () => () => {}, + onTargetRemoved: () => () => {}, onCredentialResolved: () => () => {} }, runtime: { @@ -672,6 +674,7 @@ describe('useIpcEvents browser tab close routing', () => { onCredentialRequest: () => () => {}, onPortForwardsChanged: () => () => {}, onDetectedPortsChanged: () => () => {}, + onTargetRemoved: () => () => {}, onCredentialResolved: () => () => {} }, runtime: { diff --git a/src/renderer/src/hooks/useIpcEvents-rate-limit-hydration.test.ts b/src/renderer/src/hooks/useIpcEvents-rate-limit-hydration.test.ts index 111581e27a7..81a9c78536b 100644 --- a/src/renderer/src/hooks/useIpcEvents-rate-limit-hydration.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-rate-limit-hydration.test.ts @@ -169,7 +169,8 @@ describe('useIpcEvents rate-limit hydration', () => { onCredentialRequest: () => () => {}, onCredentialResolved: () => () => {}, onPortForwardsChanged: () => () => {}, - onDetectedPortsChanged: () => () => {} + onDetectedPortsChanged: () => () => {}, + onTargetRemoved: () => () => {} }, runtime: { getTerminalFitOverrides: () => Promise.resolve([]), diff --git a/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts b/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts index a533b501b78..ad0dc3f140c 100644 --- a/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts @@ -31,6 +31,9 @@ describe('useIpcEvents updater integration', () => { } = { current: null } + const targetRemovedListenerRef: { current: ((data: { targetId: string }) => void) | null } = { + current: null + } const storeState = { setUpdateStatus: vi.fn(), fetchRepos: vi.fn(), @@ -230,7 +233,11 @@ describe('useIpcEvents updater integration', () => { onCredentialRequest: () => () => {}, onCredentialResolved: () => () => {}, onPortForwardsChanged: () => () => {}, - onDetectedPortsChanged: () => () => {} + onDetectedPortsChanged: () => () => {}, + onTargetRemoved: (listener: (data: { targetId: string }) => void) => { + targetRemovedListenerRef.current = listener + return () => {} + } }, agentStatus: { onSet: () => () => {} } } @@ -365,5 +372,10 @@ describe('useIpcEvents updater integration', () => { expect(setSshConnectionState).toHaveBeenCalledTimes(1) expect(setSshConnectionState).toHaveBeenCalledWith('conn-refresh-failure', refreshFailureState) + + // Removal by any client (Settings, CLI, paired client) clears the target's live state. + clearRemovedSshTargetState.mockClear() + targetRemovedListenerRef.current?.({ targetId: 'conn-1' }) + expect(clearRemovedSshTargetState).toHaveBeenCalledWith('conn-1') }) }) diff --git a/src/renderer/src/web/preload-api/web-terminal-api.ts b/src/renderer/src/web/preload-api/web-terminal-api.ts index 2c3db8c79d0..3d1d14ef927 100644 --- a/src/renderer/src/web/preload-api/web-terminal-api.ts +++ b/src/renderer/src/web/preload-api/web-terminal-api.ts @@ -188,6 +188,7 @@ export function createSshApi(): NonNullable['ssh']> { error: translate('auto.web.web.preload.api.31bfe8ae1a', 'Unavailable in the web client.') }), onStateChanged: () => noopUnsubscribe, + onTargetRemoved: () => noopUnsubscribe, addPortForward: () => Promise.reject(new Error('SSH port forwarding is unavailable in the web client.')), updatePortForward: () =>