Files
orca/src/shared/execution-host-registry.ts
T
Jinjing 637c7e94c9 Add SSH config host picker to add-host dialog (#12334)
* feat(ssh): add SSH config host picker for add-host form

Users can now click 'Fill from ~/.ssh/config…' to browse available SSH
config hosts in a picker, select one, and have the form automatically
prefill with resolved connection details (hostname, port, username, auth).

Previously, an 'import' button provided bulk sync on this form—confusing
and unhelpful when everything was already synced. That action is now
available as a secondary 'Add all' option in the picker.

* fix(ssh): import filter preservation and label fallback

- Reuse search loader on import completion to preserve active filter inside generation guard
- Fall back to hostname when manual host has no label, not empty string
- Make alias duplicate detection case-insensitive to match config picker behavior
- Validate host availability when restoring project group selection
- Add aria-selected attribute to picker options for accessibility

* fix(ssh): harden config picker import, alias folding, and host targeting

Review findings on the ~/.ssh/config picker + bulk add:

- Guard config-host resolution with a generation counter so a late resolve
  cannot overwrite a later pick or a form the user backed out of; freeze the
  other rows while a pick resolves.
- Stop "Add all N" from re-adopting deleted hosts — it now imports without
  reAdopt, matching the new-host count it advertises. Settings → Import keeps
  the explicit re-adopt path.
- Fold SSH aliases through a shared normalizeSshConfigAlias for import
  ownership, delete tombstones, reclaim, picker search, and the save-time
  duplicate check, which now occupies configHost *and* label like the picker.
- Persist GSSAPIAuthentication only when a parsed Host entry asks for it, not
  when `ssh -G` merely echoes the /etc/ssh system default.
- Fail closed with unavailable/setup-not-found when an explicit
  projectHostSetupId names a non-actionable host instead of silently creating
  the workspace on a sibling host.
- Cache the parsed config for the picker session (refresh on open/retry) so
  filter keystrokes no longer reparse and Include-expand the file, keep the
  filter usable during loads, add a Retry on load errors, explain an empty
  Identity file after a config fill, and drop the always-false aria-selected.

* refactor(ssh): centralize host result limit and extract folder group val

Move SSH_CONFIG_HOST_RESULT_LIMIT to shared types so the renderer's limit message
cannot drift from the host's query limit. Extract findActionableFolderProjectGroup
to avoid repeating the folder-host-availability check across the composer hook.

* fix(ssh): pass -F to ssh -G when HOME differs from passwd home

In E2E tests and sandboxes, isolated HOME can differ from the system
passwd home. OpenSSH resolves the default config via getpwuid (passwd),
while Node's loadUserSshConfig uses os.homedir() (HOME-aware). Pass -F
to explicitly specify the config path when they diverge, so ssh -G and
the picker resolve the same file.

* fix(ssh): verify config host exists before resolving with ssh -G

When a user edits ~/.ssh/config and removes a host, the import picker
should not fall back to ssh -G's echoed response (which treats any alias
as valid). Check the reloaded config file before resolving.

- Force reload config on each resolve to catch user edits post-open
- Reject aliases not in the current config before calling ssh -G
- Add test for deleted alias edge case
- Fix workspace-target fallback to honor explicit host selection

* fix(ssh): let tombstoned aliases be re-picked in the config picker

Allow users to reclaim a deleted SSH host by re-picking it from ~/.ssh/config. Tombstoned aliases now appear in the picker with a "Removed from Orca" badge and remain pickable, but don't count toward "Add all" operations — ensuring passive import never resurrects a deleted alias while still giving the user a recovery path.
2026-08-03 17:32:13 -07:00

291 lines
9.3 KiB
TypeScript

