Skip to content

fix(browser): switch client-hosted profiles by staging the replacement guest - #30452

Merged
nwparker merged 13 commits into
mainfrom
nwparker/browser-profile-switch-guest
Oct 19, 2026
Merged

nwparker merged 13 commits into
mainfrom
nwparker/browser-profile-switch-guest

Conversation

@nwparker

@nwparker nwparker commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1342 $\color{#cf222e}{\Huge{\mathbf{−}}}$​10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1332
Prod 51 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​966 $\color{#cf222e}{\Huge{\mathbf{−}}}$​170 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​796

ELI5

In a paired remote workspace whose browser runs on this computer, asking to move a browser tab into another session profile (its own cookie jar) could not be done safely. This lets the tab switch profiles by building the new page first and only throwing the old one away once the new one is working.

What Changed

Before: browser.tabSetProfile on a page hosted by the desktop for a paired remote workspace sent the request to the server's own window, which does not hold that page. It either did nothing while reporting success (an isolated page asked to go back to the default profile was answered "already default" from the wrong registry) or failed against a renderer that is not there. There was no safe way to replace the live guest: closing it first would lose the logged-in page if the replacement then failed.

After: the switch reaches the desktop that actually hosts the page, and the page keeps its identity (same page id, same workspace, same URL) while moving to the new profile's cookie jar. If anything goes wrong, the original page stays open and usable.

How it works:

  • Negotiated before anything changes. The desktop advertises profile-switch-v1. The server checks it, plus the page's lease generation, before touching any state. Older desktops get a clean "unsupported" error and nothing is mutated.
  • Staged replacement. The server reserves the next page generation and sends one switchProfile command. The desktop builds the replacement guest in its own partition (derived on the desktop from the profile id; only id, label and scope cross the wire, never a partition name), binds it, reloads the current URL, and only then publishes it and retires the old guest. Failure at any step tears down only the staged guest and rebinds the original.
  • Server-owned profiles survive recovery. Profiles live on the server, which the desktop does not know about. createPage and restorePage now carry the same optional profile metadata to desktops that advertise the capability, so a page that was switched can still be restored after a guest crash or a reconnect.
  • Edge cases covered: a connection fence during the switch also stops the staged guest; a replacement that dies before commit is rolled back; an original guest that dies during a failed switch is reported so normal recovery runs; a switch that times out keeps the original placement and reservation until the desktop answers (late failure keeps the old page; late success is adopted and the tab record updated); the execution-host grant and the replaced generation's download transfers are released when the old page is gone; a download the replacement starts while loading is accepted under its reserved generation; folder workspaces resolve through the client-page catalog instead of the server-local worktree resolver.

This is the runtime operation only. It does not add a toolbar profile picker.

  • The network execution-host schema moved to src/shared/browser-network-execution-host.ts (to keep the protocol file under the line limit); every importer imports it from there directly.

Why

Keeping the old guest until the new one is bound is the only order that never leaves the user with a dead page or two live ones. The alternatives were "close then create" (loses the page and its session if creation fails, which is what the issue describes) or switching the existing guest's session in place (Electron cannot change a live webview's partition). Carrying profile metadata on the existing page commands, behind the same capability, reuses the creation and restore paths rather than adding a second profile catalog on the desktop.

Mixed versions: new server with an old desktop never sends switchProfile or the optional profile field (both gated on profile-switch-v1). A new desktop with an old server receives neither and keeps its existing local-profile validation. The new command type only travels inside the existing command event after negotiation.

This builds on #30351 by @oliver-mee, which proposed the staged-replacement design and the first version of this code; that commit keeps its original author. The follow-up commits address review findings on fencing, recovery, timeouts and downloads.

Linked Issue

Fixes #30350

Visual Proof

N/A: this changes a runtime command and the browser guest lifecycle, not any UI.

Testing

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • Reproduced on main: browser-profiles-client-placement.test.ts fails 7/7 against main's browser-profiles.ts (main answers from the server's own window or reports a false "already in that profile").

  • New and updated unit tests cover negotiation and rejection of old desktops, staged replacement in both directions, rollback on preparation, binding, navigation and abort failures, fencing during the switch, a dead replacement, a lost original guest, timeouts with late success and late failure, grant release, generation-scoped download release, staged download admission, metadata on create/restore, and folder-workspace targets. Each fix's test was confirmed failing without its fix.

  • Paired Electron end-to-end (tests/e2e/paired-client-hosted-profile-cookies.spec.ts, hidden windows via ORCA_BACKGROUND_LAUNCH=1) passed locally on macOS: it switches default → isolated → default → isolated on a live client-hosted page and checks each native cookie jar keeps its own value.

  • Unit folders around the change (src/main/browser, src/main/runtime/browser-host, src/main/runtime/browser, src/main/runtime/rpc/methods, src/shared, browser-pane renderer tests) pass single-worker; typecheck and the full static-analysis job pass locally.

  • Not verified: Windows or Linux live runs, an SSH-hosted remote server, or an installed build.

