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:<target-id> 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 <florin@sowild.design>
This commit is contained in:
Neil
2026-11-06 06:23:46 -08:00
committed by GitHub
co-authored by Florin Timbuc
parent 26741256dc
commit 239e17f84f
32 changed files with 455 additions and 50 deletions
+8
View File
@@ -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:<target-id>` for an SSH target and `--host runtime:<environment-id>` for a paired server. Use those to settle it, since `--environment <server-name>` 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:<target-id> --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:<target-id>` 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
+4
View File
@@ -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 <name>` instead of `Host <name>` 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.
+2 -30
View File
@@ -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'],
+60 -1
View File
@@ -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<string, CommandHandler> = {
]
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<SshTargetSummary>(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:<id> 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, string | boolean>): string {
const host = parseHostFlag(flags)
if (host?.kind === 'ssh') {
return host.targetId
}
if (!host) {
throw new RuntimeClientError('invalid_argument', 'Missing required --host ssh:<target-id>')
}
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 <name>`.'
: 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:<target-id>; `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<string, string | boolean>, name: string): string {
const value = flags.get(name)
if (typeof value !== 'string' || value.length === 0) {
+37
View File
@@ -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
}
]
+168
View File
@@ -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:<target-id>']
])('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)
})
})
+2
View File
@@ -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' ||
+1
View File
@@ -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',
+1
View File
@@ -46,6 +46,7 @@ export const ROOT_HELP_TEXT_SECONDARY = [
' orca account list [--json]',
' orca account select --agent claude --account <id|email|system> [--json]',
' orca host list [--json]',
' orca host rm --host ssh:<target-id> [--json]',
' orca environment add --name <name> --pairing-code <code> [--json]',
' orca environment list [--json]',
' orca environment show --environment <selector> [--json]',
+17 -1
View File
@@ -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 <name>. An SSH target is a machine the connected Orca host reaches, selected with --host ssh:<id>. 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 <ssh-target-name>. 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 <ssh-target-name> (except `orca host rm`, which takes only the ssh:<target-id> 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 <name>`.',
@@ -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:<target-id> [--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:<target-id> 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',
+3 -1
View File
@@ -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,
@@ -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
@@ -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<string, Record<string, string>> } = {}
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<void>) => 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 }
)
})
})
+25 -1
View File
@@ -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<void>
)
}
})
// 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<void> {
+1
View File
@@ -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
+7
View File
@@ -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
@@ -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: [],
@@ -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<void> => {
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<void> => {
@@ -108,14 +108,6 @@ function HostRemoveDialogBody({
})
}
const removeSshTarget = async (targetId: string): Promise<void> => {
// 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)
@@ -126,6 +126,7 @@ export function buildWindowApi(args: {
onCredentialRequest: () => () => {},
onCredentialResolved: () => () => {},
onPortForwardsChanged: () => () => {},
onTargetRemoved: () => () => {},
onDetectedPortsChanged: () => () => {},
...args.ssh
},
@@ -7,6 +7,7 @@ export function createIdleSshApiStub() {
listDetectedPorts: () => Promise.resolve([]),
getState: () => Promise.resolve(null),
onStateChanged: () => () => {},
onTargetRemoved: () => () => {},
onCredentialRequest: () => () => {},
onPortForwardsChanged: () => () => {},
onDetectedPortsChanged: () => () => {},
@@ -181,6 +181,7 @@ export function buildTerminalCreateWindow(args: {
onStateChanged: () => () => {},
onCredentialRequest: () => () => {},
onPortForwardsChanged: () => () => {},
onTargetRemoved: () => () => {},
onDetectedPortsChanged: () => () => {},
onCredentialResolved: () => () => {}
},
@@ -216,6 +216,7 @@ export async function loadIpcEventsHarness(
listRemovedTargetLabels: () => Promise.resolve({}),
getState: () => Promise.resolve(null),
onStateChanged: () => () => {},
onTargetRemoved: () => () => {},
onCredentialRequest: () => () => {},
onCredentialResolved: () => () => {},
onPortForwardsChanged: () => () => {},
@@ -59,6 +59,7 @@ describe('direct SSH hydration fanout', () => {
onCredentialResolved: () => () => {},
onPortForwardsChanged: () => () => {},
onDetectedPortsChanged: () => () => {},
onTargetRemoved: () => () => {},
onStateChanged: () => () => {}
}
}
@@ -39,6 +39,7 @@ function stubWindow(ssh: SshApiStub): void {
onCredentialResolved: () => () => {},
onPortForwardsChanged: () => () => {},
onDetectedPortsChanged: () => () => {},
onTargetRemoved: () => () => {},
onStateChanged: (handler: (data: { targetId: string; state: unknown }) => void) => {
onStateChangedHandler = handler
return () => {}
@@ -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)
@@ -290,7 +290,8 @@ describe('useIpcEvents agent status snapshot integration', () => {
) => {
detectedListener = listener
return () => {}
}
},
onTargetRemoved: () => () => {}
}
})
)
@@ -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: {
@@ -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: {
@@ -169,7 +169,8 @@ describe('useIpcEvents rate-limit hydration', () => {
onCredentialRequest: () => () => {},
onCredentialResolved: () => () => {},
onPortForwardsChanged: () => () => {},
onDetectedPortsChanged: () => () => {}
onDetectedPortsChanged: () => () => {},
onTargetRemoved: () => () => {}
},
runtime: {
getTerminalFitOverrides: () => Promise.resolve([]),
@@ -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')
})
})
@@ -188,6 +188,7 @@ export function createSshApi(): NonNullable<Partial<PreloadApi>['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: () =>