Skip to content

fix(ssh): restore relay ownership after app restart - #11860

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/ssh-remote-environment-not-restored-after-login
Aug 1, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/ssh-remote-environment-not-restored-after-login

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Persist the authenticated SSH PTY consumer identity and owner lease so a newly launched Electron main process can reclaim the existing relay session immediately.
  • Encrypt the owner lease through the existing safeStorage persistence pipeline, validate persisted records, and clear them on stale recovery, target removal, or target re-adoption.
  • Keep the relay ownership fence intact: recovery still requires the exact client identity, owner generation, lease, build, authenticated endpoint, and SSH principal.
  • Add a true quit/relaunch E2E that preserves the same PTY, shell PID, background PID, environment token, and working directory inside the former 30-second failure window.

Fixes #11729

Manual Electron reproduction

Reproduced on the then-current main from the issue worktree using an isolated Electron dev profile and CDP, connected over real SSH to Rocky Linux 9.4/aarch64 with Node 20.20.2 and the real stablyai/demo-project repository.

  • A manual disconnect/reconnect succeeded and retained PTY ssh:ssh-1785540514218-6mrb55@@pty-1, shell PID 2415, background PID 2497, token ROCKY_RESTORE_178554, and CWD /tmp.
  • An immediate full Electron quit/relaunch failed: the SSH target remained disconnected, the UI showed “SSH connection required,” the PTY ID became null, and the app reported Remote relay did not grant an authenticated PTY session owner. The remote shell and background processes remained alive.
  • Waiting more than 30 seconds before relaunch succeeded with the same PTY, PIDs, token, and CWD, isolating the regression to immediate ownership recovery after the Electron main process exited.
  • With this fix, an immediate full Electron restart succeeds inside that former 30-second failure window.

The regression test launches two distinct Electron main processes with the same userDataDir; it is not a renderer page.reload. Orca v1.4.162 predates the PTY consumer protocol involved in this current-main regression.

Screenshots

Final commit d411ff24e5, full-window Electron evidence from the passing Docker-backed SSH restart oracle.

Before restart

Before restart: remote shell, background process, environment token, and /tmp cwd

After restart

After restart: the same shell PID, background PID, environment token, and /tmp cwd

The rendered terminal shows the same shell PID 808, background PID 825, token SSH_PROCESS_RESTART_1785546258538, and /tmp working directory before and after the full Electron process restart. The second process also printed SSH_OWNER_RESTORED_1785546268310 through the restored PTY.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — focused Vitest coverage passed: 513 tests across persistence, relay ownership/data delivery, terminal errors, agent hooks, and SSH IPC
  • pnpm build — pnpm build:relay and pnpm exec electron-vite build --mode e2e passed
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed
  • ORCA_E2E_SSH_DOCKER=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/ssh-cold-activation-restore.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 — 2 passed
  • Final d411ff24e5: persistence + consumer-session Vitest — 445 passed
  • Final d411ff24e5: focused Docker SSH full-restart oracle — 1 passed in 35.2s
  • Final d411ff24e5: headful Electron evidence run — 1 passed in 37.4s

AI Review Report

Reviewed the full recovery lifecycle: initial grant, manual detach/reconnect, complete main-process restart, stale lease fallback, relay build mismatch, legacy relay fallback, target deletion/re-adoption, and competing in-process session fencing. The review caught that a legacy-fallback session could otherwise read a retained negotiated owner; active negotiated ownership is now separated from pre-open recovery state.

Cross-platform review covered macOS, Linux, and Windows. Product code adds no platform-specific paths, shell commands, shortcuts, labels, or native dependencies. It uses the existing cross-platform profile store and Electron safeStorage. The Docker E2E intentionally uses POSIX SSH tooling and remains skipped on Windows; persistence and relay unit coverage is platform-neutral. Folder workspaces and git worktrees share the same target-scoped recovery path and neither is assumed by the implementation.

Post-fix same-model review returned CLEAN after commit d411ff24e5, focused regression coverage, lint, typecheck, and relay/recovery suites.