Review

Please look closest at browser-client-page-profile-switch.ts (desktop staging and rollback order), browser-host-client-profile-switch.ts (server reservation, timeout and late-result handling), and the file-channel admission of a pending switch in browser-host-client-page-connection.ts.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Security: the desktop never accepts a partition name from the server; it derives the partition from the authority, execution host and profile id, so a server cannot point a page at the desktop's own cookie jars. File transfers under a reserved generation are admitted only for the same page, lease and connection while that page's switch is pending.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

oliver-mee and others added 12 commits October 18, 2026 16:50
…ry host profile metadata

- A fence during automation retirement now revokes and stops the staged guest.
- A failed or late-settling switch releases its execution-host grant so the page can be recreated.
- Staging cleanup failures before handover stay visible to executor close.
- createPage/restorePage carry host-owned profile metadata to profile-switch-v1 desktops,
  so recovery and restore can rebuild a switched page.
@coderabbitai

coderabbitai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

The change adds negotiated profile switching for client-hosted browser pages. The host sends validated profile metadata and a switch command. The client prepares and binds a replacement guest while retaining the current guest until commit. The host updates the page placement and generation after success. The change also adds generation-aware download cleanup and tests for switch failures, recovery, and profile isolation.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🔵 Low · up to 7bbb2

Profile switching remains usable, but uncommon failure paths can leave stale switch state. Address the retirement cleanup and late-publication race before relying on recovery behavior.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 13.64% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 44 functions across 63 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed The PR meets the coding requirements in #30350. It negotiates profile-switch-v1 and checks the lease generation before mutation. It validates profile metadata, stages a replacement in a desktop-deri…
Out of Scope Changes check Passed The changes remain within #30350. Protocol schemas, create and restore metadata, generation fencing, recovery, download admission, cleanup, and import relocation support safe client-hosted profile rep…
Title check Passed The title clearly and concisely describes the primary change: staging a replacement guest to switch profiles for client-hosted browser pages.
Description check Passed The description is complete and follows the required template. It explains the user impact, implementation, rationale, linked issue, testing, limitations, compatibility, security, and checklist status…
Full details: Linked Issues check

Explanation

The PR meets the coding requirements in #30350. It negotiates profile-switch-v1 and checks the lease generation before mutation. It validates profile metadata, stages a replacement in a desktop-derived partition, and retains the original guest until preparation, binding, and navigation succeed. It restores or preserves the original on failure and rejects unsupported desktops before mutation. Unit tests and the paired Electron test cover these requirements and recovery paths.

Full details: Out of Scope Changes check

Explanation

The changes remain within #30350. Protocol schemas, create and restore metadata, generation fencing, recovery, download admission, cleanup, and import relocation support safe client-hosted profile replacement. The PR adds no toolbar picker, cookie-file import, or annotation controls. No unrelated change is demonstrated.

Full details: Description check

Explanation

The description is complete and follows the required template. It explains the user impact, implementation, rationale, linked issue, testing, limitations, compatibility, security, and checklist status.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@nwparker
nwparker force-pushed the nwparker/browser-profile-switch-guest branch from 4e746f6 to 7bbb24d Compare October 19, 2026 00:18

@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


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6f8ae0eb-6123-4fe9-9280-d7ea3098a686
📥 Commits

Reviewing files that changed from the base of the PR and between 4e746f6 and 7bbb24d.

📒 Files selected for processing: 20
  • src/main/browser/browser-client-network-route-registry.ts
  • src/main/browser/browser-client-route-cookie-import-partition-parity.test.ts
  • src/main/browser/browser-execution-host-storage-identity.ts
  • src/main/browser/browser-network-execution-route.ts
  • src/main/browser/browser-route-partition-stability.test.ts
  • src/main/browser/paired-runtime-browser-network-route.test.ts
  • src/main/browser/paired-runtime-browser-network-route.ts
  • src/main/browser/paired-runtime-browser-network-transport.ts
  • src/main/runtime/browser-host/browser-host-client-profile-switch.test.ts
  • src/main/runtime/browser-host/browser-host-client-profile-switch.ts
  • src/main/runtime/browser-host/browser-host-lease-registry.ts
  • src/main/runtime/browser-host/browser-host-profile-switch-recovery.test.ts
  • src/main/runtime/browser/browser-command-contracts.ts
  • src/main/runtime/browser/browser-profiles-client-placement.test.ts
  • src/main/runtime/browser/browser-profiles.ts
  • src/main/runtime/runtime-browser-client-page-creation.ts
  • src/main/runtime/runtime-browser-network-execution-host.ts
  • src/main/runtime/terminal/driver/terminal-driver-resources.ts
  • src/main/runtime/terminal/launch/terminal-workspace-scope.ts
  • src/shared/browser-client-host-protocol.ts
