Skip to content

Per-environment SSH state: desktop clients attached to a Remote Orca Server get working SSH overlays/Connect (STA-1468 desktop topology) - #7831

Merged
Jinwoo-H merged 1 commit into
mainfrom
fix/desktop-remote-ssh-parity
Jul 8, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
fix/desktop-remote-ssh-parity

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Problem — STA-1468, desktop flavor (#7718 family)

PR #7767 fixed the stale "SSH connection required" overlay for paired web clients, but a desktop client attached to a Remote Orca Server — per user feedback the most common topology (Orca on a devbox, attached from another desktop) — still had the original symptom:

  • The host emits sshStateChanged runtime client events for its SSH targets, but the desktop client deliberately dropped them (useIpcEvents.ts gated the event on isPairedWebClientWindow()), because applying a foreign machine's SSH state into the renderer's single global SSH store would collide with the desktop's own local SSH targets.
  • Result: a desktop client mirroring a remote machine's SSH-backed workspace showed a permanently stale overlay (or none when one was needed), and its Connect button called the local window.api.ssh.connect for a target id that only exists on the host.

Design

Store: SSH state scoped by owning environment. New slice runtime-environment-ssh.ts adds sshStateByEnvironment: Map<envId, bucket> where each bucket mirrors the local shape (connectionStates, targetLabels, removedTargetLabels, targetsHydrated with the same positive-evidence rule). The existing local/global maps are untouched — desktop-local and web-client behavior is bit-identical.

Selector-only reads. Components never touch the bucket map or the local maps directly: selectRuntimeAwareSshStatus/TargetLabel/TargetRemoved(state, environmentId | null, targetId) route internally (null = local). For a remote-owned target the status selector returns null (= unknown, show nothing) when the environment is unreachable or its bucket is un-hydrated, so a dead/foreign bucket can never produce a wrong overlay, and the environment's own disconnected UI outranks any SSH overlay.

Events: apply instead of drop. handleRuntimeClientEvent now routes sshStateChanged into the emitting environment's bucket on desktop (web keeps the existing global-store path). An event for a target the bucket doesn't know triggers a forced re-fetch of the authoritative target list instead of trusting the event, so a disconnect racing a target removal can't resurrect it.

Hydration. hydrateRuntimeEnvironmentSshState (single-flight per env, force-coalescing) fetches ssh.listTargets + ssh.listRemovedTargetLabels + per-target ssh.getState over the environment-routed runtime RPC. Triggered from the runtime project refresh scheduler (initial connect + reconnect) and lazily from TerminalPane when it resolves a remote-owned SSH workspace. Hosts without the ssh.* RPC methods (pre-#7767) leave the bucket un-hydrated → reads resolve to unknown, never to destructive "remove workspace" UI.

Staleness on transport loss. Client events emitted during a transport gap are lost, so: (a) the replay tag on the first post-reconnect subscription response (#7827 machinery) downgrades the bucket to un-hydrated + clears states, then force-rehydrates; (b) a reachable→unreachable transition in runtimeStatusByEnvironmentId also downgrades; (c) the selectors additionally gate on reachability.

Write path. TerminalSshReconnectOverlay gets sshOwnerEnvironmentId; when set, Connect routes to ssh.connect on the owning environment's runtime RPC (mirroring the returned state into the bucket) and the failed-connect resync refreshes that environment's target metadata, keeping the sequential targets-first + swallow pattern.

Owner resolution. TerminalPane resolves the owning environment with the existing getExplicitRuntimeEnvironmentIdForWorktree (worktree hostId override → repo executionHostId → never "merely focused runtime"), gated off for paired web windows. Unresolvable repos keep today's behavior (no target id → no overlay).

Lifecycle. Buckets are dropped when an environment is removed (setRuntimeEnvironments retain hook, same pattern as detected-agents).

Invariant: zero cross-pollution. Remote buckets never feed local SSH settings/pickers (those read the local maps as before), and local state is never written by remote events — enforced by tests.

Test evidence

Unit (all passing, vitest --config config/vitest.config.ts):

  • runtime-environment-ssh.test.ts (11): bucket routing, no cross-pollution in both directions, reference stability, empty-list hydration flag, retain/detach lifecycle, staleness downgrade, selector resolution (local vs env vs unreachable vs un-hydrated), removal positive-evidence.
  • runtime-environment-ssh-state.test.ts (11): hydration population/skip/force, old-host failure leaves un-hydrated, removed-labels failure keeps targets, event application (known target direct, unknown target re-fetch, removal race not resurrected), connect routing + state mirroring, resync.
  • TerminalSshReconnectOverlay.test.tsx (+2, 9 total): Connect routed to env RPC (local API untouched), failed remote connect resyncs env not local store; all 7 pre-existing local/web tests unchanged and passing.
  • runtime-client-events.test.ts (+1): replay-tagged response signals resync and still delivers events.
  • useIpcEvents.test.ts (+1, 70 passing), ssh.test.ts, ssh-reconnect-pane-retry, runtime-client-events-sync, runtime-status, remote-server-parity, runtime-rpc-client, FloatingTerminalPanel all green.
  • pnpm typecheck clean, oxlint clean on changed files, check:max-lines-ratchet OK.

Live smoke (two dev instances of this branch on one machine, separate ORCA_DEV_USER_DATA_PATH, CDP 9501/9502; throwaway Ubuntu 22.04 sshd Docker container as SSH target; demo-project cloned in-container from a git bundle because the container has no GitHub auth):

  1. Server: added SSH target smoke-devbox → connected (relay deployed, node-pty compiled on linux-arm64) → added /work/demo-project as remote repo.
  2. Client: paired via getRuntimePairingUrl → runtimeEnvironments.addFromPairingCode; repos fetched with connectionId=ssh-…, executionHostId=runtime:<envId>.
  3. Client bucket hydrated: {labels: {ssh-…: smoke-devbox}, states: {ssh-…: connected}}, local maps 0/0 entries.
  4. Opened the mirrored workspace terminal on the client: no overlay while connected.
  5. Disconnected SSH on the server → client bucket flipped to disconnected via the pushed event and the overlay appeared ("This terminal is waiting for smoke-devbox…") — the exact previously-dead flow.
  6. Clicked Connect on the client → server reconnected (ssh.getState on server: connected; relay node process live in container) → overlay cleared on the client. Local maps still 0/0 throughout.
  7. Cleanup: SSH disconnected, both instances stopped, container and temp key/user-data removed, worktree clean.

Not verified (honest list)

  • Transport-loss staleness (replay-tag downgrade + reachable-diff) is unit-tested but was not exercised live (would need a real tunnel drop mid-session).
  • Ghost-host flow for a remote-owned workspace (target removed on the server → "Remove workspace" on the client) is covered by selector/resync unit tests only; runWorktreeDelete for the remote-owned worktree was not exercised live.
  • Web paired client: covered by the unchanged pre-existing unit tests; no live web-client smoke.
  • Mobile client is untouched (this PR only changes the desktop/web renderer); mobile continues to ignore sshStateChanged as before.
  • Sidebar/worktree-card SSH indicators for remote-owned workspaces still read the local store (pre-existing behavior, out of scope here); only the terminal overlay read/write path is environment-aware.
  • Folder workspaces mirrored from a remote environment resolve their owner via the same explicit-owner helper, but no live folder-workspace smoke was run.

Made with Orca 🐋

…r Remote Orca Server workspaces (STA-1468 desktop topology)

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a new Zustand slice tracking SSH connection state, target labels, and removed-target tombstones per remote runtime environment, along with RPC-backed hydration, connect, and resync helper functions. The terminal SSH reconnect overlay and pane now resolve reconnect status through runtime-aware selectors and an owning environment id, routing connect/resync operations to the remote environment RPC when applicable. IPC event handling and runtime client event subscription are extended to hydrate SSH state on refresh/transport gaps, mark state stale on disconnects, apply SSH state-changed events directly for non-paired windows, and detect subscription replay after reconnect. Corresponding unit tests are added across the new slice, RPC helpers, overlay, and event handling.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: per-environment SSH state for remote desktop clients enabling overlays and Connect.
Description check ✅ Passed It includes a clear summary, design, testing evidence, and notes, though screenshots and explicit AI review/security audit headings are missing.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/renderer/src/runtime/runtime-environment-ssh-state.ts (1)

49-69: 🚀 Performance & Scalability | 🔵 Trivial

Consider fetching per-target connection states in parallel.

fetchEnvironmentSshConnectionStates awaits ssh.getState for each target serially, and each call carries a 15s timeout. On a remote host with several targets this serializes reconnect/hydration latency (worst case N × 15s). Since each fetch is already independently guarded by its own try/catch, running them concurrently preserves the per-target failure semantics while cutting latency.

♻️ Proposed parallelization
-  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.
-    }
-  }
+  await Promise.all(
+    targets.map(async (target) => {
+      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.
+      }
+    })
+  )

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b57e5fab-02d5-4d0f-9625-76a525a44be6