Reliability Gate

  • Invariant / gate: terminal-provider.ssh-remote-reattach-contract. A restarted Electron main process may reclaim only the exact authenticated SSH PTY owner tuple, and must preserve the same PTY, shell, background process, environment, and working directory without waiting for lease expiry.
  • Failure source: SSH remote: environment not restored after login on Rocky Linux 9.4 #11729 and the reproduced immediate-relaunch failure inside the prior 30-second ownership window.
  • Oracle: the two-launch Docker SSH test uses one persisted profile, gracefully closes the first Electron app, starts a distinct second Electron process, asserts the same PTY ID, sends live input, and byte-compares shell PID|background PID|token|cwd before and after restart.
  • Provider/platform coverage: macOS Electron to Linux SSH is covered here; the earlier manual run used Rocky Linux 9.4. Folder workspaces and git worktrees share the same target-scoped recovery path. Platform-neutral unit coverage and Windows packaging pass; a live Windows/WSL restart was not run.
  • Performance budget: recovery adds no polling, provider listing, subprocess fanout, or hot-path scans. Owner grants are length-bounded and perform one main-state durability write only at ownership lifecycle boundaries; the regression test proves zero unrelated GitHub-cache sidecar writes.
  • Diagnostics: existing SSH relay lifecycle logs expose build identity, owner admission, stale recovery, and cleanup; malformed persisted or granted leases fail closed.
  • Residual gaps: the final post-review live rerun used the Linux Docker fixture rather than another Rocky host, and no live Windows/WSL restart was exercised.

Security Audit

The owner lease is a bearer recovery secret, so it is main-owned, size/type validated on load, encrypted when safeStorage is available, and never added to renderer settings APIs. Recovery does not weaken server admission or promote subscribers: the relay still verifies the exact client ID, generation, lease, authenticated endpoint credential, and SSH principal. Conditional cleanup prevents an obsolete local session from deleting a newer owner's durable record.

No new IPC methods, network endpoints, command execution paths, dependencies, or user-controlled filesystem paths were added. Existing secure profile-file handling remains the fallback protection on platforms where OS encryption is unavailable.

Notes

The PTY consumer protocol was introduced after Orca 1.4.162. This fixes the current-main full-restart failure reproduced under the issue scenario; users on 1.4.162 need to upgrade to receive it.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@brennanb2025, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 1 minute

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3011071f-b7c3-4857-bc72-f55ce2c5c3be

📥 Commits

Reviewing files that changed from the base of the PR and between 5738d61 and d411ff2.

📒 Files selected for processing (15)
  • src/main/ipc/ssh.test.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/ssh/ssh-pty-consumer-recovery.ts
  • src/main/ssh/ssh-pty-consumer-session.test.ts
  • src/main/ssh/ssh-pty-consumer-session.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/main/ssh/ssh-relay-session-data-delivery.test.ts
  • src/main/ssh/ssh-relay-session-terminal-error.test.ts
  • src/main/ssh/ssh-relay-session-test-fixtures.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/shared/constants.ts
  • src/shared/ssh-types.ts
  • src/shared/types.ts
  • tests/e2e/ssh-cold-activation-restore.spec.ts

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.

@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a full Electron restart regression where the SSH PTY consumer could not reclaim relay ownership within the 30-second session window. The fix persists the authenticated PTY consumer identity, owner generation, and owner lease through the existing safeStorage encryption pipeline, so a freshly launched main process can reload and resume the relay session immediately.

  • ssh-pty-consumer-recovery.ts (new module): extracts and extends the in-memory recovery map from ssh-relay-session.ts to additionally read from and write to the persistence store, enabling cross-process handoff of the clientInstanceId and ownerLease.
  • persistence.ts: adds upsertSshPtyConsumerRecovery / removeSshPtyConsumerRecovery / getSshPtyConsumerRecovery, a two-pass load normalizer (pre- and post-decryption), and flushOrThrow on each write so the lease is durable before relay negotiation continues; also clears recovery records on target deletion and re-adoption.
  • ssh-relay-session.ts: splits negotiatedPtyConsumerOwner() into activePtyConsumerOwner() (in-session only) and recoverablePtyConsumerOwner() (in-session + persisted pre-open), now requiring a matching serverBuildId for recovery; E2E test validates the full quit/relaunch lifecycle.

Confidence Score: 5/5

Safe to merge — the recovery path is well-fenced and cannot promote a subscriber to owner or weaken relay admission