💤 Files with no reviewable changes: 1
  • src/shared/browser-client-host-protocol.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Comment on lines +72 to +78
const retirePlacement = () => {
if (input.placements.getPlacement(authority.browserPageId) === expected) {
input.placements.completePageRetirement(
input.placements.beginPageRetirement(authority.browserPageId, expected)
)
}
}

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C12 'export function completeBrowserHostPageRetirement' src/main/runtime/browser-host

Repository: stablyai/orca

Length of output: 2658


🏁 Script executed:

set -eu
printf '%s\n' '--- switch implementation ---'
nl -ba src/main/runtime/browser-host/browser-host-client-profile-switch.ts | sed -n '1,180p'
printf '%s\n' '--- retirement completion wrapper ---'
nl -ba src/main/runtime/browser-host/browser-host-page-retirement-completion.ts | sed -n '1,120p'
printf '%s\n' '--- lease registry retirement bindings ---'
rg -n -F --glob '*.ts' -e 'completePageRetirement(' -e 'beginPageRetirement(' -e 'onClientPageReleased' src/main/runtime/browser-host
printf '%s\n' '--- lease registry declaration and relevant implementation ---'
rg -n -F --glob '*.ts' 'class BrowserHostLeaseRegistry' src/main/runtime/browser-host

Repository: stablyai/orca

Length of output: 23006


🏁 Script executed:

set -eu
printf '%s\n' '--- lease registry retirement and switch wiring ---'
nl -ba src/main/runtime/browser-host/browser-host-lease-registry.ts | sed -n '200,350p'
nl -ba src/main/runtime/browser-host/browser-host-lease-registry-instance.ts | sed -n '1,100p'
rg -n -F --glob '*.ts' -e 'switchBrowserHostClientProfile(' -e 'onLateCommit' -e 'onCommitted' src/main/runtime/browser-host src/main/runtime
printf '%s\n' '--- grant and transfer cleanup definitions ---'
rg -n -F --glob '*.ts' -e 'interface BrowserClientPageExecutionHostGrant' -e 'type BrowserClientPageExecutionHostGrant' -e 'class BrowserClientPageExecutionHostGrant' -e 'release()' src/main/runtime/browser-host
nl -ba src/main/runtime/browser-host/browser-host-client-page-creation.ts | sed -n '1,240p'
nl -ba src/main/runtime/browser-host/browser-host-lease-download-transfer-cleanup.test.ts | sed -n '1,130p'

Repository: stablyai/orca

Length of output: 27230


Route switched-page retirement through BrowserHostLeaseRegistry.

retirePlacement bypasses command-ledger retirement and onClientPageReleased, which releases staged download transfers. Its local releaseGrant only handles the grant, so pass a retirement callback from BrowserHostLeaseRegistry and remove the duplicate grant cleanup.

🐛 Suggested fix
diff --git a/src/main/runtime/browser-host/browser-host-client-profile-switch.ts b/src/main/runtime/browser-host/browser-host-client-profile-switch.ts
@@
     registry: Pick<BrowserHostLeaseRegistry, 'requireClientPage' | 'select'>
+    retirePage: (
+      browserPageId: string,
+      expected: RuntimeBrowserClientPlacement
+    ) => void
@@
   const retirePlacement = () => {
     if (input.placements.getPlacement(authority.browserPageId) === expected) {
-      input.placements.completePageRetirement(
-        input.placements.beginPageRetirement(authority.browserPageId, expected)
-      )
+      input.retirePage(authority.browserPageId, expected)
     }
   }
-  // Why: a held grant blocks recreating the page once its placement is retired.
-  const releaseGrant = () => {
-    if (input.grants.get(authority.browserPageId) === grant) {
-      input.grants.delete(authority.browserPageId)
-      grant.release()
-    }
-  }
@@
     retirePlacement()
     closeSettledReplacement()
-    releaseGrant()
@@
             input.placements.cancelClientPageReservation(reservation)
             retirePlacement()
-            releaseGrant()
           }
diff --git a/src/main/runtime/browser-host/browser-host-lease-registry.ts b/src/main/runtime/browser-host/browser-host-lease-registry.ts
@@
       placements: this.pagePlacements,
       grants: this.clientPageExecutionHostGrants,
+      retirePage: (browserPageId, expected) =>
+        this.completePageRetirement(this.beginPageRetirement(browserPageId, expected)),
       onCommitted: this.options.onClientPageReleased

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.

[Bug]: Client-hosted browser profile switching cannot safely replace a live guest

2 participants