📥 Commits

Reviewing files that changed from the base of the PR and between 6c98835 and b6b859a.

📒 Files selected for processing (16)
  • src/renderer/src/components/terminal-pane/TerminalPane.tsx
  • src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.test.tsx
  • src/renderer/src/components/terminal-pane/TerminalSshReconnectOverlay.tsx
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/runtime/runtime-client-events.test.ts
  • src/renderer/src/runtime/runtime-client-events.ts
  • src/renderer/src/runtime/runtime-environment-ssh-state.test.ts
  • src/renderer/src/runtime/runtime-environment-ssh-state.ts
  • src/renderer/src/store/index.ts
  • src/renderer/src/store/slices/diffComments.test.ts
  • src/renderer/src/store/slices/runtime-environment-ssh.test.ts
  • src/renderer/src/store/slices/runtime-environment-ssh.ts
  • src/renderer/src/store/slices/runtime-status.ts
  • src/renderer/src/store/slices/store-test-helpers.ts
  • src/renderer/src/store/types.ts

@Jinwoo-H
Jinwoo-H merged commit 2b3eba4 into main Jul 8, 2026
2 of 3 checks passed
@AmethystLiang AmethystLiang added the orca-remote-server Remote Orca Server / orca serve / paired remote runtime label Jul 22, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…r Remote Orca Server workspaces (STA-1468 desktop topology) (stablyai#7831)

Co-authored-by: Orca <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

orca-remote-server Remote Orca Server / orca serve / paired remote runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants