Skip to content

fix(terminal): make remote workspace sleep converge - #9874

Merged
OrcaWin merged 2 commits into
mainfrom
OrcaWin/remote-sleep-convergence
Jul 22, 2026
Merged

OrcaWin merged 2 commits into
mainfrom
OrcaWin/remote-sleep-convergence

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Summary

Remote workspace sleep is now host-authoritative and converges on the first successful action for existing and future workspaces. The owner runtime freshly discovers live PTYs, fences concurrent spawns, waits for physical teardown, verifies liveness afterward, and only then lets clients commit sleeping state. Failures roll back/surface through the existing sleep flow, while proven-dead siblings remain reversibly committed for idempotent retry.

Root cause: daemon liveness and renderer/persisted projections could diverge. The old flow depended on client-hydrated PTY IDs, cleared renderer IDs before remote confirmation, swallowed compatibility errors, and used graph-derived fire-and-forget stops. worktree.ps could then count stale leaves/tabs even after fresh terminal.list was empty.

This supersedes #9665 while retaining its correct principle that persisted identifiers are wake hints, not liveness. #9665 fixes the stale status projection; this PR additionally establishes the long-term host discover → stop/wait → verify contract, per-PTY partial outcomes, multi-client dispositions and reconnect snapshots.

No visual change.

Testing

  • pnpm lint — full repository lint not run; touched-file oxlint passed
  • pnpm typecheck — node and web passed after rebasing onto latest main
  • pnpm test — focused contract run: 1,930 passed, 12 skipped; one unrelated existing Windows /tmp path fixture failed (preserves existing badgeColor on runtime createRepo dedupe)
  • pnpm build — the Windows Electron E2E built main, preload, and renderer successfully; standalone command not run
  • Added or updated high-quality regression, transport integration, and Windows E2E coverage

Focused coverage includes: no hydrated client PTY IDs, transient graph/RPC failure, physical stop failure, stale renderer leaves/persisted tabs, partial sibling failure, first-attempt convergence, idempotent retry, legacy runtime fallback, mutation timeout, two clients, late/reconnecting client snapshots, missed dispositions, stale generations, and more than 512 active guards.

Windows Electron E2E (terminal-sleep-wake-restore.spec.ts) passed after one sleep action with:

  • fresh terminal.list.totalCount = 0
  • worktree.ps.liveTerminalCount = 0
  • worktree.ps.hasAttachedPty = false
  • wake restored prior scrollback and accepted fresh terminal input

Encrypted WebSocket integration proves one terminal.sleep reaches the host, two clients observe ordered started/committed state, and a client subscribing after commit receives the authoritative snapshot followed by woken.

Repository setup passed. This PR also repairs Windows native dependency setup so the required setup path does not silently skip the correct platform package.

AI Review Report

Ran seven iterative adversarial review rounds using the installed internal PR-review skill until no valid Critical, Important, or Minor findings remained. Reviews explicitly challenged physical teardown verification, partial failures, mutation fencing, old-runtime deadlines, handle identity, passive-client output suspension, reconnect hydration, missed outcomes, generation ordering, bounded expiry, large workspaces, and macOS/Linux/Windows/SSH/WSL behavior.

Findings led to per-PTY outcomes, passive transport suspension, autonomous rollback expiry, listener-first sleep snapshots, stale-generation tombstones, missed-commit wake reconciliation, and removal of correctness-breaking count eviction. Final verdict: approved with no findings.

Cross-platform review confirmed no platform-specific sleep policy was introduced: authority stays with the selected runtime, path identity uses existing runtime normalization, and the contract is transport/provider-neutral for local, SSH, WSL, macOS, Linux, and Windows hosts.

Security Audit

The new RPC reuses existing paired-runtime authorization and worktree selector resolution. No new shell command construction, secrets, dependencies, provider-specific API, or renderer-trusted liveness input was added. Host mutation fencing and wall-clock deadlines prevent abandoned requests from later killing terminals; subscription snapshots are read-only runtime state scoped to the authenticated connection.

Notes

  • Wake identifiers, daemon history, SSH relay scrollback, browser shutdown, completed-agent hibernation, and local sleep behavior are preserved.
  • Old runtimes fall back only on method_not_found, using repeated fresh discovery/stop under one bounded deadline; real remote errors are surfaced.
  • No physical Mac was available. macOS/Linux/SSH/WSL behavior is covered by the provider-neutral runtime contract and focused tests, while the real E2E evidence is from Windows.
  • Do not merge without explicit authorization.

@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b1130a31-b7ca-4217-bcbd-91ecb37f63e2

📥 Commits

Reviewing files that changed from the base of the PR and between 57b82b4 and eb90e71.

📒 Files selected for processing (1)
  • config/scripts/rebuild-native-deps.test.mjs
🚧 Files skipped from review as they are similar to previous changes (1)
  • config/scripts/rebuild-native-deps.test.mjs

📝 Walkthrough

Walkthrough

The changes add worktree-scoped terminal sleep with serialized PTY teardown, liveness verification, structured results, and replayable client sleep events. Renderer PTY handling now buffers output, defers exits, preserves bindings across reversible stops, and rolls back failed shutdowns. Remote runtimes support modern sleep RPCs with legacy stop-and-convergence fallback. Tests expand coverage for runtime coordination, remote subscriptions, renderer lifecycle handling, and end-to-end sleep/wake convergence. Native dependency rebuilding now targets only modules whose probes fail.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.89% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: remote workspace sleep convergence.
Description check ✅ Passed It includes the main required sections and testing/security details, with only the Screenshots section folded into the no-visual-change summary.
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.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/shared/runtime-types.ts (1)