import {
LOCAL_EXECUTION_HOST_ID,
getLocalExecutionHostLabel,
getSettingsFocusedExecutionHostId,
isRuntimeOwnedSshTargetId,
parseExecutionHostId,
toRuntimeExecutionHostId,
toSshExecutionHostId,
type ExecutionHostId,
type ExecutionHostKind
} from './execution-host'
import { evaluateRuntimeCompat, type RuntimeCompatVerdict } from './protocol-compat'
import { MIN_COMPATIBLE_RUNTIME_SERVER_VERSION, RUNTIME_PROTOCOL_VERSION } from './protocol-version'
import type { RuntimeStatus } from './runtime-types'
import type { SshConnectionState, SshConnectionStatus } from './ssh-types'
import type { RuntimeEnvironmentSource } from './runtime-environments'
import type { GlobalSettings, Repo } from './types'
export type ExecutionHostHealth =
| 'local'
| 'available'
| 'connecting'
| 'blocked'
| 'disconnected'
| 'error'
export type ExecutionHostRegistryEntry = {
id: ExecutionHostId
kind: ExecutionHostKind
label: string
detail: string
health: ExecutionHostHealth
connectionStatus?: SshConnectionStatus
compatibility?: RuntimeCompatVerdict
capabilities?: readonly string[]
appVersion?: string | null
protocolVersion?: number | null
minCompatibleClientVersion?: number | null
platform?: NodeJS.Platform | null
remoteControlState?: RuntimeStatus['remoteControl']
source?: RuntimeEnvironmentSource
}
type RuntimeEnvironmentSummary = {
id: string
name?: string | null
source?: RuntimeEnvironmentSource
}
type RuntimeHostStatus = {
status?: RuntimeStatus | null
appVersion?: string | null
}
type RuntimeStatusByEnvironmentId = ReadonlyMap<string, RuntimeHostStatus>
export type ExecutionHostSource = 'configured-only' | 'include-references'
function normalizeHostPart(value: string | null | undefined): string | null {
const trimmed = value?.trim()
return trimmed ? trimmed : null
}
function runtimeCompatibility(
status: RuntimeStatus | null | undefined
): RuntimeCompatVerdict | null {
if (!status) {
return null
}
return evaluateRuntimeCompat({
clientProtocolVersion: RUNTIME_PROTOCOL_VERSION,
minCompatibleServerProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION,
serverProtocolVersion: status.runtimeProtocolVersion ?? status.protocolVersion,
serverMinCompatibleClientProtocolVersion:
status.minCompatibleRuntimeClientVersion ?? status.minCompatibleMobileVersion
})
}
function runtimeHealth(
status: RuntimeStatus | null | undefined,
compatibility: RuntimeCompatVerdict | null
): ExecutionHostHealth {
// Why: with no live status we have no evidence the Orca server is reachable, so
// it must read 'disconnected' (like SSH) rather than defaulting to 'available'.
// A configured-but-never-connected host was showing "Connected" otherwise.
if (!status) {
return 'disconnected'
}
if (!compatibility) {
return 'available'
}
return compatibility.kind === 'blocked' ? 'blocked' : 'available'
}
function runtimeControlHealth(
remoteControl: RuntimeStatus['remoteControl'] | null | undefined
): ExecutionHostHealth | null {
switch (remoteControl?.state) {
case 'awaiting_authenticated':
case 'awaiting_ready':
case 'reconnecting':
return 'connecting'
case 'closed':
return remoteControl.lastError ? 'error' : 'disconnected'
case 'ready':
return null
case undefined:
return null
}
}
function sshHealth(state: SshConnectionState | undefined): ExecutionHostHealth {
switch (state?.status) {
case 'connected':
return 'available'
case 'connecting':
case 'deploying-relay':
case 'reconnecting':
return 'connecting'
case 'auth-failed':
case 'error':
case 'reconnection-failed':
return 'error'
case 'disconnected':
case undefined:
return 'disconnected'
}
}
function setHost(
hosts: Map<ExecutionHostId, ExecutionHostRegistryEntry>,
entry: ExecutionHostRegistryEntry
): void {
const existing = hosts.get(entry.id)
if (!existing) {
hosts.set(entry.id, entry)
return
}
if (existing.health !== 'disconnected') {
return
}
// Why: a later status-bearing registration may upgrade health, but the first
// (named) registration is authoritative for the label — runtime envs are
// seeded with a friendly name before the id-labeled status/focus/repo
// fallbacks run, so keep the existing label on a health-only upgrade.
hosts.set(entry.id, { ...entry, label: existing.label, source: existing.source ?? entry.source })
}
function addRuntimeHost(
hosts: Map<ExecutionHostId, ExecutionHostRegistryEntry>,
environmentId: string,
label: string,
source: RuntimeEnvironmentSource | undefined,
statusByEnvironmentId: RuntimeStatusByEnvironmentId | undefined
): void {
const hostId = toRuntimeExecutionHostId(environmentId)
const runtimeStatus = statusByEnvironmentId?.get(environmentId)
const status = runtimeStatus?.status
const compatibility = runtimeCompatibility(status)
const controlHealth = runtimeControlHealth(status?.remoteControl)
setHost(hosts, {
id: hostId,
kind: 'runtime',
label,
detail: 'Orca server',
health: controlHealth ?? runtimeHealth(status, compatibility),
compatibility: compatibility ?? undefined,
capabilities: status?.capabilities,
appVersion: runtimeStatus?.appVersion ?? status?.appVersion ?? null,
protocolVersion: status?.runtimeProtocolVersion ?? status?.protocolVersion ?? null,
minCompatibleClientVersion:
status?.minCompatibleRuntimeClientVersion ?? status?.minCompatibleMobileVersion ?? null,
platform: status?.hostPlatform ?? null,
remoteControlState: status?.remoteControl ?? null,
...(source ? { source } : {})
})
}
export function buildExecutionHostRegistry(args: {
repos: readonly Pick<Repo, 'connectionId' | 'executionHostId'>[]
settings: Pick<GlobalSettings, 'activeRuntimeEnvironmentId'> | null | undefined
hostSource?: ExecutionHostSource
sshTargetLabels?: ReadonlyMap<string, string>
sshConnectionStates?: ReadonlyMap<string, SshConnectionState>
runtimeEnvironments?: readonly RuntimeEnvironmentSummary[]
runtimeStatusByEnvironmentId?: RuntimeStatusByEnvironmentId
// Why: user-chosen per-host display labels override the derived label so a
// rename in the host menu/settings shows everywhere the registry feeds.
hostLabelOverrides?: ReadonlyMap<ExecutionHostId, string>
}): ExecutionHostRegistryEntry[] {
const hosts = new Map<ExecutionHostId, ExecutionHostRegistryEntry>()
hosts.set(LOCAL_EXECUTION_HOST_ID, {
id: LOCAL_EXECUTION_HOST_ID,
kind: 'local',
label: getLocalExecutionHostLabel(),
detail: 'This computer',
health: 'local'
})
for (const environment of args.runtimeEnvironments ?? []) {
const environmentId = normalizeHostPart(environment.id)
if (!environmentId) {
continue
}
addRuntimeHost(
hosts,
environmentId,
normalizeHostPart(environment.name) ?? environmentId,
environment.source,
args.runtimeStatusByEnvironmentId
)
}
for (const environmentId of args.runtimeStatusByEnvironmentId?.keys() ?? []) {
addRuntimeHost(
hosts,
environmentId,
environmentId,
undefined,
args.runtimeStatusByEnvironmentId
)
}
const focusedHost = getSettingsFocusedExecutionHostId(args.settings)
const parsedFocusedHost = parseExecutionHostId(focusedHost)
if (parsedFocusedHost?.kind === 'runtime' && args.hostSource !== 'configured-only') {
addRuntimeHost(
hosts,
parsedFocusedHost.environmentId,
parsedFocusedHost.environmentId,
undefined,
args.runtimeStatusByEnvironmentId
)
}
const sshTargetIds = new Set<string>()
if (args.hostSource !== 'configured-only') {
for (const repo of args.repos) {
const parsedHost = parseExecutionHostId(repo.executionHostId)
if (parsedHost?.kind === 'runtime') {
addRuntimeHost(
hosts,
parsedHost.environmentId,
parsedHost.environmentId,
undefined,
args.runtimeStatusByEnvironmentId
)
}
// Why: a VM-backed repo's executionHostId is `ssh:runtime-ssh-<id>`. Runtime-owned
// targets are hidden, so they must not become visible SSH run-target hosts here.
if (parsedHost?.kind === 'ssh' && !isRuntimeOwnedSshTargetId(parsedHost.targetId)) {
sshTargetIds.add(parsedHost.targetId)
}
}
}
for (const targetId of args.sshTargetLabels?.keys() ?? []) {
const normalized = normalizeHostPart(targetId)
if (normalized && !isRuntimeOwnedSshTargetId(normalized)) {
sshTargetIds.add(normalized)
}
}
if (args.hostSource !== 'configured-only') {
for (const repo of args.repos) {
const targetId = normalizeHostPart(repo.connectionId)
if (targetId && !isRuntimeOwnedSshTargetId(targetId)) {
sshTargetIds.add(targetId)
}
}
}
for (const targetId of sshTargetIds) {
const state = args.sshConnectionStates?.get(targetId)
setHost(hosts, {
id: toSshExecutionHostId(targetId),
kind: 'ssh',
label: args.sshTargetLabels?.get(targetId) || targetId,
detail: 'SSH',
health: sshHealth(state),
connectionStatus: state?.status
})
}
const overrides = args.hostLabelOverrides
if (!overrides || overrides.size === 0) {
return [...hosts.values()]
}
return [...hosts.values()].map((host) => {
const label = overrides.get(host.id)
return label ? { ...host, label } : host
})
}