Skip to content

fix(runtime): make remote terminal lifecycle host-owned - #9522

Closed
OrcaWin wants to merge 1 commit into
stablyai:mainfrom
OrcaWin:OrcaWin/remote-mirror-lifecycle-ownership
Closed

OrcaWin wants to merge 1 commit into
stablyai:mainfrom
OrcaWin:OrcaWin/remote-mirror-lifecycle-ownership

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Jul 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Make the remote host the sole owner of destructive terminal lifecycle decisions.

A paired renderer is now a mirror: disconnecting, unmounting, switching servers, or observing a stale PTY exit cannot kill the host PTY. An intentional ready-tab close carries an exact generation-bound terminal handle, and main revalidates the PTY/worktree/tab/leaf/generation immediately before committing the durable retirement and tearing down the provider.

This is a fresh replacement design for the lifecycle problem discussed in #8872. It does not modify that contributor branch.

ELI5 user flow

  • You open a terminal running on another Orca runtime.
  • Your local Orca window shows a mirror of that terminal.
  • If the mirror disappears because you disconnect or switch runtimes, the real terminal keeps running.
  • If you intentionally click close, Orca presents the terminal's exact current identity to the host.
  • The host checks that identity again at the last possible moment. It closes only that terminal; a stale mirror, replacement process, pinned tab, or shared sibling is rejected safely.

Design

  • Viewer disconnect/unmount/server-focus changes only prune local mirror state.
  • Explicit ready-tab close uses a generation-bound terminal handle.
  • Main validates exact PTY, worktree, tab, leaf, and lifecycle generation after renderer validation.
  • Durable retirement flushes before provider teardown.
  • Renderer performs only guarded mirror pruning after the host transaction succeeds.
  • Runtime protocol v4 fences destructive old/new client-server skew.
  • Shared PTYs and snapshot-only SSH aliases are protected from unrelated leaf retirement.

Verification

Deterministic checks on the final rebased commit:

  • Runtime/shared: 4 files, 798 tests passed.
  • Renderer/main-window plus adjacent upstream SSH-ownership controls: 8 files, 686 tests passed.
  • Mobile protocol compatibility: 1 file, 2 tests passed.
  • Mobile typecheck and formatting passed.
  • Targeted lint and max-lines ratchet passed.
  • Full desktop typecheck/build passed.
  • git diff --check passed.

Real paired Electron + orca serve validation through the encrypted runtime transport:

  • protocol v4 pairing and real durable remote terminals;
  • disconnect/switch-local preserved host shells and children;
  • reconnect/switch-back restored terminal close controls;
  • explicit close killed only the exact target, preserving its sibling;
  • exact tab/leaf rebind rejected the old handle with terminal_handle_stale;
  • natural PTY exit retired only its exact leaf;
  • pinned close returned terminal_tab_pinned and preserved both process trees;
  • guarded cleanup removed the remaining tabs and PTYs.

After rebasing onto the latest adjacent SSH-ownership change, the exact final artifacts were rebuilt and a publication smoke repeated protocol pairing, live PTY disconnect survival, ready-state reconnect, pinned rejection, and guarded explicit close.

Regression considerations

  • Protocol v4 deliberately rejects destructive version-skew combinations that cannot distinguish automatic lifecycle events from explicit user intent.
  • Terminal tab close now spans renderer validation, main revalidation, durable state, and provider teardown; the tests cover stale generations and validation/commit races.
  • Shared PTY and SSH snapshot aliases must not let one leaf retire another owner; focused ownership tests cover these cases.
  • Windows/WSL paired-runtime verification is requested as an additional platform acceptance pass before merge.

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change raises mobile and runtime protocol compatibility versions to 4. It adds exact terminal layout-leaf and workspace-session retirement, generation-aware PTY handles, stale-close validation, ownership-aware PTY cleanup, persistence rollback, and runtime-owned PTY exit retirement. Close options now propagate through main-process IPC, preload, renderer handlers, and web-runtime terminal actions. Mobile snapshots include unified terminal color and pin state, while tests cover protocol compatibility, terminal ownership, stale bindings, renderer validation, and retirement flows.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers Summary/Design/Verification, but it omits required template sections like Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes. Add the missing template sections, especially a checklist-style Testing section, an AI Review Report, a Security Audit, and Notes/Screenshots as applicable.
Docstring Coverage ⚠️ Warning Docstring coverage is 3.70% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately captures the main change: remote terminal lifecycle ownership moving to the host.
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.

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 (2)
src/shared/workspace-session-terminal-leaf-retirement.ts (1)