487-503: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the outcome-dependent type invariant.

The never fields prevent consumers from treating verified and failed teardown outcomes as interchangeable; add a concise Why comment above this union.

Proposed clarification
 } & (
+  // Why: callers may only receive liveness evidence on failed verification;
+  // verified results must not be mistaken for a failure carrying stale evidence.
   | {

As per coding guidelines, “For non-obvious TypeScript code, add a concise comment explaining why the constraint exists.”

Source: Coding guidelines

src/preload/index.ts (1)

1048-1049: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Align the internal listener param type with the widened callback contract.

The callback type now includes preserveRendererBinding?: boolean, but the intermediate listener's data is still typed { id: string; code: number }. It works at runtime (the IPC object carries the field and is forwarded verbatim), but the annotation understates the payload and can mislead future readers.

♻️ Proposed annotation alignment
-      const listener = (_event: Electron.IpcRendererEvent, data: { id: string; code: number }) =>
-        callback(data)
+      const listener = (
+        _event: Electron.IpcRendererEvent,
+        data: { id: string; code: number; preserveRendererBinding?: boolean }
+      ) => callback(data)
src/renderer/src/components/terminal-pane/pty-shutdown-host-generation.ts (1)

24-79: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document that shouldApplyHostSleepPhase records the accepted phase.

The name reads as a pure predicate, but on return true it also mutates hostSleepPhaseByPtyId (Lines 71-76). It's invoked from inside a .filter() in pty-shutdown-exit-deferral.ts, so a reader could reasonably assume it's side-effect free. A one-line comment on the function explaining that it records/advances the accepted generation-phase barrier would prevent misuse.

As per coding guidelines: "For non-obvious TypeScript code, add a concise comment explaining why the constraint exists, not how the code works."

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 8bb59737-20d7-47ca-a493-6fe41d88d297

📥 Commits

Reviewing files that changed from the base of the PR and between e600600 and 57b82b4.

📒 Files selected for processing (37)
  • config/scripts/rebuild-native-deps.mjs
  • config/scripts/rebuild-native-deps.test.mjs
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/remote-runtime-request-connection.integration.test.ts
  • src/main/runtime/rpc/methods/client-events.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/sidebar/sleep-worktree-flow.test.ts
  • src/renderer/src/components/sidebar/sleep-worktree-flow.ts
  • src/renderer/src/components/terminal-pane/TerminalPane.tsx
  • src/renderer/src/components/terminal-pane/pty-connection-types.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-dispatcher.ts
  • src/renderer/src/components/terminal-pane/pty-shutdown-data-suspension.test.ts
  • src/renderer/src/components/terminal-pane/pty-shutdown-data-suspension.ts
  • src/renderer/src/components/terminal-pane/pty-shutdown-exit-deferral.test.ts
  • src/renderer/src/components/terminal-pane/pty-shutdown-exit-deferral.ts
  • src/renderer/src/components/terminal-pane/pty-shutdown-host-generation.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-watcher-registry.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/runtime/remote-worktree-sleep.ts
  • src/renderer/src/runtime/runtime-client-events.test.ts
  • src/renderer/src/runtime/runtime-client-events.ts
  • src/renderer/src/store/slices/store-cascades.test.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/shared/runtime-client-events.ts
  • src/shared/runtime-types.ts
  • tests/e2e/terminal-sleep-wake-restore.spec.ts

Comment on lines +418 to +423
await waitFor(() => reconnectedEvents.some((event) => event.type === 'ready'))
expect(
reconnectedEvents
.filter((event) => event.type === 'worktreeTerminalSleepState')
.map((event) => event.phase)
).toEqual(['committed'])

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that the committed snapshot precedes ready.

The current assertion passes if ready is emitted before the snapshot. Compare their indices so this test protects the listener-first ordering contract.

Proposed assertion
             await waitFor(() => reconnectedEvents.some((event) => event.type === 'ready'))
+            expect(
+              reconnectedEvents.findIndex(
+                (event) =>
+                  event.type === 'worktreeTerminalSleepState' && event.phase === 'committed'
+              )
+            ).toBeLessThan(reconnectedEvents.findIndex((event) => event.type === 'ready'))
             expect(
               reconnectedEvents
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await waitFor(() => reconnectedEvents.some((event) => event.type === 'ready'))
expect(
reconnectedEvents
.filter((event) => event.type === 'worktreeTerminalSleepState')
.map((event) => event.phase)
).toEqual(['committed'])
await waitFor(() => reconnectedEvents.some((event) => event.type === 'ready'))
expect(
reconnectedEvents.findIndex(
(event) =>
event.type === 'worktreeTerminalSleepState' && event.phase === 'committed'
)
).toBeLessThan(reconnectedEvents.findIndex((event) => event.type === 'ready'))
expect(
reconnectedEvents
.filter((event) => event.type === 'worktreeTerminalSleepState')
.map((event) => event.phase)
).toEqual(['committed'])

@OrcaWin
OrcaWin merged commit 300ee19 into main Jul 22, 2026
4 checks passed
@OrcaWin
OrcaWin deleted the OrcaWin/remote-sleep-convergence branch July 22, 2026 07:27
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.

1 participant