Per-environment SSH state so desktop clients get live SSH overlays for Remote Orca Server workspaces (STA-1468 desktop topology) (#7831)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-07-08 13:17:19 -07:00
committed by GitHub
co-authored by Orca
parent ace196b08e
commit 2b3eba46cb
16 changed files with 1137 additions and 36 deletions
@@ -24,7 +24,17 @@ import TerminalSearch from '@/components/TerminalSearch'
import type { PtyTransport } from './pty-transport'
import { fitPanes, isWindowsUserAgent } from './pane-helpers'
import { getConnectionId, getConnectionIdFromState } from '@/lib/connection-context'
import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner'
import {
getExplicitRuntimeEnvironmentIdForWorktree,
getRuntimeEnvironmentIdForWorktree
} from '@/lib/worktree-runtime-owner'
import {
selectRuntimeAwareSshStatus,
selectRuntimeAwareSshTargetLabel,
selectRuntimeAwareSshTargetRemoved
} from '@/store/slices/runtime-environment-ssh'
import { hydrateRuntimeEnvironmentSshState } from '@/runtime/runtime-environment-ssh-state'
import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome'
import { handleInternalTerminalFileDrop } from './terminal-drop-handler'
import { recordTerminalUserInputForLeaf } from './terminal-input-activity'
import {
@@ -306,33 +316,44 @@ export default function TerminalPane({
}
return connectionId
})
// Which machine's SSH store this target belongs to: a remote Orca server's
// per-environment bucket, or null for this machine's local SSH maps. The
// explicit-owner resolver never lets a merely focused runtime make a
// local-owned workspace look remote. The paired web client mirrors its one
// host through the local maps instead.
const sshReconnectEnvironmentId = useAppStore((store) =>
sshReconnectTargetId && !isPairedWebClientWindow()
? getExplicitRuntimeEnvironmentIdForWorktree(store, worktreeId)
: null
)
const sshReconnectStatus = useAppStore((store) =>
sshReconnectTargetId
? (store.sshConnectionStates.get(sshReconnectTargetId)?.status ?? 'disconnected')
? selectRuntimeAwareSshStatus(store, sshReconnectEnvironmentId, sshReconnectTargetId)
: null
)
const sshReconnectTargetLabel = useAppStore((store) =>
sshReconnectTargetId
? (store.sshTargetLabels.get(sshReconnectTargetId) ??
// Fall back to the removed target's last known label (ghost host) before
// the raw id, so a removed host shows its name instead of ssh-<ts>-<rand>.
store.removedSshTargetLabels.get(sshReconnectTargetId) ??
sshReconnectTargetId)
? selectRuntimeAwareSshTargetLabel(store, sshReconnectEnvironmentId, sshReconnectTargetId)
: ''
)
// Why: the target was removed entirely (a ghost) when it's no longer a known
// SSH target. Reconnecting to it can only fail ("SSH target not found"), so
// the overlay must offer to remove the workspace instead of Connect.
// Removal needs positive evidence — a removal tombstone label, or a
// successfully hydrated target list (even an empty one) that lacks the id.
// A client whose SSH state never hydrated (paired client on an older host)
// must not offer workspace removal off that ignorance.
// SSH target on its owning host. Reconnecting to it can only fail ("SSH
// target not found"), so the overlay must offer to remove the workspace
// instead of Connect. The selector requires positive removal evidence.
const sshReconnectTargetRemoved = useAppStore((store) =>
sshReconnectTargetId
? store.removedSshTargetLabels.has(sshReconnectTargetId) ||
(store.sshTargetsHydrated && !store.sshTargetLabels.has(sshReconnectTargetId))
? selectRuntimeAwareSshTargetRemoved(store, sshReconnectEnvironmentId, sshReconnectTargetId)
: false
)
useEffect(() => {
if (!sshReconnectEnvironmentId) {
return
}
// Why: an SSH-backed workspace can be mirrored before its owning
// environment's bucket ever hydrated (no-op once hydrated), and overlay
// state must come from fetched evidence, never from an empty default.
void hydrateRuntimeEnvironmentSshState(sshReconnectEnvironmentId).catch(() => {})
}, [sshReconnectEnvironmentId])
useVisibleTerminalTabClaim({ isVisible, tabId })
@@ -2991,6 +3012,7 @@ export default function TerminalPane({
status={sshReconnectStatus}
targetRemoved={sshReconnectTargetRemoved}
worktreeId={worktreeId}
sshOwnerEnvironmentId={sshReconnectEnvironmentId}
/>
) : null}
<DaemonActionDialog api={daemonActions} />
@@ -17,6 +17,11 @@ const deleteFlowMocks = vi.hoisted(() => ({
runWorktreeDelete: vi.fn()
}))
const environmentSshMocks = vi.hoisted(() => ({
connectRuntimeEnvironmentSshTarget: vi.fn(),
resyncRuntimeEnvironmentSshTargets: vi.fn()
}))
vi.mock('sonner', () => ({
toast: {
error: toastMocks.error
@@ -27,6 +32,8 @@ vi.mock('../sidebar/delete-worktree-flow', () => ({
runWorktreeDelete: deleteFlowMocks.runWorktreeDelete
}))
vi.mock('@/runtime/runtime-environment-ssh-state', () => environmentSshMocks)
vi.mock('@/i18n/i18n', () => ({
translate: (_key: string, fallback: string, values?: Record<string, string>) =>
fallback.replace('{{value0}}', values?.value0 ?? '')
@@ -54,6 +61,8 @@ describe('TerminalSshReconnectOverlay', () => {
useAppStore.setState(useAppStore.getInitialState(), true)
toastMocks.error.mockReset()
deleteFlowMocks.runWorktreeDelete.mockReset()
environmentSshMocks.connectRuntimeEnvironmentSshTarget.mockReset()
environmentSshMocks.resyncRuntimeEnvironmentSshTargets.mockReset()
})
afterEach(() => {
@@ -190,6 +199,65 @@ describe('TerminalSshReconnectOverlay', () => {
expect(connect).not.toHaveBeenCalled()
})
it('routes Connect to the owning environment runtime RPC for a remote-owned workspace', async () => {
const connect = vi.fn().mockResolvedValue(undefined)
installSshConnect(connect)
environmentSshMocks.connectRuntimeEnvironmentSshTarget.mockResolvedValue(null)
const user = userEvent.setup()
render(
<TerminalSshReconnectOverlay
targetId="ssh-remote-1"
targetLabel="devbox"
status="disconnected"
sshOwnerEnvironmentId="env-1"
/>
)
await user.click(screen.getByRole('button', { name: 'Connect' }))
await waitFor(() =>
expect(environmentSshMocks.connectRuntimeEnvironmentSshTarget).toHaveBeenCalledWith(
'env-1',
'ssh-remote-1'
)
)
// The local ssh API must never see a remote host's target.
expect(connect).not.toHaveBeenCalled()
})
it('resyncs the owning environment (not the local store) after a failed remote connect', async () => {
const connect = vi.fn().mockResolvedValue(undefined)
const listTargets = vi.fn().mockResolvedValue([])
installSshConnect(connect, { listTargets })
environmentSshMocks.connectRuntimeEnvironmentSshTarget.mockRejectedValue(
new Error('SSH target "ssh-remote-dead" not found')
)
environmentSshMocks.resyncRuntimeEnvironmentSshTargets.mockResolvedValue(undefined)
const user = userEvent.setup()
render(
<TerminalSshReconnectOverlay
targetId="ssh-remote-dead"
targetLabel="devbox"
status="disconnected"
sshOwnerEnvironmentId="env-1"
/>
)
await user.click(screen.getByRole('button', { name: 'Connect' }))
await waitFor(() =>
expect(toastMocks.error).toHaveBeenCalledWith('SSH target "ssh-remote-dead" not found')
)
await waitFor(() =>
expect(environmentSshMocks.resyncRuntimeEnvironmentSshTargets).toHaveBeenCalledWith('env-1')
)
// The failed-connect resync must not rewrite local target metadata.
expect(listTargets).not.toHaveBeenCalled()
expect(useAppStore.getState().sshTargetsHydrated).toBe(false)
})
it('publishes the returned SSH state so deferred terminal reattach can resume', async () => {
const connectedState: SshConnectionState = {
targetId: 'ssh-target-1',
@@ -7,6 +7,10 @@ import { useAppStore } from '@/store'
import type { SshConnectionStatus } from '../../../../shared/ssh-types'
import { translate } from '@/i18n/i18n'
import { runWorktreeDelete } from '../sidebar/delete-worktree-flow'
import {
connectRuntimeEnvironmentSshTarget,
resyncRuntimeEnvironmentSshTargets
} from '@/runtime/runtime-environment-ssh-state'
type TerminalSshReconnectOverlayProps = {
targetId: string
@@ -16,6 +20,10 @@ type TerminalSshReconnectOverlayProps = {
// remove the workspace instead of a Connect button that can only fail.
targetRemoved?: boolean
worktreeId?: string
// Set when the SSH target belongs to a remote Orca server (runtime
// environment): Connect and the failed-connect resync then route to that
// environment's runtime RPC and bucket instead of the local ssh.* API.
sshOwnerEnvironmentId?: string | null
}
// Why: relay deployment/reconnect are host-driven transient states; the
@@ -70,7 +78,8 @@ export function TerminalSshReconnectOverlay({
targetLabel,
status,
targetRemoved = false,
worktreeId
worktreeId,
sshOwnerEnvironmentId = null
}: TerminalSshReconnectOverlayProps): React.JSX.Element {
const [connecting, setConnecting] = useState(false)
const mountedRef = useMountedRef()
@@ -85,11 +94,16 @@ export function TerminalSshReconnectOverlay({
}
setConnecting(true)
try {
const connectState = await window.api.ssh.connect({ targetId })
if (connectState) {
// Why: ssh.connect can resolve before the global state-change IPC lands;
// the waiting deferred PTY reattach path keys off this renderer store.
setSshConnectionState(targetId, connectState)
if (sshOwnerEnvironmentId) {
// Bucket state is written inside the helper, mirroring the local path.
await connectRuntimeEnvironmentSshTarget(sshOwnerEnvironmentId, targetId)
} else {
const connectState = await window.api.ssh.connect({ targetId })
if (connectState) {
// Why: ssh.connect can resolve before the global state-change IPC lands;
// the waiting deferred PTY reattach path keys off this renderer store.
setSshConnectionState(targetId, connectState)
}
}
} catch (err) {
toast.error(
@@ -105,18 +119,22 @@ export function TerminalSshReconnectOverlay({
// overlay converges to the ghost/re-adopted state instead of offering
// the same failing Connect forever (STA-1468). Apply the target list
// first — a removed-labels failure must not discard it.
void (async () => {
const targets = await window.api.ssh.listTargets()
useAppStore.getState().setSshTargetsMetadata(targets)
const removedLabels = await window.api.ssh.listRemovedTargetLabels()
useAppStore.getState().setRemovedSshTargetLabels(removedLabels)
})().catch(() => {})
if (sshOwnerEnvironmentId) {
void resyncRuntimeEnvironmentSshTargets(sshOwnerEnvironmentId).catch(() => {})
} else {
void (async () => {
const targets = await window.api.ssh.listTargets()
useAppStore.getState().setSshTargetsMetadata(targets)
const removedLabels = await window.api.ssh.listRemovedTargetLabels()
useAppStore.getState().setRemovedSshTargetLabels(removedLabels)
})().catch(() => {})
}
} finally {
if (mountedRef.current) {
setConnecting(false)
}
}
}, [isConnecting, mountedRef, setSshConnectionState, targetId])
}, [isConnecting, mountedRef, setSshConnectionState, sshOwnerEnvironmentId, targetId])
return (
<div
@@ -5,6 +5,7 @@ import {
buildRuntimeClientEventEnvironmentKey,
buildNewWorkspaceShortcutModalData,
getNewlyConnectedRuntimeEnvironmentIds,
getNewlyDisconnectedRuntimeEnvironmentIds,
getRuntimeProjectRefreshEnvironmentIds,
openNewWorkspaceFromShortcut,
resolveBrowserSessionTabTarget,
@@ -57,6 +58,15 @@ describe('getNewlyConnectedRuntimeEnvironmentIds', () => {
})
})
describe('getNewlyDisconnectedRuntimeEnvironmentIds', () => {
it('returns only environments whose transport was just observed down', () => {
expect(getNewlyDisconnectedRuntimeEnvironmentIds(['env-a', 'env-b'], ['env-a'])).toEqual([
'env-b'
])
expect(getNewlyDisconnectedRuntimeEnvironmentIds(['env-a'], ['env-a', 'env-b'])).toEqual([])
})
})
describe('getRuntimeProjectRefreshEnvironmentIds', () => {
it('refreshes when an already-desired runtime becomes reachable', () => {
expect(
+44 -5
View File
@@ -83,6 +83,10 @@ import { attachMobileMarkdownBridge } from '@/runtime/mobile-markdown-bridge'
import { closeMobileSessionTabInStore } from '@/runtime/mobile-session-tab-close'
import { createWorktreeChangeRefreshQueue } from './worktree-change-refresh-queue'
import { subscribeRuntimeClientEvents } from '@/runtime/runtime-client-events'
import {
applyRuntimeEnvironmentSshStateChanged,
hydrateRuntimeEnvironmentSshState
} from '@/runtime/runtime-environment-ssh-state'
import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome'
import { createRuntimeProjectRefreshScheduler } from './runtime-project-refresh-scheduler'
import { createRuntimeClientEventsSync } from './runtime-client-events-sync'
@@ -770,6 +774,15 @@ export function getNewlyConnectedRuntimeEnvironmentIds(
return [...new Set(next)].filter((environmentId) => !known.has(environmentId))
}
/** Ids in `previous` not in `next` — runtime environments whose transport was
* just observed down. Their mirrored SSH buckets get downgraded to unknown. */
export function getNewlyDisconnectedRuntimeEnvironmentIds(
previous: readonly string[],
next: readonly string[]
): string[] {
return getNewlyConnectedRuntimeEnvironmentIds(next, previous)
}
export function getRuntimeProjectRefreshEnvironmentIds(args: {
previousDesired: readonly string[]
nextDesired: readonly string[]
@@ -955,6 +968,13 @@ export function useIpcEvents(): void {
const runtimeProjectRefreshScheduler = createRuntimeProjectRefreshScheduler({
refresh: async (environmentId) => {
if (!isPairedWebClientWindow()) {
// Why: mirrored SSH-backed workspaces read the owning environment's
// SSH bucket; refresh it whenever the environment (re)connects so a
// pre-drop snapshot can't keep a reconnect overlay stale. The web
// client mirrors host SSH state through the global store instead.
void hydrateRuntimeEnvironmentSshState(environmentId, { force: true }).catch(() => {})
}
const repos = await useAppStore.getState().fetchRuntimeEnvironmentRepos(environmentId)
await refreshRuntimeProjectWorktrees(repos)
await useAppStore.getState().fetchWorktreeLineage()
@@ -975,12 +995,14 @@ export function useIpcEvents(): void {
return
}
if (event.type === 'sshStateChanged') {
// Why: only a paired web client routes its ssh.* API to the host that
// emitted this event, so only there can the store mirror host SSH state
// (STA-1468). Desktop clients own a local SSH surface a foreign
// runtime's targets would pollute, so they ignore it.
// Why: a paired web client mirrors host SSH state in the global store —
// its whole ssh.* API routes to that one host (STA-1468). A desktop
// client owns a local SSH surface those maps must keep describing, so a
// remote host's state goes into that environment's own bucket instead.
if (isPairedWebClientWindow()) {
handleSshStateChangedEvent?.({ targetId: event.targetId, state: event.state })
} else {
applyRuntimeEnvironmentSshStateChanged(environmentId, event.targetId, event.state)
}
return
}
@@ -1008,7 +1030,17 @@ export function useIpcEvents(): void {
const runtimeClientEventsSync = createRuntimeClientEventsSync({
getDesiredEnvironmentIds: getRuntimeClientEventEnvironmentIds,
subscribe: subscribeRuntimeClientEvents,
subscribe: (environmentId, onEvent, onError) =>
subscribeRuntimeClientEvents(environmentId, onEvent, onError, () => {
if (isPairedWebClientWindow()) {
return
}
// Why: sshStateChanged events during the transport gap are lost, so
// the pre-drop bucket may hold a stale "connected". Downgrade to
// unknown, then refetch the authoritative state.
useAppStore.getState().markEnvironmentSshStateStale(environmentId)
void hydrateRuntimeEnvironmentSshState(environmentId, { force: true }).catch(() => {})
}),
onEvent: handleRuntimeClientEvent
})
@@ -1049,6 +1081,13 @@ export function useIpcEvents(): void {
})) {
runtimeProjectRefreshScheduler.request(environmentId)
}
for (const environmentId of getNewlyDisconnectedRuntimeEnvironmentIds(
reachableRuntimeEnvironmentIds,
nextReachableEnvironmentIds
)) {
// No-op when the environment has no SSH bucket (e.g. web client).
useAppStore.getState().markEnvironmentSshStateStale(environmentId)
}
runtimeClientEventEnvironmentIds = nextEnvironmentIds
runtimeClientEventEnvironmentKey = nextKey
reachableRuntimeEnvironmentIds = nextReachableEnvironmentIds
@@ -55,4 +55,47 @@ describe('subscribeRuntimeClientEvents', () => {
subscription.unsubscribe()
expect(unsubscribe).toHaveBeenCalledTimes(1)
})
it('signals a replay-tagged response so event-derived state can resync after a reconnect', async () => {
let capturedOnResponse: ((response: unknown) => void) | undefined
const subscribe = vi.fn(async (_args, nextCallbacks) => {
capturedOnResponse = (nextCallbacks as { onResponse: (response: unknown) => void }).onResponse
return { unsubscribe: vi.fn(), sendBinary: vi.fn() }
})
const onEvent = vi.fn()
const onReplayed = vi.fn()
vi.stubGlobal('window', {
api: {
runtimeEnvironments: { subscribe }
}
})
await subscribeRuntimeClientEvents('env-1', onEvent, vi.fn(), onReplayed)
if (!capturedOnResponse) {
throw new Error('Expected subscription callbacks')
}
capturedOnResponse({
ok: true,
result: { type: 'ready', subscriptionId: 'sub-1' }
})
expect(onReplayed).not.toHaveBeenCalled()
capturedOnResponse({
ok: true,
result: { type: 'ready', subscriptionId: 'sub-1' },
_replayedAfterReconnect: true
})
expect(onReplayed).toHaveBeenCalledTimes(1)
// A replay-tagged event frame both signals and still delivers the event.
capturedOnResponse({
ok: true,
result: { type: 'worktreesChanged', repoId: 'repo-1' },
_replayedAfterReconnect: true
})
expect(onReplayed).toHaveBeenCalledTimes(2)
expect(onEvent).toHaveBeenCalledWith({ type: 'worktreesChanged', repoId: 'repo-1' })
})
})
@@ -3,6 +3,7 @@ import type {
RuntimeClientEventStreamMessage
} from '../../../shared/runtime-client-events'
import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope'
import { isRuntimeSubscriptionReplayResponse } from '../../../shared/runtime-subscription-replay'
export type RuntimeClientEventSubscription = {
unsubscribe: () => void
@@ -11,7 +12,12 @@ export type RuntimeClientEventSubscription = {
export async function subscribeRuntimeClientEvents(
environmentId: string,
onEvent: (event: RuntimeClientEvent) => void,
onError: (error: unknown) => void = console.warn
onError: (error: unknown) => void = console.warn,
// Why: client events emitted while the shared-control transport was down are
// lost, not queued. The replay tag on the first post-reconnect response is
// the renderer's only signal that mirrored event-derived state (e.g. the
// per-environment SSH bucket) may have missed transitions and must resync.
onReplayedAfterReconnect?: () => void
): Promise<RuntimeClientEventSubscription> {
const handle = await window.api.runtimeEnvironments.subscribe(
{
@@ -21,7 +27,7 @@ export async function subscribeRuntimeClientEvents(
},
{
onResponse: (response) => {
handleRuntimeClientEventResponse(response, onEvent, onError)
handleRuntimeClientEventResponse(response, onEvent, onError, onReplayedAfterReconnect)
},
onError
}
@@ -32,12 +38,16 @@ export async function subscribeRuntimeClientEvents(
function handleRuntimeClientEventResponse(
response: RuntimeRpcResponse<unknown>,
onEvent: (event: RuntimeClientEvent) => void,
onError: (error: unknown) => void
onError: (error: unknown) => void,
onReplayedAfterReconnect?: () => void
): void {
if (response.ok === false) {
onError(response.error)
return
}
if (isRuntimeSubscriptionReplayResponse(response)) {
onReplayedAfterReconnect?.()
}
const message = response.result as RuntimeClientEventStreamMessage
if (message.type === 'ready' || message.type === 'end') {
return
@@ -0,0 +1,255 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { SshConnectionState } from '../../../shared/ssh-types'
import { useAppStore } from '@/store'
import {
applyRuntimeEnvironmentSshStateChanged,
connectRuntimeEnvironmentSshTarget,
hydrateRuntimeEnvironmentSshState,
resyncRuntimeEnvironmentSshTargets
} from './runtime-environment-ssh-state'
import { callRuntimeRpc } from './runtime-rpc-client'
vi.mock('./runtime-rpc-client', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
callRuntimeRpc: vi.fn()
}))
const callRuntimeRpcMock = vi.mocked(callRuntimeRpc)
function connState(
targetId: string,
status: SshConnectionState['status'] = 'connected'
): SshConnectionState {
return { targetId, status, error: null, reconnectAttempt: 0 }
}
type RpcResponses = {
targets?: { id: string; label: string }[]
labels?: Record<string, string>
states?: Record<string, SshConnectionState | null>
failListTargets?: boolean
failRemovedLabels?: boolean
}
function installRpcResponses(responses: RpcResponses): void {
callRuntimeRpcMock.mockImplementation((_target, method, params) => {
switch (method) {
case 'ssh.listTargets':
if (responses.failListTargets) {
return Promise.reject(new Error('method not found'))
}
return Promise.resolve({ targets: responses.targets ?? [] } as never)
case 'ssh.listRemovedTargetLabels':
if (responses.failRemovedLabels) {
return Promise.reject(new Error('method not found'))
}
return Promise.resolve({ labels: responses.labels ?? {} } as never)
case 'ssh.getState': {
const targetId = (params as { targetId: string }).targetId
return Promise.resolve({ state: responses.states?.[targetId] ?? null } as never)
}
default:
return Promise.reject(new Error(`unexpected method ${method}`))
}
})
}
let envCounter = 0
function nextEnvId(): string {
envCounter += 1
return `env-${envCounter}`
}
beforeEach(() => {
useAppStore.setState(useAppStore.getInitialState(), true)
callRuntimeRpcMock.mockReset()
})
describe('hydrateRuntimeEnvironmentSshState', () => {
it('populates the environment bucket with targets, tombstones, and per-target states', async () => {
const envId = nextEnvId()
installRpcResponses({
targets: [
{ id: 'ssh-1', label: 'devbox' },
{ id: 'ssh-2', label: 'buildbox' }
],
labels: { 'ssh-old': 'retired box' },
states: { 'ssh-1': connState('ssh-1', 'connected') }
})
await hydrateRuntimeEnvironmentSshState(envId)
const bucket = useAppStore.getState().sshStateByEnvironment.get(envId)
expect(bucket?.targetsHydrated).toBe(true)
expect(bucket?.targetLabels.get('ssh-1')).toBe('devbox')
expect(bucket?.removedTargetLabels.get('ssh-old')).toBe('retired box')
expect(bucket?.connectionStates.get('ssh-1')?.status).toBe('connected')
// ssh-2 had no live state: absent, so reads fall back to 'disconnected'.
expect(bucket?.connectionStates.has('ssh-2')).toBe(false)
// Local maps stay untouched.
expect(useAppStore.getState().sshTargetLabels.size).toBe(0)
expect(useAppStore.getState().sshTargetsHydrated).toBe(false)
// Every call was routed to the owning environment.
for (const [target] of callRuntimeRpcMock.mock.calls) {
expect(target).toEqual({ kind: 'environment', environmentId: envId })
}
})
it('skips refetching when already hydrated unless forced', async () => {
const envId = nextEnvId()
installRpcResponses({ targets: [] })
await hydrateRuntimeEnvironmentSshState(envId)
const callsAfterFirst = callRuntimeRpcMock.mock.calls.length
await hydrateRuntimeEnvironmentSshState(envId)
expect(callRuntimeRpcMock.mock.calls.length).toBe(callsAfterFirst)
await hydrateRuntimeEnvironmentSshState(envId, { force: true })
expect(callRuntimeRpcMock.mock.calls.length).toBeGreaterThan(callsAfterFirst)
})
it('leaves the bucket un-hydrated when the host lacks the ssh RPC methods', async () => {
const envId = nextEnvId()
installRpcResponses({ failListTargets: true })
await expect(hydrateRuntimeEnvironmentSshState(envId)).rejects.toThrow()
const bucket = useAppStore.getState().sshStateByEnvironment.get(envId)
expect(bucket?.targetsHydrated ?? false).toBe(false)
})
it('still hydrates the target list when the removed-labels fetch fails', async () => {
const envId = nextEnvId()
installRpcResponses({
targets: [{ id: 'ssh-1', label: 'devbox' }],
failRemovedLabels: true
})
await hydrateRuntimeEnvironmentSshState(envId)
const bucket = useAppStore.getState().sshStateByEnvironment.get(envId)
expect(bucket?.targetsHydrated).toBe(true)
expect(bucket?.targetLabels.get('ssh-1')).toBe('devbox')
})
})
describe('applyRuntimeEnvironmentSshStateChanged', () => {
it('applies a known target state directly into the owning bucket without RPC', () => {
const envId = nextEnvId()
useAppStore
.getState()
.setEnvironmentSshTargetsMetadata(envId, [{ id: 'ssh-1', label: 'devbox' }])
applyRuntimeEnvironmentSshStateChanged(envId, 'ssh-1', connState('ssh-1', 'disconnected'))
expect(
useAppStore.getState().sshStateByEnvironment.get(envId)?.connectionStates.get('ssh-1')?.status
).toBe('disconnected')
expect(callRuntimeRpcMock).not.toHaveBeenCalled()
// Local map untouched.
expect(useAppStore.getState().sshConnectionStates.size).toBe(0)
})
it('does not touch another environment bucket or local state (no cross-pollution)', () => {
const envA = nextEnvId()
const envB = nextEnvId()
useAppStore.getState().setEnvironmentSshTargetsMetadata(envA, [{ id: 'ssh-1', label: 'a' }])
useAppStore.getState().setEnvironmentSshTargetsMetadata(envB, [{ id: 'ssh-1', label: 'b' }])
const bucketBBefore = useAppStore.getState().sshStateByEnvironment.get(envB)
const localStatesBefore = useAppStore.getState().sshConnectionStates
applyRuntimeEnvironmentSshStateChanged(envA, 'ssh-1', connState('ssh-1', 'connected'))
const state = useAppStore.getState()
expect(state.sshStateByEnvironment.get(envA)?.connectionStates.get('ssh-1')?.status).toBe(
'connected'
)
expect(state.sshStateByEnvironment.get(envB)).toBe(bucketBBefore)
expect(state.sshStateByEnvironment.get(envB)?.connectionStates.size).toBe(0)
expect(state.sshConnectionStates).toBe(localStatesBefore)
expect(state.sshConnectionStates.size).toBe(0)
})
it('re-fetches the authoritative target list for an unknown target instead of trusting the event', async () => {
const envId = nextEnvId()
// The event races a removal: the authoritative list does not contain it.
installRpcResponses({ targets: [], labels: { 'ssh-gone': 'old devbox' } })
applyRuntimeEnvironmentSshStateChanged(envId, 'ssh-gone', connState('ssh-gone', 'disconnected'))
await vi.waitFor(() => {
expect(useAppStore.getState().sshStateByEnvironment.get(envId)?.targetsHydrated).toBe(true)
})
const bucket = useAppStore.getState().sshStateByEnvironment.get(envId)
// The trailing event must not resurrect the removed target's state.
expect(bucket?.connectionStates.has('ssh-gone')).toBe(false)
expect(bucket?.removedTargetLabels.get('ssh-gone')).toBe('old devbox')
})
it('picks up a just-added target through the forced refresh', async () => {
const envId = nextEnvId()
installRpcResponses({
targets: [{ id: 'ssh-new', label: 'fresh box' }],
states: { 'ssh-new': connState('ssh-new', 'connecting') }
})
applyRuntimeEnvironmentSshStateChanged(envId, 'ssh-new', connState('ssh-new', 'connecting'))
await vi.waitFor(() => {
expect(
useAppStore.getState().sshStateByEnvironment.get(envId)?.targetLabels.get('ssh-new')
).toBe('fresh box')
})
expect(
useAppStore.getState().sshStateByEnvironment.get(envId)?.connectionStates.get('ssh-new')
?.status
).toBe('connecting')
})
})
describe('connectRuntimeEnvironmentSshTarget', () => {
it('routes ssh.connect to the owning environment and mirrors the returned state', async () => {
const envId = nextEnvId()
callRuntimeRpcMock.mockResolvedValue({ state: connState('ssh-1', 'connected') } as never)
const state = await connectRuntimeEnvironmentSshTarget(envId, 'ssh-1')
expect(state?.status).toBe('connected')
expect(callRuntimeRpcMock).toHaveBeenCalledWith(
{ kind: 'environment', environmentId: envId },
'ssh.connect',
{ targetId: 'ssh-1' },
expect.anything()
)
expect(
useAppStore.getState().sshStateByEnvironment.get(envId)?.connectionStates.get('ssh-1')?.status
).toBe('connected')
expect(useAppStore.getState().sshConnectionStates.size).toBe(0)
})
it('propagates connect failures without writing any state', async () => {
const envId = nextEnvId()
callRuntimeRpcMock.mockRejectedValue(new Error('SSH target not found'))
await expect(connectRuntimeEnvironmentSshTarget(envId, 'ssh-dead')).rejects.toThrow(
'SSH target not found'
)
expect(useAppStore.getState().sshStateByEnvironment.has(envId)).toBe(false)
})
})
describe('resyncRuntimeEnvironmentSshTargets', () => {
it('applies the target list even when the removed-labels refresh fails', async () => {
const envId = nextEnvId()
installRpcResponses({
targets: [{ id: 'ssh-live', label: 'devbox' }],
failRemovedLabels: true
})
await resyncRuntimeEnvironmentSshTargets(envId)
const bucket = useAppStore.getState().sshStateByEnvironment.get(envId)
expect(bucket?.targetLabels.get('ssh-live')).toBe('devbox')
expect(bucket?.targetsHydrated).toBe(true)
})
})
@@ -0,0 +1,165 @@
import { useAppStore } from '@/store'
import type { SshConnectionState, SshTarget } from '../../../shared/ssh-types'
import { callRuntimeRpc } from './runtime-rpc-client'
/**
* Mirrors a remote Orca server's own SSH targets into that environment's
* per-environment SSH bucket (store slice `runtime-environment-ssh`), so a
* desktop client attached to the server gets live reconnect overlays for the
* server's SSH-backed workspaces (STA-1468, desktop topology). Never touches
* the local SSH maps.
*/
const SSH_RPC_TIMEOUT_MS = 15_000
function environmentTarget(environmentId: string): { kind: 'environment'; environmentId: string } {
return { kind: 'environment', environmentId }
}
async function fetchEnvironmentSshTargets(environmentId: string): Promise<SshTarget[]> {
const { targets } = await callRuntimeRpc<{ targets: SshTarget[] }>(
environmentTarget(environmentId),
'ssh.listTargets',
undefined,
{ timeoutMs: SSH_RPC_TIMEOUT_MS }
)
return targets
}
/** Applies the environment's target list, then best-effort removal tombstones.
* Targets land first — a removed-labels failure must not discard them
* (they alone are enough evidence for the ghost-host derivation). */
async function syncEnvironmentSshTargetMetadata(environmentId: string): Promise<SshTarget[]> {
const targets = await fetchEnvironmentSshTargets(environmentId)
useAppStore.getState().setEnvironmentSshTargetsMetadata(environmentId, targets)
try {
const { labels } = await callRuntimeRpc<{ labels: Record<string, string> }>(
environmentTarget(environmentId),
'ssh.listRemovedTargetLabels',
undefined,
{ timeoutMs: SSH_RPC_TIMEOUT_MS }
)
useAppStore.getState().setEnvironmentRemovedSshTargetLabels(environmentId, labels)
} catch {
// Best-effort — a missing map just falls back to the raw target id.
}
return targets
}
async function fetchEnvironmentSshConnectionStates(
environmentId: string,
targets: readonly SshTarget[]
): Promise<void> {
for (const target of targets) {
try {
const { state } = await callRuntimeRpc<{ state: SshConnectionState | null }>(
environmentTarget(environmentId),
'ssh.getState',
{ targetId: target.id },
{ timeoutMs: SSH_RPC_TIMEOUT_MS }
)
if (state) {
useAppStore.getState().setEnvironmentSshConnectionState(environmentId, target.id, state)
}
} catch {
// A missing state just reads as 'disconnected'; the overlay's Connect
// action and push events converge it.
}
}
}
type HydrationEntry = { promise: Promise<void>; rerunRequested: boolean }
const hydrationsInFlight = new Map<string, HydrationEntry>()
async function runEnvironmentSshHydration(environmentId: string): Promise<void> {
const targets = await syncEnvironmentSshTargetMetadata(environmentId)
await fetchEnvironmentSshConnectionStates(environmentId, targets)
}
/**
* Fetches the environment's SSH targets, removal tombstones, and per-target
* connection states into its bucket. Single-flight per environment; a `force`
* request during an in-flight run schedules exactly one follow-up run so a
* refresh triggered by a just-added target can't be swallowed by a stale
* in-flight fetch.
*
* Hosts without the ssh.* RPC methods fail here and leave the bucket
* un-hydrated — reads then resolve to "unknown", never to destructive UI.
*/
export async function hydrateRuntimeEnvironmentSshState(
environmentId: string,
options: { force?: boolean } = {}
): Promise<void> {
const inFlight = hydrationsInFlight.get(environmentId)
if (inFlight) {
if (options.force) {
inFlight.rerunRequested = true
}
return inFlight.promise
}
const bucket = useAppStore.getState().sshStateByEnvironment.get(environmentId)
if (!options.force && bucket?.targetsHydrated) {
return
}
const entry: HydrationEntry = { promise: Promise.resolve(), rerunRequested: false }
entry.promise = (async () => {
try {
await runEnvironmentSshHydration(environmentId)
while (entry.rerunRequested) {
entry.rerunRequested = false
await runEnvironmentSshHydration(environmentId)
}
} finally {
hydrationsInFlight.delete(environmentId)
}
})()
hydrationsInFlight.set(environmentId, entry)
return entry.promise
}
/**
* Applies a `sshStateChanged` runtime client event from `environmentId` to
* that environment's bucket. For a target the bucket doesn't know yet
* (added after hydration, or a disconnect racing a removal), the authoritative
* target list is re-fetched instead of trusting the event: the forced
* hydration also re-reads the state, so a removed target's trailing event
* can't resurrect it.
*/
export function applyRuntimeEnvironmentSshStateChanged(
environmentId: string,
targetId: string,
state: SshConnectionState
): void {
const store = useAppStore.getState()
const bucket = store.sshStateByEnvironment.get(environmentId)
if (bucket?.targetsHydrated && bucket.targetLabels.has(targetId)) {
store.setEnvironmentSshConnectionState(environmentId, targetId, state)
return
}
void hydrateRuntimeEnvironmentSshState(environmentId, { force: true }).catch(() => {})
}
/** Connects the environment's own SSH target via its runtime RPC and mirrors
* the returned state into the bucket (ssh.connect can resolve before the
* push event lands). */
export async function connectRuntimeEnvironmentSshTarget(
environmentId: string,
targetId: string
): Promise<SshConnectionState | null> {
const { state } = await callRuntimeRpc<{ state: SshConnectionState | null }>(
environmentTarget(environmentId),
'ssh.connect',
{ targetId },
{ timeoutMs: 60_000 }
)
if (state) {
useAppStore.getState().setEnvironmentSshConnectionState(environmentId, targetId, state)
}
return state
}
/** Resyncs the environment's target metadata after a failed connect so a
* stale overlay converges to the ghost/re-adopted state (STA-1468). */
export async function resyncRuntimeEnvironmentSshTargets(environmentId: string): Promise<void> {
await syncEnvironmentSshTargetMetadata(environmentId)
}
+2
View File
@@ -23,6 +23,7 @@ import { createOpenCodeUsageSlice } from './slices/opencode-usage'
import { createBrowserSlice } from './slices/browser'
import { createRateLimitSlice } from './slices/rate-limits'
import { createSshSlice } from './slices/ssh'
import { createRuntimeEnvironmentSshSlice } from './slices/runtime-environment-ssh'
import { createAgentStatusSlice } from './slices/agent-status'
import { createPaneForegroundAgentSlice } from './slices/pane-foreground-agent'
import { createDiffCommentsSlice } from './slices/diffComments'
@@ -61,6 +62,7 @@ export const useAppStore = create<AppState>()((...a) => ({
...createBrowserSlice(...a),
...createRateLimitSlice(...a),
...createSshSlice(...a),
...createRuntimeEnvironmentSshSlice(...a),
...createAgentStatusSlice(...a),
...createPaneForegroundAgentSlice(...a),
...createDiffCommentsSlice(...a),
@@ -128,6 +128,7 @@ import { createOpenCodeUsageSlice } from './opencode-usage'
import { createBrowserSlice } from './browser'
import { createRateLimitSlice } from './rate-limits'
import { createSshSlice } from './ssh'
import { createRuntimeEnvironmentSshSlice } from './runtime-environment-ssh'
import { createAgentStatusSlice } from './agent-status'
import { createPaneForegroundAgentSlice } from './pane-foreground-agent'
import { createDiffCommentsSlice } from './diffComments'
@@ -165,6 +166,7 @@ function createTestStore() {
...createBrowserSlice(...a),
...createRateLimitSlice(...a),
...createSshSlice(...a),
...createRuntimeEnvironmentSshSlice(...a),
...createAgentStatusSlice(...a),
...createPaneForegroundAgentSlice(...a),
...createDiffCommentsSlice(...a),
@@ -0,0 +1,198 @@
import { describe, expect, it } from 'vitest'
import type { SshConnectionState } from '../../../../shared/ssh-types'
import type { RuntimeStatus } from '../../../../shared/runtime-types'
import { createTestStore } from './store-test-helpers'
import {
selectRuntimeAwareSshStatus,
selectRuntimeAwareSshTargetLabel,
selectRuntimeAwareSshTargetRemoved
} from './runtime-environment-ssh'
const ENV_A = 'env-a'
const ENV_B = 'env-b'
function connState(
targetId: string,
status: SshConnectionState['status'] = 'connected'
): SshConnectionState {
return { targetId, status, error: null, reconnectAttempt: 0 }
}
function markReachable(store: ReturnType<typeof createTestStore>, environmentId: string): void {
store.getState().setRuntimeEnvironmentStatus(environmentId, {
status: { runtimeId: environmentId } as RuntimeStatus,
checkedAt: Date.now()
})
}
describe('runtime-environment-ssh slice', () => {
it('routes state into the owning environment bucket without touching local maps or other buckets', () => {
const store = createTestStore()
store.getState().setEnvironmentSshTargetsMetadata(ENV_B, [{ id: 'ssh-b', label: 'b-box' }])
const localStatesBefore = store.getState().sshConnectionStates
const localLabelsBefore = store.getState().sshTargetLabels
const bucketBBefore = store.getState().sshStateByEnvironment.get(ENV_B)
store.getState().setEnvironmentSshConnectionState(ENV_A, 'ssh-a', connState('ssh-a'))
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }])
store.getState().setEnvironmentRemovedSshTargetLabels(ENV_A, { 'ssh-dead': 'old box' })
const state = store.getState()
// Local maps: bit-identical (same references, still empty).
expect(state.sshConnectionStates).toBe(localStatesBefore)
expect(state.sshTargetLabels).toBe(localLabelsBefore)
expect(state.sshConnectionStates.size).toBe(0)
expect(state.sshTargetsHydrated).toBe(false)
// Environment B's bucket: untouched reference.
expect(state.sshStateByEnvironment.get(ENV_B)).toBe(bucketBBefore)
// Environment A's bucket: populated.
const bucketA = state.sshStateByEnvironment.get(ENV_A)
expect(bucketA?.connectionStates.get('ssh-a')?.status).toBe('connected')
expect(bucketA?.targetLabels.get('ssh-a')).toBe('a-box')
expect(bucketA?.removedTargetLabels.get('ssh-dead')).toBe('old box')
expect(bucketA?.targetsHydrated).toBe(true)
})
it('local slice writes never leak into environment buckets', () => {
const store = createTestStore()
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }])
const bucketBefore = store.getState().sshStateByEnvironment.get(ENV_A)
store.getState().setSshConnectionState('ssh-a', connState('ssh-a', 'disconnected'))
store.getState().setSshTargetsMetadata([{ id: 'ssh-a', label: 'local a' } as never])
expect(store.getState().sshStateByEnvironment.get(ENV_A)).toBe(bucketBefore)
expect(store.getState().sshStateByEnvironment.get(ENV_A)?.connectionStates.size).toBe(0)
})
it('keeps references stable when applying an identical state or target list', () => {
const store = createTestStore()
store.getState().setEnvironmentSshConnectionState(ENV_A, 'ssh-a', connState('ssh-a'))
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }])
const mapBefore = store.getState().sshStateByEnvironment
const bucketBefore = mapBefore.get(ENV_A)
store.getState().setEnvironmentSshConnectionState(ENV_A, 'ssh-a', connState('ssh-a'))
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }])
store.getState().setEnvironmentRemovedSshTargetLabels(ENV_A, {})
expect(store.getState().sshStateByEnvironment).toBe(mapBefore)
expect(store.getState().sshStateByEnvironment.get(ENV_A)).toBe(bucketBefore)
})
it('flips the hydrated flag on the first fetch of an empty target list', () => {
const store = createTestStore()
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [])
expect(store.getState().sshStateByEnvironment.get(ENV_A)?.targetsHydrated).toBe(true)
})
it('drops only the detached environment bucket on retain', () => {
const store = createTestStore()
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }])
store.getState().setEnvironmentSshTargetsMetadata(ENV_B, [{ id: 'ssh-b', label: 'b-box' }])
store.getState().setSshTargetsMetadata([{ id: 'ssh-local', label: 'local' } as never])
const bucketB = store.getState().sshStateByEnvironment.get(ENV_B)
const localLabels = store.getState().sshTargetLabels
store.getState().retainEnvironmentSshState([ENV_B])
expect(store.getState().sshStateByEnvironment.has(ENV_A)).toBe(false)
expect(store.getState().sshStateByEnvironment.get(ENV_B)).toBe(bucketB)
expect(store.getState().sshTargetLabels).toBe(localLabels)
})
it('detaching an environment through setRuntimeEnvironments drops its bucket', () => {
const store = createTestStore()
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }])
store.getState().setEnvironmentSshTargetsMetadata(ENV_B, [{ id: 'ssh-b', label: 'b-box' }])
store.getState().setRuntimeEnvironments([{ id: ENV_B, name: 'B', createdAt: 0 } as never])
expect(store.getState().sshStateByEnvironment.has(ENV_A)).toBe(false)
expect(store.getState().sshStateByEnvironment.has(ENV_B)).toBe(true)
})
it('markEnvironmentSshStateStale downgrades to unknown but keeps labels for display', () => {
const store = createTestStore()
markReachable(store, ENV_A)
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-a', label: 'a-box' }])
store.getState().setEnvironmentSshConnectionState(ENV_A, 'ssh-a', connState('ssh-a'))
expect(selectRuntimeAwareSshStatus(store.getState(), ENV_A, 'ssh-a')).toBe('connected')
store.getState().markEnvironmentSshStateStale(ENV_A)
const bucket = store.getState().sshStateByEnvironment.get(ENV_A)
expect(bucket?.targetsHydrated).toBe(false)
expect(bucket?.connectionStates.size).toBe(0)
expect(bucket?.targetLabels.get('ssh-a')).toBe('a-box')
// Un-hydrated bucket reads as unknown — no overlay, no removal evidence.
expect(selectRuntimeAwareSshStatus(store.getState(), ENV_A, 'ssh-a')).toBeNull()
expect(selectRuntimeAwareSshTargetRemoved(store.getState(), ENV_A, 'ssh-a')).toBe(false)
})
describe('selectors', () => {
it('resolve the local maps when the owning environment is null', () => {
const store = createTestStore()
store.getState().setSshConnectionState('ssh-local', connState('ssh-local', 'disconnected'))
store.getState().setSshTargetsMetadata([{ id: 'ssh-local', label: 'local box' } as never])
// A same-id target in a bucket must not shadow the local resolution.
markReachable(store, ENV_A)
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [])
const state = store.getState()
expect(selectRuntimeAwareSshStatus(state, null, 'ssh-local')).toBe('disconnected')
expect(selectRuntimeAwareSshTargetLabel(state, null, 'ssh-local')).toBe('local box')
expect(selectRuntimeAwareSshTargetRemoved(state, null, 'ssh-local')).toBe(false)
expect(selectRuntimeAwareSshTargetRemoved(state, null, 'ssh-gone')).toBe(true)
})
it('resolve the owning environment bucket, not local state, for a remote-owned target', () => {
const store = createTestStore()
markReachable(store, ENV_A)
// Same target id exists locally as connected — must not leak into the
// environment read.
store.getState().setSshConnectionState('ssh-1', connState('ssh-1', 'connected'))
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-1', label: 'devbox' }])
store
.getState()
.setEnvironmentSshConnectionState(ENV_A, 'ssh-1', connState('ssh-1', 'disconnected'))
const state = store.getState()
expect(selectRuntimeAwareSshStatus(state, ENV_A, 'ssh-1')).toBe('disconnected')
expect(selectRuntimeAwareSshTargetLabel(state, ENV_A, 'ssh-1')).toBe('devbox')
expect(selectRuntimeAwareSshTargetRemoved(state, ENV_A, 'ssh-1')).toBe(false)
})
it('return unknown (null status) for an unreachable environment even with a hydrated bucket', () => {
const store = createTestStore()
markReachable(store, ENV_A)
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [{ id: 'ssh-1', label: 'devbox' }])
store
.getState()
.setEnvironmentSshConnectionState(ENV_A, 'ssh-1', connState('ssh-1', 'disconnected'))
// Environment probe now records unreachable.
store.getState().setRuntimeEnvironmentStatus(ENV_A, { status: null, checkedAt: Date.now() })
const state = store.getState()
expect(selectRuntimeAwareSshStatus(state, ENV_A, 'ssh-1')).toBeNull()
expect(selectRuntimeAwareSshTargetRemoved(state, ENV_A, 'ssh-1')).toBe(false)
})
it('never report removal from an un-hydrated bucket, and report it from a hydrated one', () => {
const store = createTestStore()
markReachable(store, ENV_A)
const before = store.getState()
expect(selectRuntimeAwareSshTargetRemoved(before, ENV_A, 'ssh-ghost')).toBe(false)
expect(selectRuntimeAwareSshStatus(before, ENV_A, 'ssh-ghost')).toBeNull()
store.getState().setEnvironmentSshTargetsMetadata(ENV_A, [])
const after = store.getState()
expect(selectRuntimeAwareSshTargetRemoved(after, ENV_A, 'ssh-ghost')).toBe(true)
// Removal tombstones win the label fallback for ghost hosts.
store.getState().setEnvironmentRemovedSshTargetLabels(ENV_A, { 'ssh-ghost': 'old devbox' })
expect(selectRuntimeAwareSshTargetLabel(store.getState(), ENV_A, 'ssh-ghost')).toBe(
'old devbox'
)
})
})
})
@@ -0,0 +1,263 @@
import type { StateCreator } from 'zustand'
import type { AppState } from '../types'
import type {
SshConnectionState,
SshConnectionStatus,
SshTarget
} from '../../../../shared/ssh-types'
import { sshConnectionStatesEqual, sshTargetLabelsEqual } from './ssh-target-cleanup'
/**
* SSH state of one remote Orca server's own SSH targets, mirrored on this
* client. Kept strictly separate from the local `SshSlice` maps so a remote
* machine's targets can never pollute local SSH settings, pickers, or the
* execution-host registry — and vice versa (STA-1468, desktop topology).
*/
export type RuntimeEnvironmentSshBucket = {
connectionStates: Map<string, SshConnectionState>
targetLabels: Map<string, string>
removedTargetLabels: Map<string, string>
/** Mirrors the local `sshTargetsHydrated` positive-evidence rule: absence
* from `targetLabels` only counts as target removal once a target list
* actually loaded from that environment (even an empty one). */
targetsHydrated: boolean
}
export type RuntimeEnvironmentSshSlice = {
/**
* Per-runtime-environment SSH state buckets, keyed by environment id.
* Do NOT read this map directly from components — use the
* `selectRuntimeAwareSsh*` selectors below, which route between the local
* SSH maps (`environmentId === null`) and the owning environment's bucket.
*/
sshStateByEnvironment: Map<string, RuntimeEnvironmentSshBucket>
setEnvironmentSshConnectionState: (
environmentId: string,
targetId: string,
state: SshConnectionState
) => void
setEnvironmentSshTargetsMetadata: (
environmentId: string,
targets: Pick<SshTarget, 'id' | 'label'>[]
) => void
setEnvironmentRemovedSshTargetLabels: (
environmentId: string,
labels: Record<string, string>
) => void
/** Transport to the environment dropped: its mirrored SSH state can no
* longer be trusted (it may hold a pre-drop "connected"). Downgrades the
* bucket to unhydrated and clears connection states so reads resolve to
* "unknown" until a reconnect re-hydrates. */
markEnvironmentSshStateStale: (environmentId: string) => void
removeEnvironmentSshState: (environmentId: string) => void
/** Drops buckets for environments no longer in the saved set. */
retainEnvironmentSshState: (environmentIds: Iterable<string>) => void
}
const EMPTY_BUCKET: RuntimeEnvironmentSshBucket = {
connectionStates: new Map(),
targetLabels: new Map(),
removedTargetLabels: new Map(),
targetsHydrated: false
}
function getBucket(
buckets: Map<string, RuntimeEnvironmentSshBucket>,
environmentId: string
): RuntimeEnvironmentSshBucket {
return buckets.get(environmentId) ?? EMPTY_BUCKET
}
function withBucket(
s: Pick<AppState, 'sshStateByEnvironment'>,
environmentId: string,
bucket: RuntimeEnvironmentSshBucket
): Pick<AppState, 'sshStateByEnvironment'> {
const next = new Map(s.sshStateByEnvironment)
next.set(environmentId, bucket)
return { sshStateByEnvironment: next }
}
function removedLabelsEqual(current: Map<string, string>, labels: Record<string, string>): boolean {
const entries = Object.entries(labels)
return (
entries.length === current.size && entries.every(([id, label]) => current.get(id) === label)
)
}
export const createRuntimeEnvironmentSshSlice: StateCreator<
AppState,
[],
[],
RuntimeEnvironmentSshSlice
> = (set) => ({
sshStateByEnvironment: new Map(),
setEnvironmentSshConnectionState: (environmentId, targetId, state) =>
set((s) => {
const bucket = getBucket(s.sshStateByEnvironment, environmentId)
if (sshConnectionStatesEqual(bucket.connectionStates.get(targetId), state)) {
return s
}
const connectionStates = new Map(bucket.connectionStates)
connectionStates.set(targetId, state)
return withBucket(s, environmentId, { ...bucket, connectionStates })
}),
setEnvironmentSshTargetsMetadata: (environmentId, targets) =>
set((s) => {
const bucket = getBucket(s.sshStateByEnvironment, environmentId)
if (sshTargetLabelsEqual(bucket.targetLabels, targets)) {
// Why: an unchanged (even empty) list is still a successful load — the
// hydration flag must flip on the first fetch of an empty target set.
return bucket.targetsHydrated
? s
: withBucket(s, environmentId, { ...bucket, targetsHydrated: true })
}
return withBucket(s, environmentId, {
...bucket,
targetLabels: new Map(targets.map((target) => [target.id, target.label])),
targetsHydrated: true
})
}),
setEnvironmentRemovedSshTargetLabels: (environmentId, labels) =>
set((s) => {
const bucket = getBucket(s.sshStateByEnvironment, environmentId)
if (removedLabelsEqual(bucket.removedTargetLabels, labels)) {
return s
}
return withBucket(s, environmentId, {
...bucket,
removedTargetLabels: new Map(Object.entries(labels))
})
}),
markEnvironmentSshStateStale: (environmentId) =>
set((s) => {
const bucket = s.sshStateByEnvironment.get(environmentId)
if (!bucket || (!bucket.targetsHydrated && bucket.connectionStates.size === 0)) {
return s
}
// Labels are kept so a re-hydrating overlay can still show a friendly
// host name; hydration=false alone forces reads back to "unknown".
return withBucket(s, environmentId, {
...bucket,
connectionStates: new Map(),
targetsHydrated: false
})
}),
removeEnvironmentSshState: (environmentId) =>
set((s) => {
if (!s.sshStateByEnvironment.has(environmentId)) {
return s
}
const next = new Map(s.sshStateByEnvironment)
next.delete(environmentId)
return { sshStateByEnvironment: next }
}),
retainEnvironmentSshState: (environmentIds) =>
set((s) => {
const keep = new Set(environmentIds)
let changed = false
const next = new Map(s.sshStateByEnvironment)
for (const id of next.keys()) {
if (!keep.has(id)) {
next.delete(id)
changed = true
}
}
return changed ? { sshStateByEnvironment: next } : s
})
})
type RuntimeAwareSshReadState = Pick<
AppState,
| 'sshConnectionStates'
| 'sshTargetLabels'
| 'removedSshTargetLabels'
| 'sshTargetsHydrated'
| 'sshStateByEnvironment'
> &
Partial<Pick<AppState, 'runtimeStatusByEnvironmentId'>>
function isEnvironmentReachable(state: RuntimeAwareSshReadState, environmentId: string): boolean {
return Boolean(state.runtimeStatusByEnvironmentId?.get(environmentId)?.status)
}
/**
* Reconnect-overlay status for an SSH target owned by `environmentId` (a
* remote Orca server) or by this machine (`environmentId === null`).
*
* Returns null when the state is unknown — environment unreachable or its
* bucket not hydrated — so callers show nothing rather than another machine's
* stale state. The runtime environment's own disconnected UI outranks any SSH
* overlay in that case.
*/
export function selectRuntimeAwareSshStatus(
state: RuntimeAwareSshReadState,
environmentId: string | null,
targetId: string
): SshConnectionStatus | null {
if (environmentId === null) {
return state.sshConnectionStates.get(targetId)?.status ?? 'disconnected'
}
if (!isEnvironmentReachable(state, environmentId)) {
return null
}
const bucket = state.sshStateByEnvironment.get(environmentId)
if (!bucket?.targetsHydrated) {
return null
}
return bucket.connectionStates.get(targetId)?.status ?? 'disconnected'
}
export function selectRuntimeAwareSshTargetLabel(
state: RuntimeAwareSshReadState,
environmentId: string | null,
targetId: string
): string {
if (environmentId === null) {
return (
state.sshTargetLabels.get(targetId) ??
// Fall back to the removed target's last known label (ghost host) before
// the raw id, so a removed host shows its name instead of ssh-<ts>-<rand>.
state.removedSshTargetLabels.get(targetId) ??
targetId
)
}
const bucket = state.sshStateByEnvironment.get(environmentId)
return bucket?.targetLabels.get(targetId) ?? bucket?.removedTargetLabels.get(targetId) ?? targetId
}
/**
* True only on positive evidence that the target was removed on its owning
* host: a removal tombstone, or a hydrated target list that lacks the id.
* An unreachable environment or un-hydrated bucket never reports removal, so
* destructive "remove workspace" UI cannot be offered out of ignorance.
*/
export function selectRuntimeAwareSshTargetRemoved(
state: RuntimeAwareSshReadState,
environmentId: string | null,
targetId: string
): boolean {
if (environmentId === null) {
return (
state.removedSshTargetLabels.has(targetId) ||
(state.sshTargetsHydrated && !state.sshTargetLabels.has(targetId))
)
}
if (!isEnvironmentReachable(state, environmentId)) {
return false
}
const bucket = state.sshStateByEnvironment.get(environmentId)
if (!bucket) {
return false
}
return (
bucket.removedTargetLabels.has(targetId) ||
(bucket.targetsHydrated && !bucket.targetLabels.has(targetId))
)
}
@@ -66,6 +66,8 @@ export const createRuntimeStatusSlice: StateCreator<AppState, [], [], RuntimeSta
// Optional-chained: minimal store assemblies (some unit tests) omit the
// detected-agents slice.
get().retainRuntimeDetectedAgents?.(environments.map((environment) => environment.id))
// A detached environment's mirrored SSH state must not outlive it.
get().retainEnvironmentSshState?.(environments.map((environment) => environment.id))
},
setRuntimeEnvironmentStatus: (environmentId, status) => {
@@ -31,6 +31,7 @@ import { createOpenCodeUsageSlice } from './opencode-usage'
import { createBrowserSlice } from './browser'
import { createRateLimitSlice } from './rate-limits'
import { createSshSlice } from './ssh'
import { createRuntimeEnvironmentSshSlice } from './runtime-environment-ssh'
import { createAgentStatusSlice } from './agent-status'
import { createPaneForegroundAgentSlice } from './pane-foreground-agent'
import { createDiffCommentsSlice } from './diffComments'
@@ -77,6 +78,7 @@ export function createTestStore() {
...createBrowserSlice(...a),
...createRateLimitSlice(...a),
...createSshSlice(...a),
...createRuntimeEnvironmentSshSlice(...a),
...createAgentStatusSlice(...a),
...createPaneForegroundAgentSlice(...a),
...createDiffCommentsSlice(...a),
+2
View File
@@ -21,6 +21,7 @@ import type { OpenCodeUsageSlice } from './slices/opencode-usage'
import type { BrowserSlice } from './slices/browser'
import type { RateLimitSlice } from './slices/rate-limits'
import type { SshSlice } from './slices/ssh'
import type { RuntimeEnvironmentSshSlice } from './slices/runtime-environment-ssh'
import type { AgentStatusSlice } from './slices/agent-status'
import type { PaneForegroundAgentSlice } from './slices/pane-foreground-agent'
import type { DiffCommentsSlice } from './slices/diffComments'
@@ -56,6 +57,7 @@ export type AppState = RepoSlice &
BrowserSlice &
RateLimitSlice &
SshSlice &
RuntimeEnvironmentSshSlice &
AgentStatusSlice &
PaneForegroundAgentSlice &
DiffCommentsSlice &