22-31: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document why pin protection is bypassed here.

Passing allowPinnedRetirement: true unconditionally overrides the pin guard so a pinned tab is fully closed when its last leaf's PTY exits. This is a deliberate exception to pin protection but isn't explained inline, which makes it easy for a future edit to either "fix" this as a bug or extend the bypass to unsafe call sites.

As per coding guidelines, "When code is driven by a design document or non-obvious constraint, add a brief one- or two-line comment explaining why the behavior is necessary."

📝 Suggested comment
   if (!retirement.layout) {
+    // Why: the retired leaf was the tab's last pane, so there is nothing left
+    // to display — close it even if pinned, since pin protection exists to
+    // preserve visible content, not a dead PTY's empty shell.
     const closed = closeTerminalTabInWorkspaceSession(session, worktreeId, args.parentTabId, {
       allowPinnedRetirement: true
     })

Source: Coding guidelines

src/shared/workspace-session-terminal-leaf-retirement.test.ts (1)

69-95: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the last-leaf/tab-close branch.

Both tests exercise the "leaf survives" and "stale reject" paths, but neither covers retiring the tab's last leaf, which routes through closeTerminalTabInWorkspaceSession(..., { allowPinnedRetirement: true }) and fully removes the tab. This is the branch that intentionally overrides pin protection — worth a dedicated test (including a pinned-tab case) given how central that bypass is to this PR's safety goals.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 9ba28c23-3776-4331-a9c9-ed80d65c7f80

📥 Commits

Reviewing files that changed from the base of the PR and between 49149a0 and d57cf6d988c710f1fecce226f19d03704caeba0e.

📒 Files selected for processing (28)
  • mobile/src/transport/protocol-compat.test.ts
  • mobile/src/transport/protocol-version.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/window/attach-main-window-services.ts
  • src/main/window/terminal-tab-close-request-relay.test.ts
  • src/main/window/terminal-tab-close-request-relay.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.test.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/runtime/sync-runtime-graph.test.ts
  • src/renderer/src/runtime/sync-runtime-graph.ts
  • src/renderer/src/runtime/web-runtime-session.test.ts
  • src/renderer/src/runtime/web-runtime-session.ts
  • src/renderer/src/store/slices/terminal-tab-retirement.ts
  • src/shared/protocol-compat.test.ts
  • src/shared/protocol-version.ts
  • src/shared/terminal-layout-leaf-retirement.test.ts
  • src/shared/terminal-layout-leaf-retirement.ts
  • src/shared/terminal-tab-close.ts
  • src/shared/workspace-session-terminal-leaf-retirement.test.ts
  • src/shared/workspace-session-terminal-leaf-retirement.ts
  • src/shared/workspace-session-terminal-tab-close.ts

Co-authored-by: Orca <help@stably.ai>
@OrcaWin
OrcaWin force-pushed the OrcaWin/remote-mirror-lifecycle-ownership branch from d57cf6d to b39dff7 Compare July 20, 2026 18:49

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b1dad8f4-9aac-4310-ad3d-3e35e8cd9b1b

📥 Commits

Reviewing files that changed from the base of the PR and between d57cf6d988c710f1fecce226f19d03704caeba0e and b39dff7.

📒 Files selected for processing (22)
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/transport/protocol-compat.test.ts
  • mobile/src/transport/protocol-version.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/session-tabs-schemas.ts
  • src/main/runtime/rpc/methods/session-tabs.test.ts
  • src/main/runtime/rpc/methods/session-tabs.ts
  • src/main/window/attach-main-window-services.ts
  • src/main/window/terminal-tab-close-request-relay.test.ts
  • src/main/window/terminal-tab-close-request-relay.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/automations/automation-target-availability.test.ts
  • src/renderer/src/components/sidebar/sidebar-host-options.test.ts
  • src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.focus.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.test.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
🚧 Files skipped from review as they are similar to previous changes (13)
  • src/preload/index.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/preload/api-types.ts
  • mobile/src/transport/protocol-version.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
  • src/main/window/terminal-tab-close-request-relay.ts
  • src/main/window/attach-main-window-services.ts
  • mobile/src/transport/protocol-compat.test.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.test.ts
  • src/main/runtime/orca-runtime.ts

Comment on lines +12 to +37
it('rejects ambiguous legacy closes before they reach the runtime', async () => {
const runtime = {
getRuntimeId: () => 'test-runtime',
closeMobileSessionTab: vi.fn()
} as unknown as OrcaRuntimeService
const dispatcher = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS })

const legacyResponse = await dispatcher.dispatch(
makeRequest('session.tabs.close', {
worktree: 'id:wt-1',
tabId: 'tab-1'
})
)
const explicitResponse = await dispatcher.dispatch(
makeRequest('session.tabs.close', {
worktree: 'id:wt-1',
tabId: 'tab-1',
intent: 'user'
})
)

expect(legacyResponse.ok).toBe(false)
expect(explicitResponse.ok).toBe(true)
expect(runtime.closeMobileSessionTab).toHaveBeenCalledTimes(1)
expect(runtime.closeMobileSessionTab).toHaveBeenCalledWith('id:wt-1', 'tab-1')
})

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.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Test rejection of non-user intent values.

