Skip to content

Keep embedded browser commands on the registered Orca target - #9633

Merged
OrcaWin merged 4 commits into
mainfrom
OrcaWin/issue-9510-embedded-browser-routing
Jul 21, 2026
Merged

OrcaWin merged 4 commits into
mainfrom
OrcaWin/issue-9510-embedded-browser-routing

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Jul 21, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • make registered Electron webContents authoritative for embedded browser navigation and evaluation
  • reassert the Orca CDP proxy on every helper-backed command so stale helper sessions cannot launch or control external Chrome
  • fail closed on destroyed targets, stale debugger state, and helper-session cleanup failures

Reproduction

A deterministic fake registers an Orca Electron webContents, initializes the helper, marks its session stale, and records helper calls without --cdp. Before this fix, goto and evaluate each produced one wrong-owner call:

--session orca-tab-tab-1 goto https://embedded.example/next --json
--session orca-tab-tab-1 eval document.title --json

The regression harness now proves both commands remain on the registered embedded target without launching a real browser.

Validation

  • real Electron E2E: create an actual embedded webview, initialize and terminate its real helper daemon, arm an external-launch sentinel, then verify browser.goto and browser.eval update the visible webview without launching the sentinel or recreating the helper
  • browser slice: 28 files, 501 tests
  • bridge suite: 95 tests
  • full TypeScript typecheck
  • touched-file oxlint
  • reliability gates
  • max-lines ratchet
  • git diff --check

Fixes #9510

@coderabbitai

coderabbitai Bot commented Jul 21, 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: 5454c750-8516-4661-9a10-f26d11e6be2f

📥 Commits

Reviewing files that changed from the base of the PR and between 71ffc0c and 6b32a4c.

📒 Files selected for processing (3)
  • src/main/browser/agent-browser-bridge.test.ts
  • src/main/browser/agent-browser-bridge.ts
  • tests/e2e/browser-embedded-owner-routing.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/browser/agent-browser-bridge.ts
  • src/main/browser/agent-browser-bridge.test.ts

📝 Walkthrough

Walkthrough

The bridge now routes goto through WebContents.loadURL() and evaluate through Electron CDP, with URL validation, timeouts, target replacement handling, debugger cleanup, and structured errors. Stale agent-browser ownership failures now reject explicitly, and helper commands consistently include embedded CDP arguments. Browser error types and inline synchronization comments were updated, with expanded tests covering direct commands, lifecycle changes, ownership, and subprocess behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers summary, reproduction, and validation, but omits required screenshots, AI review, security audit, and notes sections. Add the missing template sections: Screenshots, AI Review Report, Security Audit, and Notes, or mark non-applicable items explicitly.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: keeping embedded browser commands on the registered target.
Linked Issues check ✅ Passed The PR implements the #9510 requirements by routing goto/evaluate through the registered webContents and adding regression coverage.
Out of Scope Changes check ✅ Passed The changes stay focused on embedded-browser routing, helper cleanup, tests, and related type/error updates with no clear unrelated scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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 (1)
src/main/browser/agent-browser-bridge.ts (1)

1482-1485: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

String(result.value) collapses object/array eval results to "[object Object]".

With returnByValue: true, result.value is the actual JS value, so expressions returning objects/arrays stringify to "[object Object]" / "a,b" rather than a JSON representation. If the prior agent-browser eval passthrough serialized structured results, this is a behavior regression for non-primitive returns. Consider JSON.stringify for non-primitive values.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 500a7d19-f61e-46b9-a4b6-1e16010552ac

📥 Commits

Reviewing files that changed from the base of the PR and between 6424a73 and dc9eea6.

📒 Files selected for processing (4)
  • src/main/browser/agent-browser-bridge.test.ts
  • src/main/browser/agent-browser-bridge.ts
  • src/main/runtime/orca-runtime-browser.ts
  • src/shared/runtime-types.ts

