Skip to content
Closed
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
597a3a2
feat(ssh): the owner records a user's Disconnect and refuses connects…
brennanb2025 Sep 27, 2026
0c2d369
fix(terminal): background connects wait for the user instead of redia…
brennanb2025 Sep 27, 2026
2909338
feat(workspace): panes say when the user's own Disconnect holds their…
brennanb2025 Sep 27, 2026
d3c821a
test(e2e): a user's Disconnect holds with a terminal open until the o…
brennanb2025 Sep 27, 2026
54c0bc0
test(ssh): pin the refusal after a queued wait, the intent strip, adm…
brennanb2025 Sep 27, 2026
7a42e7b
fix(ssh): a held-down host publishes as disconnected while Reset Rela…
brennanb2025 Sep 27, 2026
7599fa8
fix(terminal): a held-down pane waits for the user's Connect to finis…
brennanb2025 Sep 27, 2026
103dec3
fix(ssh): a failed terminate closes the cleanup transport of a host t…
brennanb2025 Sep 27, 2026
0336e20
test(ssh): a user's Connect during a failed terminate keeps its conne…
brennanb2025 Sep 28, 2026
6ef7fba
fix(ssh): ending a host's terminals dials and closes the relay in one…
brennanb2025 Sep 28, 2026
899107b
test(relay): a stop from a connection with no consumer session ends t…
brennanb2025 Sep 28, 2026
7910b1a
fix(ssh): end terminals and reset a relay without bringing a disconne…
brennanb2025 Sep 28, 2026
44fff19
test(ssh): a Connect behind End Terminals ends connected with its rel…
brennanb2025 Sep 28, 2026
2867f14
test(ssh): a Connect behind End Terminals also restores its forwards
brennanb2025 Sep 28, 2026
0dac851
fix(ssh): name a host the user disconnected in the quit prompt, file …
brennanb2025 Sep 28, 2026
48634a8
fix(file-explorer): reload a failed tree when the workspace's host co…
brennanb2025 Sep 28, 2026
6351544
fix(ssh): say closing does not end terminals on a host the user disco…
brennanb2025 Sep 28, 2026
344b92b
fix(file-explorer): keep the raw read error off screen while the host…
brennanb2025 Sep 28, 2026
9295ba4
test(file-explorer): pass the workspace id to the tree load effects
brennanb2025 Sep 28, 2026
b9951e1
fix(editor): show the connecting state, not a dropped read error, whi…
brennanb2025 Sep 28, 2026
30e8971
fix(i18n): name the disconnected host in the quit prompt's Japanese a…
brennanb2025 Sep 28, 2026
853925f
fix(editor): promise a reload on connect only for the file the retry …
brennanb2025 Sep 28, 2026
c89e029
Merge origin/main into brennanb2025/ssh-disconnect-sticks
brennanb2025 Sep 28, 2026
9df2f3b
test(e2e): the escape-hatch spec proves the user's Disconnect held, n…
brennanb2025 Sep 28, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ jobs:
. != "tests/e2e/ssh-skill-installation.spec.ts" and
. != "tests/e2e/ssh-stale-resume-execution-host-scope.spec.ts" and
. != "tests/e2e/ssh-terminal-window-wake-stale-grid-repro.spec.ts" and
. != "tests/e2e/ssh-user-disconnect-sticks.spec.ts" and
. != "tests/e2e/terminal-inline-images-ssh.spec.ts" and
. != "tests/e2e/ssh-docker-watcher-isolation.spec.ts" and
. != "tests/e2e/ssh-terminal-parking.spec.ts" and
Expand Down Expand Up @@ -362,6 +363,7 @@ jobs:
contains(inputs.test_files, 'tests/e2e/ssh-skill-installation.spec.ts') ||
contains(inputs.test_files, 'tests/e2e/ssh-stale-resume-execution-host-scope.spec.ts') ||
contains(inputs.test_files, 'tests/e2e/ssh-terminal-window-wake-stale-grid-repro.spec.ts') ||
contains(inputs.test_files, 'tests/e2e/ssh-user-disconnect-sticks.spec.ts') ||
contains(inputs.test_files, 'tests/e2e/terminal-inline-images-ssh.spec.ts') ||
contains(inputs.test_files, 'tests/e2e/ssh-docker-watcher-isolation.spec.ts') ||
contains(inputs.test_files, 'tests/e2e/ssh-terminal-parking.spec.ts') ||
Expand Down
1 change: 1 addition & 0 deletions config/scripts/run-ssh-docker-e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ const result = spawnSync(
'tests/e2e/ssh-skill-installation.spec.ts',
'tests/e2e/ssh-stale-resume-execution-host-scope.spec.ts',
'tests/e2e/ssh-terminal-window-wake-stale-grid-repro.spec.ts',
'tests/e2e/ssh-user-disconnect-sticks.spec.ts',
'tests/e2e/terminal-inline-images-ssh.spec.ts',
'--config',
'tests/playwright.config.ts',
Expand Down
2 changes: 1 addition & 1 deletion src/main/ephemeral-vm-runtime-ssh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export async function connectRuntimeOwnedSshTarget(args: {
}
const target = store.upsertRuntimeOwnedTarget(args.runtimeId, args.connection.target)
try {
const state = await connectRegisteredSshTarget(target.id)
const state = await connectRegisteredSshTarget(target.id, 'background')
if (state.status !== 'connected') {
throw new Error(state.error || `SSH target did not connect: ${state.status}`)
}
Expand Down
4 changes: 4 additions & 0 deletions src/main/ipc/ssh-app-shutdown.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ vi.mock('electron', () => mocks.electron)
vi.mock('./ssh-pty-output-intake-registry', () => mocks.sshPtyOutputIntakeRegistry)
vi.mock('../ssh/ssh-connection-store', () => mocks.sshConnectionStore)
vi.mock('../ssh/ssh-connection-manager', () => mocks.sshConnectionManager)
vi.mock('../ssh/ssh-connection', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
...mocks.sshConnection
}))
vi.mock('../ssh/ssh-relay-deploy', () => mocks.sshRelayDeploy)
vi.mock('../ssh/ssh-relay-reset', () => mocks.sshRelayReset)
vi.mock('../ssh/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer)
Expand Down
28 changes: 26 additions & 2 deletions src/main/ipc/ssh-connect-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ import type { SshConnection } from '../ssh/ssh-connection'
import { SshRelaySession } from '../ssh/ssh-relay-session'
import type { SshConnectionState, SshConnectionStatus } from '../../shared/ssh-types'
import { createCancelledConnectAttemptError } from '../ssh/ssh-connect-attempt-cancellation'
import { createSshDisconnectedByUserError } from '../../shared/ssh-disconnected-by-user'
import { isAuthError } from '../ssh/ssh-connection-utils'
import {
getSshProviderAuthority,
isCurrentSshProviderAuthority,
rotateSshProviderAuthority
} from '../ssh/ssh-provider-authority'
import { getSshTargetRegistryStore } from '../ssh/ssh-target-registry'
import { getSshTargetRegistryStore, type SshConnectAdmission } from '../ssh/ssh-target-registry'
import { activeSessions } from './ssh-active-relay-sessions'
import {
assertSshConnectsNotFenced,
Expand All @@ -30,6 +31,11 @@ import {
persistedStore,
portForwardManager
} from './ssh-ipc-context'
import {
isSshTargetDisconnectedByUser,
recordSshConnectionIntent,
sshTargetDisplayLabel
} from './ssh-connection-intent'
import { clearRelayLostBackoff, relayLostBackoff } from './ssh-relay-lost-backoff'
import { configureRelaySessionCallbacks } from './ssh-relay-session-callbacks'
import {
Expand All @@ -42,19 +48,29 @@ import {
import { abandonCancelledConnectAttempt, abandonFailedSshSession } from './ssh-session-teardown'
import { awaitTargetLifecycle } from './ssh-target-lifecycle-queue'

export async function connectTarget(targetId: string): Promise<SshConnectionState> {
export async function connectTarget(
targetId: string,
admission: SshConnectAdmission
): Promise<SshConnectionState> {
const e2eProbePath = process.env.ORCA_E2E_FORBID_LOCAL_SSH_CONNECT_PROBE
if (e2eProbePath) {
appendFileSync(e2eProbePath, `${JSON.stringify(targetId)}\n`)
throw new Error('e2e_forbidden_local_ssh_connect')
}
if (admission === 'user') {
// Why at admission: a Disconnect that arrives after this click must win, and it writes later.
recordSshConnectionIntent(targetId, 'connected')
}
assertConnectAdmitted(targetId, admission)
// Why: fence callers that entered before a same-turn disconnect/reset but resume after its cleanup.
const admissionAuthority = getSshProviderAuthority(targetId)
await awaitTargetLifecycle(targetId)
const reset = resetRelayInFlight.get(targetId)
if (reset) {
await reset
}
// Why again: a Disconnect may have landed while this connect waited on the lifecycle queue.
assertConnectAdmitted(targetId, admission)

// Why: serialize concurrent ssh:connect for the same target; interleaved connects otherwise leak the first session.
const existing = connectInFlight.get(targetId)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -94,6 +110,14 @@ export async function connectTarget(targetId: string): Promise<SshConnectionStat
}
}

// Why before any rotation, registration or broadcast: a refused connect must leave no trace.
function assertConnectAdmitted(targetId: string, admission: SshConnectAdmission): void {
if (admission === 'background' && isSshTargetDisconnectedByUser(targetId)) {
console.warn(`[ssh] Refused a background connect to ${targetId}: the user disconnected it`)
throw createSshDisconnectedByUserError(sshTargetDisplayLabel(targetId))
}
}

async function doConnect(
targetId: string,
replacePendingTransport = false
Expand Down
151 changes: 38 additions & 113 deletions src/main/ipc/ssh-connection-handlers.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,27 @@
import { ipcMain } from 'electron'
import {
sshRemotePtyLeaseAllowsReattach,
type SshTarget,
type SshTerminateSessionsResult
} from '../../shared/ssh-types'
import { SSH_TERMINATE_RECONNECT_REQUIRED } from '../../shared/constants'
import { isSshPtyNotFoundError } from '../providers/ssh-pty-errors'
import { toAppSshPtyId, toRelaySshPtyId } from '../providers/ssh-pty-id'
import type { SshTarget } from '../../shared/ssh-types'
import { toAppSshPtyId } from '../providers/ssh-pty-id'
import { rotateSshProviderAuthority } from '../ssh/ssh-provider-authority'
import { forceStopRelayForTarget } from '../ssh/ssh-relay-reset'
import { setSshTargetRegistryHandlers, getSshTargetRegistryStore } from '../ssh/ssh-target-registry'
import {
clearProviderPtyState,
deletePtyOwnership,
getPtyIdsForConnection,
getSshPtyProvider
} from './pty'
import { clearProviderPtyState, deletePtyOwnership, getPtyIdsForConnection } from './pty'
import { activeSessions } from './ssh-active-relay-sessions'
import {
assertSshConnectsNotFenced,
connectInFlight,
credentialRequestedForTarget,
invalidateConnectAttempt,
resetRelayInFlight,
testConnectionProbes,
testingTargets
} from './ssh-connect-attempt-registry'
import { connectTarget } from './ssh-connect-flow'
import { connectionManager, persistedStore } from './ssh-ipc-context'
import { getPublicSshState } from './ssh-renderer-broadcast'
import {
disconnectRegisteredSshTarget,
teardownActiveSshSession,
teardownSshTargetTransport
} from './ssh-session-teardown'
import { withSshMaintenanceTransport } from './ssh-maintenance-channel'
import { recordSshConnectionIntent } from './ssh-connection-intent'
import { connectionManager, getCurrentMainWindow, persistedStore } from './ssh-ipc-context'
import { broadcastSshState, getPublicSshState } from './ssh-renderer-broadcast'
import { disconnectRegisteredSshTarget, teardownActiveSshSession } from './ssh-session-teardown'
import { runTargetLifecycle } from './ssh-target-lifecycle-queue'
import { terminateSshTargetSessions } from './ssh-terminate-sessions'

async function doResetRelay(targetId: string, target: SshTarget): Promise<void> {
const inFlightConnect = connectInFlight.get(targetId)
Expand All @@ -57,16 +44,13 @@ async function doResetRelay(targetId: string, target: SshTarget): Promise<void>
}

const existingConn = connectionManager!.getConnection(targetId)
let conn = existingConn
if (!conn) {
// Why re-check: admission fenced this reset before it parked on the in-flight connect, so shutdown
// may have started (and drained) while we waited — opening a transport now would outlive the drain.
assertSshConnectsNotFenced()
conn = await connectionManager!.connect(target)
}
let relayStopAcknowledged = false
try {
await forceStopRelayForTarget(conn, targetId)
// Why a maintenance transport when none is registered: registering one would publish the
// host as up, and a Disconnect the user made must hold through their Reset.
await (existingConn
? forceStopRelayForTarget(existingConn, targetId)
: withSshMaintenanceTransport(target, (conn) => forceStopRelayForTarget(conn, targetId)))
relayStopAcknowledged = true
} finally {
const ptyIds = new Set(getPtyIdsForConnection(targetId))
Expand Down Expand Up @@ -96,9 +80,9 @@ async function doResetRelay(targetId: string, target: SshTarget): Promise<void>
clearProviderPtyState(appPtyId)
deletePtyOwnership(appPtyId)
}
// Why: reset's connect() may trip onCredentialRequest; clear so a later non-prompting doConnect doesn't persist lastRequiredPassphrase=true.
credentialRequestedForTarget.delete(targetId)
await connectionManager!.disconnect(targetId)
if (existingConn) {
await connectionManager!.disconnect(targetId)
}
}
}

Expand All @@ -109,93 +93,34 @@ export function registerSshConnectionHandlers(): void {
})

ipcMain.handle('ssh:connect', async (_event, args: { targetId: string }) => {
return connectTarget(args.targetId)
return connectTarget(args.targetId, 'user')
})

ipcMain.handle('ssh:disconnect', async (_event, args: { targetId: string }) => {
await disconnectRegisteredSshTarget(args.targetId)
ipcMain.handle('ssh:ensureConnected', async (_event, args: { targetId: string }) => {
return connectTarget(args.targetId, 'background')
})

ipcMain.handle('ssh:terminateSessions', async (_event, args: { targetId: string }) => {
invalidateConnectAttempt(args.targetId)
// Why (#12661): an offline sweep tears down local transport only. The caller must be able to tell
// "the host stopped these" from "nobody asked the host", so carry the verdict out of the lifecycle queue.
let outcome: SshTerminateSessionsResult = { terminated: 0, unverifiable: 0 }
await runTargetLifecycle(args.targetId, async () => {
const provider = getSshPtyProvider(args.targetId)
const leases = persistedStore!.getSshRemotePtyLeases(args.targetId)
const ptyIdsByRelayId = new Map<string, string>()
// Why: only leases the app still believes it owns may force a reconnect; a lease whose route
// died for good is swept opportunistically instead, so a target that can no longer answer
// never blocks its own removal (issue #2626, and the renderer tolerates the refusal there).
const ownedRelayIds = new Set<string>()
const trackPtyId = (ptyId: string, owned: boolean): void => {
const relayPtyId = toRelaySshPtyId(args.targetId, ptyId)
if (!ptyIdsByRelayId.has(relayPtyId)) {
ptyIdsByRelayId.set(relayPtyId, toAppSshPtyId(args.targetId, ptyId))
}
if (owned) {
ownedRelayIds.add(relayPtyId)
}
}
for (const ptyId of getPtyIdsForConnection(args.targetId)) {
trackPtyId(ptyId, true)
}
for (const lease of leases) {
if (lease.state === 'terminated') {
continue
}
// Why the predicate and not `state !== 'expired'`: an `expired` lease carrying no
// retirement mark records only that reattach gave up, never that the remote shell died, so
// it is exactly the orphan the user's terminate must reach — and reaching it needs the
// relay, which is what the fence below demands. Only `supersededBy` / `relayIdRecycled`
// prove the route is dead for good, and those stay unowned.
trackPtyId(lease.ptyId, sshRemotePtyLeaseAllowsReattach(lease))
}
const ptyIds = Array.from(ptyIdsByRelayId, ([relayPtyId, appPtyId]) => ({
relayPtyId,
appPtyId
}))

if (ownedRelayIds.size > 0 && !provider) {
throw new Error(
`${SSH_TERMINATE_RECONNECT_REQUIRED}: SSH relay is not connected; reconnect before terminating remote sessions.`
)
}
const shutdownResults = provider
? await Promise.allSettled(
ptyIds.map(({ appPtyId }) =>
provider.shutdown(appPtyId, { immediate: true, keepHistory: false })
)
)
: []
if (!provider) {
// Nothing observed these remote shells, so their state is unknown — not "nothing to do".
outcome = { terminated: 0, unverifiable: ptyIds.length }
}
const shutdownFailures: string[] = []
for (const [index, result] of shutdownResults.entries()) {
const { appPtyId, relayPtyId } = ptyIds[index]
if (result.status !== 'fulfilled' && !isSshPtyNotFoundError(result.reason)) {
shutdownFailures.push(
`${relayPtyId}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`
)
continue
}
clearProviderPtyState(appPtyId)
deletePtyOwnership(appPtyId)
persistedStore!.markSshRemotePtyLease(args.targetId, relayPtyId, 'terminated')
outcome = { ...outcome, terminated: outcome.terminated + 1 }
}
if (shutdownFailures.length > 0) {
// Why: a failed relay shutdown can leave the remote process alive in the grace window; keep the lease/session so the user can retry.
throw new Error(`Failed to terminate SSH host sessions: ${shutdownFailures.join('; ')}`)
ipcMain.handle('ssh:disconnect', async (_event, args: { targetId: string }) => {
// Why only here and not in disconnectRegisteredSshTarget: VM teardown shares that path, and
// only this handler is a user's Disconnect. Written first so every state published during
// the teardown already says the user holds the host down.
recordSshConnectionIntent(args.targetId, 'disconnected')
const hadConnection = connectionManager!.getConnection(args.targetId) !== undefined
await disconnectRegisteredSshTarget(args.targetId)
if (!hadConnection) {
// Why: with no connection object nothing emits 'disconnected', so a failed connect's
// 'error' would otherwise stay published over the user's Disconnect.
const state = getPublicSshState(args.targetId)
if (state) {
broadcastSshState(getCurrentMainWindow, args.targetId, state)
}
await teardownSshTargetTransport(args.targetId, (session) => session.disposeAndPersist())
})
return outcome
}
})

ipcMain.handle('ssh:terminateSessions', (_event, args: { targetId: string }) =>
terminateSshTargetSessions(args.targetId)
)

ipcMain.handle('ssh:resetRelay', (_event, args: { targetId: string }) => {
const existingReset = resetRelayInFlight.get(args.targetId)
if (existingReset) {
Expand Down
34 changes: 34 additions & 0 deletions src/main/ipc/ssh-connection-intent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { SshTarget } from '../../shared/ssh-types'
import { isRuntimeOwnedSshTarget } from '../../shared/execution-host'
import { getSshTargetRegistryStore } from '../ssh/ssh-target-registry'

type SshConnectionIntent = NonNullable<SshTarget['desiredConnection']>

/** True while the user's own Disconnect holds this host down. Runtime-owned targets never are. */
export function isSshTargetDisconnectedByUser(targetId: string): boolean {
const target = getSshTargetRegistryStore()?.getTarget(targetId)
return (
target !== undefined &&
!isRuntimeOwnedSshTarget(target) &&
target.desiredConnection === 'disconnected'
)
}

/**
* Records what the user asked for on the target row itself, so it survives a restart and ends
* with the target. Only a user's Connect or Disconnect may call this — a network drop is never
* the user's intent (docs/reference/ssh-execution-boundary.md).
*/
export function recordSshConnectionIntent(targetId: string, intent: SshConnectionIntent): void {
const store = getSshTargetRegistryStore()
const target = store?.getTarget(targetId)
// Why ownership: a runtime-owned target's lifecycle belongs to the runtime layer, not the user.
if (!store || !target || isRuntimeOwnedSshTarget(target) || target.desiredConnection === intent) {
return
}
store.updateTarget(targetId, { desiredConnection: intent })
}

export function sshTargetDisplayLabel(targetId: string): string {
return getSshTargetRegistryStore()?.getTarget(targetId)?.label ?? targetId
}
4 changes: 4 additions & 0 deletions src/main/ipc/ssh-disconnect-cancellation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ vi.mock('electron', () => mocks.electron)
vi.mock('./ssh-pty-output-intake-registry', () => mocks.sshPtyOutputIntakeRegistry)
vi.mock('../ssh/ssh-connection-store', () => mocks.sshConnectionStore)
vi.mock('../ssh/ssh-connection-manager', () => mocks.sshConnectionManager)
vi.mock('../ssh/ssh-connection', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
...mocks.sshConnection
}))
vi.mock('../ssh/ssh-relay-deploy', () => mocks.sshRelayDeploy)
vi.mock('../ssh/ssh-relay-reset', () => mocks.sshRelayReset)
vi.mock('../ssh/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer)
Expand Down
4 changes: 4 additions & 0 deletions src/main/ipc/ssh-handler-reregistration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ vi.mock('electron', () => mocks.electron)
vi.mock('./ssh-pty-output-intake-registry', () => mocks.sshPtyOutputIntakeRegistry)
vi.mock('../ssh/ssh-connection-store', () => mocks.sshConnectionStore)
vi.mock('../ssh/ssh-connection-manager', () => mocks.sshConnectionManager)
vi.mock('../ssh/ssh-connection', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
...mocks.sshConnection
}))
vi.mock('../ssh/ssh-relay-deploy', () => mocks.sshRelayDeploy)
vi.mock('../ssh/ssh-relay-reset', () => mocks.sshRelayReset)
vi.mock('../ssh/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer)
Expand Down
Loading
Loading