The test covers missing intent and intent: 'user', but not values such as 'mirror'. Add that case and assert the runtime is not called; otherwise a regression to a generic string schema could still pass while allowing ambiguous destructive requests.

Comment on lines +162 to +163
runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION,
minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION

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

Preserve explicit version-skew coverage in this compatibility fixture.

Replacing the previous 3/3 values with the current 4/4 constants turns this case into same-version compatibility. Keep a named legacy-compatible fixture (and add a separate current-version case if needed), otherwise future protocol regressions can pass without testing backward compatibility.

Suggested adjustment
-              runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION,
-              minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION
+              runtimeProtocolVersion: LEGACY_COMPATIBLE_RUNTIME_PROTOCOL_VERSION,
+              minCompatibleRuntimeClientVersion: LEGACY_COMPATIBLE_RUNTIME_CLIENT_VERSION
📝 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
runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION,
minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION
runtimeProtocolVersion: LEGACY_COMPATIBLE_RUNTIME_PROTOCOL_VERSION,
minCompatibleRuntimeClientVersion: LEGACY_COMPATIBLE_RUNTIME_CLIENT_VERSION

@AmethystLiang AmethystLiang added the orca-remote-server Remote Orca Server / orca serve / paired remote runtime label Jul 22, 2026
@AmethystLiang

Copy link
Copy Markdown
Contributor

Related to #9952 (sessions vanishing over remote Orca link).

@OrcaWin

OrcaWin commented Jul 23, 2026

Copy link
Copy Markdown
Collaborator Author

Closing this as superseded by the host-authoritative terminal lifecycle work that has since landed on main in #9687, #9804, and #9994.

The current PR head (b39dff7adb) is now conflicting and duplicates/replaces older versions of that machinery. It also raises the runtime compatibility floor to protocol 4, which is no longer wanted: main keeps the additive lifecycle RPC model at protocol 3 / minimum 2 so older clients and servers retain their previous connectivity.

We reproduced the original destructive flow on pre-fix main with a real encrypted paired client and real serve-runtime PTY. On exact 41751dd90d (#9994), the same live audit passed: renderer disconnect preserved the host PTY and child processes, reconnect restored a stable mirror, and explicit UI close retired exactly the intended PTY. The focused lifecycle suites passed 175/175 and the desktop build passed.

Any remaining generation-bound hardening for explicit user closes should be a small follow-up PR on current main, with an old-host fallback only for method_not_found, rather than reviving this broad implementation.

@OrcaWin OrcaWin closed this Jul 23, 2026
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