Comment on lines +782 to +809
await Promise.race([
wc.loadURL(navigationUrl),
new Promise<never>((_resolve, reject) => {
navigationTimeout = setTimeout(
() =>
reject(
new Error(
`Browser navigation timed out after ${EMBEDDED_NAVIGATION_TIMEOUT_MS}ms`
)
),
EMBEDDED_NAVIGATION_TIMEOUT_MS
)
navigationTimeout.unref?.()
})
])
} catch (error) {
if (!this.getWebContents(target.webContentsId)) {
throw this.createPageUnavailableError(`orca-tab-${target.browserPageId}`)
}
throw new BrowserError(
'browser_error',
`Failed to navigate browser page ${target.browserPageId}: ${error instanceof Error ? error.message : String(error)}`
)
} finally {
if (navigationTimeout) {
clearTimeout(navigationTimeout)
}
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Electron webContents loadURL promise rejects ERR_ABORTED redirect download

💡 Result:

The ERR_ABORTED (-3) error when using webContents.loadURL in Electron is often expected behavior rather than a bug, particularly when a navigation is interrupted by a redirect to a downloadable file or another page [1][2][3]. In Chromium, when a requested URL is identified as a download after headers are received, the initial navigation is aborted, which triggers this error [1]. To handle this, you should catch the error on the promise returned by loadURL and ignore it if the error code is ERR_ABORTED [2]. Example implementation: win.webContents.loadURL(url).catch((error) => { if (error.code === 'ERR_ABORTED') { return; // Ignore expected aborts during redirects or downloads } throw error; }); If the abort is caused by a download, Electron will trigger the will-download event on the session [4][5]. You can handle the download logic within that event listener in your main process [4]: win.webContents.session.on('will-download', (event, item, webContents) => { item.setSavePath('/path/to/save/file'); item.once('done', (event, state) => { if (state === 'completed') { console.log('Download successful'); } else { console.log(Download failed: ${state}); } }); }); If you are experiencing this error during redirects that are not intended to be downloads, ensure you are not triggering additional navigations (like history.pushState or location.hash changes) before the initial page has finished loading, as these can also cause the original load request to be aborted [3].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the relevant file and inspect the navigation/reload implementations.
ast-grep outline src/main/browser/agent-browser-bridge.ts --view expanded >/tmp/outline.txt || true
printf '\n--- outline (filtered) ---\n'
sed -n '1,220p' /tmp/outline.txt | sed -n '/goto\|reload\|loadURL\|did-finish-load\|did-fail-load/p' || true

printf '\n--- surrounding lines 730-860 ---\n'
sed -n '730,860p' src/main/browser/agent-browser-bridge.ts

printf '\n--- surrounding lines 1260-1345 ---\n'
sed -n '1260,1345p' src/main/browser/agent-browser-bridge.ts

printf '\n--- search for loadURL usages and ERR_ABORTED handling ---\n'
rg -n "loadURL\\(|ERR_ABORTED|did-finish-load|did-fail-load|will-download|navigationTimeout|Promise\\.race" src/main/browser/agent-browser-bridge.ts

Repository: stablyai/orca

Length of output: 9074


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n--- search for ERR_ABORTED handling across src ---\n'
rg -n "ERR_ABORTED|error\\.code === 'ERR_ABORTED'|code === 'ERR_ABORTED'" src || true

printf '\n--- search for Promise.race patterns with timeouts in src/main/browser/agent-browser-bridge.ts ---\n'
rg -n "Promise\\.race\\(|setTimeout\\(|unref\\(\\)?" src/main/browser/agent-browser-bridge.ts || true

printf '\n--- inspect any other navigation helpers in this file ---\n'
rg -n "did-finish-load|did-fail-load|loadURL\\(|reload\\(|goBack\\(|goForward\\(" src/main/browser/agent-browser-bridge.ts || true

Repository: stablyai/orca

Length of output: 1762


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n--- browser-manager.ts around ERR_ABORTED handling ---\n'
sed -n '780,880p' src/main/browser/browser-manager.ts

printf '\n--- BrowserPane.tsx around the redirect/cancel handling comment ---\n'
sed -n '3870,3925p' src/renderer/src/components/browser-pane/BrowserPane.tsx

printf '\n--- promise.race / unhandled-rejection semantics probe ---\n'
node - <<'JS'
process.on('unhandledRejection', (reason) => {
  console.log('UNHANDLED', reason && reason.message ? reason.message : String(reason));
});

(async () => {
  let rejectLate;
  const slowReject = new Promise((_, reject) => {
    rejectLate = reject;
  });
  const fast = Promise.resolve('ok');

  const raced = Promise.race([fast, slowReject]);
  const result = await raced;
  console.log('race result:', result);

  // Reject after race settled.
  rejectLate(new Error('late failure'));
  await new Promise((r) => setTimeout(r, 50));
  console.log('done');
})();
JS

Repository: stablyai/orca

Length of output: 6852


Handle ERR_ABORTED from loadURL() here

wc.loadURL() can reject on legitimate redirect/download navigations, which will currently be reported as browser_error. Ignore ERR_ABORTED explicitly or switch goto to the event-based pattern used by reload().

@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 (1)
tests/e2e/browser-embedded-owner-routing.spec.ts (1)

13-14: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a "why" comment for the shortened temp root.

shortTempRoot isn't self-explanatory — the reason to avoid os.tmpdir() directly on macOS/Linux is that AF_UNIX socket paths are capped at ~104-108 bytes, and macOS's default tmpdir (/var/folders/.../T/) is often long enough to blow that limit for the helper socket path built from helperSocketDir. As per coding guidelines, **/*.{ts,tsx}: "For non-obvious TypeScript code, add a concise comment explaining why the constraint exists, not how the code works."

📝 Proposed comment
+// Why: AF_UNIX socket paths are capped at ~104-108 bytes on macOS/Linux, and
+// os.tmpdir() (e.g. macOS's /var/folders/.../T/) is often too long once the
+// session id suffix is appended. Use the short system tmp root instead.
 const shortTempRoot =
   process.platform === 'win32' ? os.tmpdir() : path.join(path.parse(os.tmpdir()).root, 'tmp')

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: dbe6a938-1a58-4fe1-bb91-6df3a09c3909

📥 Commits

Reviewing files that changed from the base of the PR and between dc9eea6 and 71ffc0c.

📒 Files selected for processing (1)
  • tests/e2e/browser-embedded-owner-routing.spec.ts

Comment on lines +226 to +231
expect(existsSync(externalLaunchMarker)).toBe(false)
expect(evaluation).toMatchObject({
ok: true,
result: { result: 'destination-webview', origin: server.destinationUrl }
})
expect(existsSync(path.join(helperSocketDir, `${sessionName}.pid`))).toBe(false)

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Pid-file removal check isn't polled like the earlier equivalents.

Lines 157-159 and 190-194 both wrap the same kind of pid-file-existence assertion in expect.poll to tolerate async cleanup timing, but line 231 checks existsSync(...) synchronously right after the eval call. If helper-session cleanup on eval completes slightly after the runtime response resolves, this assertion can flake.

🐛 Proposed fix
-    expect(existsSync(path.join(helperSocketDir, `${sessionName}.pid`))).toBe(false)
+    await expect
+      .poll(() => existsSync(path.join(helperSocketDir, `${sessionName}.pid`)), { timeout: 5_000 })
+      .toBe(false)
📝 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
expect(existsSync(externalLaunchMarker)).toBe(false)
expect(evaluation).toMatchObject({
ok: true,
result: { result: 'destination-webview', origin: server.destinationUrl }
})
expect(existsSync(path.join(helperSocketDir, `${sessionName}.pid`))).toBe(false)
expect(existsSync(externalLaunchMarker)).toBe(false)
expect(evaluation).toMatchObject({
ok: true,
result: { result: 'destination-webview', origin: server.destinationUrl }
})
await expect
.poll(() => existsSync(path.join(helperSocketDir, `${sessionName}.pid`)), { timeout: 5_000 })
.toBe(false)
🧰 Tools
🪛 ast-grep (0.44.1)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFile } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

@OrcaWin
OrcaWin merged commit 085fc6a into main Jul 21, 2026
1 check passed
brennanb2025 added a commit that referenced this pull request Jul 22, 2026
…e load (#9822)

* fix(browser): stop failing goto when a redirect or download aborts the load

Electron's loadURL rejects with ERR_ABORTED (-3) when the initial
navigation is superseded — a client-side/meta redirect (common in SSO
flows) or a download-triggered load. Since #9633 drives goto through
wc.loadURL directly, that rejection surfaced as a spurious
'Failed to navigate' browser_error even though the page landed fine.

Treat ERR_ABORTED like offscreen-browser-backend already does: resolve
with the page's actual URL/title. Every other loadURL failure still
fails closed.

* fix(browser): settle replacement navigation after abort

* fix(browser): clean up aborted navigation destruction race
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…i#9633)

* fix(browser): keep embedded commands on registered target

* fix(browser): cover internal helper ownership paths

* test(browser): cover stale helper routing in Electron

* fix(browser): preserve direct command result semantics

---------

Co-authored-by: OrcaWin <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…e load (stablyai#9822)

* fix(browser): stop failing goto when a redirect or download aborts the load

Electron's loadURL rejects with ERR_ABORTED (-3) when the initial
navigation is superseded — a client-side/meta redirect (common in SSO
flows) or a download-triggered load. Since stablyai#9633 drives goto through
wc.loadURL directly, that rejection surfaced as a spurious
'Failed to navigate' browser_error even though the page landed fine.

Treat ERR_ABORTED like offscreen-browser-backend already does: resolve
with the page's actual URL/title. Every other loadURL failure still
fails closed.

* fix(browser): settle replacement navigation after abort

* fix(browser): clean up aborted navigation destruction race
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]: Embedded browser commands can launch external Chrome instead of controlling the Orca webview

1 participant