The change adds a narrow, well-bounded persistence path (encrypt on write, two-pass validate+decrypt on load, flush synchronously) with no new IPC surface, no new network endpoints, and no user-controlled file paths. Relay admission still requires the exact client identity, owner generation, lease, serverBuildId, and SSH principal. The stale-recovery branch correctly clears the persisted record before retrying fresh. All three new persistence tests, the wire-boundary lease-length test, and the quit/relaunch E2E test exercise the critical paths.

Files Needing Attention: No files require special attention

Important Files Changed

Filename Overview
src/main/ssh/ssh-pty-consumer-recovery.ts New module cleanly encapsulates in-memory + persisted recovery state; clientInstanceId guards on all mutating functions prevent cross-session interference; checkpoints/migrations are correctly preserved via in-place mutation of the existing record rather than replacement
src/main/persistence.ts Two-pass load pipeline (pre-decryption 4096-char bound, then post-decryption 512-char bound) is correct and tested; flushOrThrow on upsert/remove ensures durability; removeSshTarget now correctly short-circuits when neither targets nor recoveries changed
src/main/ssh/ssh-relay-session.ts Split of negotiatedPtyConsumerOwner into activePtyConsumerOwner + recoverablePtyConsumerOwner correctly restricts legacy-fallback sessions from consuming persisted owner state; the new tighter serverBuildId guard is a deliberate hardening
src/shared/ssh-types.ts New SshPtyConsumerRecovery type is minimal and correct; outputFlowControl is optional to handle older relay sessions
src/main/persistence.test.ts Three new tests cover durable encryption round-trip, post-decrypt size rejection, and recovery cleanup on target removal
src/main/ssh/ssh-relay-session-data-delivery.test.ts New test exercises the full persisted-record recovery path including correct clientInstanceId propagation, upsert after negotiation, and removal on dispose
tests/e2e/ssh-cold-activation-restore.spec.ts New E2E test correctly launches two distinct Electron processes sharing the same userDataDir, validates PTY ID, shell PID, background PID, env token, and CWD are preserved
src/main/ssh/ssh-pty-consumer-session.ts Added ownerLease.length > 512 guard to validateGrant so relay-granted leases exceeding the persistence bound are rejected at the wire boundary
src/shared/types.ts sshPtyConsumerRecoveries added as optional array to PersistedState with a comment noting it must not be exposed through renderer settings APIs

Sequence Diagram

sequenceDiagram
    participant E1 as Electron Process 1
    participant R as SSH Relay
    participant S as Store (safeStorage)
    participant E2 as Electron Process 2

    E1->>R: "pty.openClient (clientInstanceId, requestedRole=session-owner)"
    R-->>E1: grant (ownerGeneration, ownerLease, serverBuildId)
    E1->>S: upsertSshPtyConsumerRecovery (encrypted ownerLease)
    Note over S: flushOrThrow() — durable before relay continues

    Note over E1,R: Session active (PTY, shell PID, env token, CWD alive on relay)
    E1->>E1: App quit (dispose → forgetSshPtyConsumerRecovery → removeSshPtyConsumerRecovery)
    Note over S: Record removed on clean dispose (kept on detach for reconnect)

    alt Restart within 30s window (relay still holds session)
        E2->>S: claimSshPtyConsumerRecovery → getSshPtyConsumerRecovery
        S-->>E2: persisted record (clientInstanceId, ownerLease, serverBuildId)
        E2->>R: "pty.openClient (same clientInstanceId, resume={ownerGeneration, ownerLease})"
        R-->>E2: grant (same PTY, same shell PID, env, CWD)
        E2->>S: upsertSshPtyConsumerRecovery (new encrypted ownerLease)
    else Resume fails (stale lease / build mismatch)
        E2->>S: removeSshPtyConsumerOwnerRecovery (clear stale record)
        E2->>R: pty.openClient (fresh session, no resume)
        R-->>E2: new grant
    end
Loading

Reviews (2): Last reviewed commit: "fix(ssh): bound durable owner recovery" | Re-trigger Greptile

Comment thread src/main/persistence.ts Resolved
@brennanb2025
brennanb2025 merged commit ed00ab0 into main Aug 1, 2026
45 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SSH remote: environment not restored after login on Rocky Linux 9.4

1 participant