Skip to content

fix(browser): scope JavaScript dialogs to their page - #11959

Closed
dgk-dev wants to merge 1 commit into
stablyai:mainfrom
dgk-dev:fix/worktree-scoped-browser-dialogs
Closed

dgk-dev wants to merge 1 commit into
stablyai:mainfrom
dgk-dev:fix/worktree-scoped-browser-dialogs

Conversation

@dgk-dev

@dgk-dev dgk-dev commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Replace Electron's app-global native alert / confirm / prompt sheets for managed browser guests with an overlay rendered inside the originating browser page.
  • Keep Chromium's blocking dialog callback intact, including prompt text, while routing open/close state through the page's existing renderer ownership mapping.
  • Preserve automation: orca dialog accept|dismiss --page ... --worktree ... now resolves an already-pending scoped dialog directly, with the existing agent-browser path retained as fallback.
  • Clean up pending dialogs on CDP resolution, navigation cancellation, guest replacement, and teardown.

Screenshots

The page is dimmed only inside its browser viewport; Orca's worktree and browser chrome remain usable.

Worktree-scoped browser alert

Manual QA also switched to a sibling terminal/browser surface while the alert was pending: the overlay disappeared with its originating page and returned when that page was selected again. CLI acceptance completed in 148 ms without starting an agent-browser process, and the page observed the accepted result.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Focused validation on current origin/main:

  • 189 dialog/controller/BrowserManager/IPC/renderer tests passed.
  • Node and web typechecks passed.
  • Changed files passed oxlint and oxfmt checks.

The full local suite was also exercised. It reached 41,919 passing tests but retained 6 failures in pre-existing PTY/shell-ready suites under a scrubbed test environment; none overlap this change. Re-running the PTY suite against the PR candidate passed all 400 tests, while one existing live-zsh non-ASCII-path case remained environment-sensitive. The dialog-focused suites are green.

AI Review Report

Reviewed the complete main/preload/renderer path and the pinned Electron 43.1.0 implementation. The review specifically checked:

  • preservation of Chromium's blocking callback and prompt value semantics;
  • stale dialog IDs, page ownership, renderer hydration races, guest swaps, teardown, and CDP-driven closure;
  • the existing CLI/AI accept-dismiss flow, including the startup deadlock that occurs if agent-browser is launched behind an already-blocking dialog;
  • accessibility labels, keyboard acceptance/dismissal, bounded long content, localization, and inactive-page behavior.

The review flagged that the initial CLI fallback could block during agent-browser session startup. The implementation now attempts the pending BrowserManager dialog first and keeps agent-browser only as the fallback; regression tests cover both paths.

Cross-platform review covered macOS, Linux, and Windows. The overlay has no platform-specific paths, shell behavior, or modifier labels. Enter/Escape behavior is platform-neutral. The only Electron-specific dependency is the internal -run-dialog event used by the project's pinned Electron version; tests cover listener replacement, restoration, cancellation, and callback behavior.

Security Audit

  • No dependency, auth, secret, filesystem, path, or command-execution changes.
  • Dialog IPC is limited to the trusted browser renderer and verifies page ownership before reading or responding.
  • Responses include a per-dialog UUID so stale renderer actions cannot answer a newer dialog.
  • Page-controlled message/default text and renderer-supplied prompt text are length-bounded; React renders text without HTML injection, and displayed origins use the existing safe origin parser.
  • Teardown dismisses pending callbacks and restores Electron's original listener, avoiding a stranded blocked renderer.

No security follow-up is required.

Notes

Electron does not expose a public JavaScript-dialog interception API. This uses its internal -run-dialog contract, which is explicitly typed by Electron and verified against the pinned runtime. If Electron changes that internal contract during a future upgrade, the controller tests should fail before release.

@dgk-dev
dgk-dev requested a review from brennanb2025 as a code owner August 1, 2026 13:59
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds browser JavaScript dialog support across Electron guests, BrowserManager, IPC, preload APIs, and the renderer. Dialogs are intercepted, normalized, length-limited, tracked, and routed to authorized renderers. The renderer provides alert, confirm, and prompt controls. Automation commands respond directly to pending dialogs before using the existing fallback. Tests cover routing, lifecycle cleanup, cancellation, Unicode-safe truncation, IPC behavior, renderer state, and dialog interactions.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 identifies the main change: scoping JavaScript dialogs to their originating browser page.
Description check ✅ Passed The description covers the user-visible change, screenshots, testing results, AI review, security audit, and platform notes.
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.

Actionable comments posted: 3

🧹 Nitpick comments (7)
src/main/browser/browser-javascript-dialog-controller.test.ts (1)

34-110: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for -cancel-dialogs and for dispose with a pending dialog.

The tests cover interception, CDP resolution, response, and truncation. Two deliberate behaviors stay untested:

  • -cancel-dialogs must call onClosed and must not invoke the Chromium callback.
  • dispose with a pending dialog must invoke the callback with (false, '') so the guest page does not stay blocked.

Both are cheap to assert with the existing createGuest helper.

💚 Proposed tests
it('clears scoped UI when Chromium cancels dialogs', () => {
  const { events, guest } = createGuest()
  const callback = vi.fn()
  const onClosed = vi.fn()
  installBrowserJavaScriptDialogController(guest, { onOpened: vi.fn(), onClosed })

  events.emit('-run-dialog', dialogInfo(), callback)
  events.emit('-cancel-dialogs')

  expect(onClosed).toHaveBeenCalledOnce()
  expect(callback).not.toHaveBeenCalled()
})

it('rejects a pending dialog on dispose', () => {
  const { events, guest } = createGuest()
  const callback = vi.fn()
  const controller = installBrowserJavaScriptDialogController(guest, {
    onOpened: vi.fn(),
    onClosed: vi.fn()
  })

  events.emit('-run-dialog', dialogInfo(), callback)
  controller.dispose()

  expect(callback).toHaveBeenCalledWith(false, '')
})
src/main/browser/browser-manager.ts (1)

1232-1248: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low value

Document that respondToPendingJavaScriptDialog skips renderer ownership validation.

respondToJavaScriptDialog validates rendererWebContentsIdByTabId before delegating. This method performs no such check, so it answers the pending dialog for any page id the caller names. The only current caller is AgentBrowserBridge, which runs in the main process, so the trust boundary holds today. Add a short doc comment so a future IPC handler is not wired to it directly.

♻️ Proposed comment
+  // Why: trusted main-process automation only (agent-browser). Renderer IPC must use
+  // respondToJavaScriptDialog, which validates page ownership first.
   respondToPendingJavaScriptDialog(
src/main/browser/browser-manager.test.ts (1)

179-203: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Add a file:// frame case to cover the only path that forwards a frame URL.

toJavaScriptDialogEvent uses dialog.frameUrl when frameOrigin is file://, and passes it to safeOrigin. This fixture always sends origin: 'https://example.com', so the assertion at Line 203 never exercises that branch. The file:// branch is the one place where a full URL, including its query, reaches the sanitizer. Add a second emission with frame: { origin: 'file://', url: 'file:///tmp/page.html?token=secret' } and assert the forwarded origin contains no query.

src/main/ipc/browser.test.ts (2)

212-237: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive the oversize length from the shared constant.

The test hardcodes 4_097. If BROWSER_JAVASCRIPT_DIALOG_PROMPT_MAX_CHARS changes, this test still passes but no longer exercises the boundary.

♻️ Proposed refactor
-          promptText: 'x'.repeat(4_097)
+          promptText: 'x'.repeat(BROWSER_JAVASCRIPT_DIALOG_PROMPT_MAX_CHARS + 1)

Add the import:

import { BROWSER_JAVASCRIPT_DIALOG_PROMPT_MAX_CHARS } from '../../shared/browser-javascript-dialog'

173-210: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding an authorization negative case.

The tests cover the happy path and the length limit. They do not cover an untrusted sender. A regression that drops the isTrustedBrowserRenderer check in either handler would go undetected. Add a case with a sender whose getType() returns 'webview' and assert null and false.

src/renderer/src/components/browser-pane/use-browser-javascript-dialog.test.tsx (1)

59-90: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider covering the page-id filter branch.

Both tests use page-1 only. The hook ignores opened and closed events whose browserPageId does not match. That branch prevents one worktree pane from rendering another page's dialog, and it is untested. Add a case that emits an event for page-2 and asserts result.current.dialog stays null.

src/renderer/src/components/browser-pane/browser-javascript-dialog-overlay.test.tsx (1)

44-92: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider covering the busy branch.

The overlay ignores Enter and Escape while busy is true and disables both buttons. No test asserts that. A regression that drops the busy guard would allow a duplicate response for the same dialog. Add a case that renders with busy and asserts onRespond is not called after a key press.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b45e5558-fad2-47de-bfcf-70d9d031b57b

📥 Commits

Reviewing files that changed from the base of the PR and between 16c5526 and f2ee24e60f743b29aaedd3f8e834f6f5d9e3e2f7.

📒 Files selected for processing (18)
  • src/main/browser/agent-browser-bridge.test.ts
  • src/main/browser/agent-browser-bridge.ts
  • src/main/browser/browser-javascript-dialog-controller.test.ts
  • src/main/browser/browser-javascript-dialog-controller.ts
  • src/main/browser/browser-manager.test.ts
  • src/main/browser/browser-manager.ts
  • src/main/ipc/browser.test.ts
  • src/main/ipc/browser.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/browser-pane/BrowserPane.tsx
  • src/renderer/src/components/browser-pane/browser-javascript-dialog-overlay.test.tsx
  • src/renderer/src/components/browser-pane/browser-javascript-dialog-overlay.tsx
  • src/renderer/src/components/browser-pane/use-browser-javascript-dialog.test.tsx
  • src/renderer/src/components/browser-pane/use-browser-javascript-dialog.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/browser-javascript-dialog.ts

Comment thread src/renderer/src/i18n/locales/en.json Resolved
@greptile-apps

greptile-apps Bot commented Aug 1, 2026

Copy link
Copy Markdown

Greptile Summary

Replaces Electron's app-global native alert/confirm/prompt sheets for managed browser guests with a React overlay rendered inside the originating browser page's viewport. The implementation intercepts Electron's internal -run-dialog event on each guest WebContents, routes open/close state through BrowserManager's renderer ownership mapping, and preserves Chromium's blocking callback across all resolution paths: user interaction, CDP, CLI automation, navigation, and teardown.

  • browser-javascript-dialog-controller.ts (new): installs a per-guest -run-dialog listener, replaces Electron's native listener, and exposes respond/dispose; CDP coordination is handled via Page.javascriptDialogClosed debugger messages, and original listeners are restored on dispose.
  • browser-manager.ts: integrates the controller into guest lifecycle, forwards open/close events as IPC to the owning renderer, and exposes getJavaScriptDialog / respondToJavaScriptDialog / respondToPendingJavaScriptDialog for IPC and CLI paths.
  • Renderer side: useBrowserJavaScriptDialog hook wires push subscriptions before issuing a hydration query (guarded by an eventRevision counter to discard stale responses), and BrowserJavaScriptDialogOverlay renders the scoped UI with keyboard handling, focus management, and ARIA roles.

Confidence Score: 4/5

Safe to merge; the two findings are edge-case style concerns that do not affect dialog blocking semantics, data integrity, or security boundaries.

The core interception mechanism, callback lifecycle, renderer ownership checks, UUID-gated responses, and teardown path are all implemented correctly and covered by tests. Two minor issues were found: boundDialogText can split a surrogate pair when an emoji spans the truncation boundary, and getJavaScriptDialog carries a redundant state mutation that is surprising in a getter.

Files Needing Attention: browser-javascript-dialog-controller.ts (surrogate-pair truncation) and browser-manager.ts (getJavaScriptDialog side effect).

Important Files Changed

Filename Overview
src/main/browser/browser-javascript-dialog-controller.ts New controller that intercepts Electron's internal -run-dialog event; handles dispose, CDP coordination, and prompt text bounding — but boundDialogText uses UTF-16 length, which can split surrogate pairs at the truncation boundary.
src/main/browser/browser-manager.ts Integrates dialog controller lifecycle into guest registration/cleanup; getJavaScriptDialog carries a hidden state mutation (sets javascriptDialogPageIdByGuestId) that is benign but surprising for a getter.
src/main/ipc/browser.ts Adds two IPC handlers with proper renderer trust checks, ownership verification, and prompt-text length guard before forwarding to BrowserManager.
src/main/browser/agent-browser-bridge.ts Tries BrowserManager-owned dialog first (fast path) before launching agent-browser; fallback is preserved correctly.
src/renderer/src/components/browser-pane/use-browser-javascript-dialog.ts Hook wires IPC subscriptions before issuing the hydration query and uses an eventRevision counter to correctly discard stale query results when an event arrives concurrently.
src/renderer/src/components/browser-pane/browser-javascript-dialog-overlay.tsx New scoped overlay with accessible roles, aria-modal, keyboard handling (Enter/Escape), and focus management; renders inside the browser viewport, not a document-level portal.

Reviews (1): Last reviewed commit: "fix(browser): scope JavaScript dialogs t..." | Re-trigger Greptile

Comment thread src/main/browser/browser-manager.ts Resolved
Harden callback resolution, focus containment, Unicode bounds, IPC authorization, localization, and regression coverage.
@dgk-dev

dgk-dev commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Updated onto current main and addressed all actionable review feedback:

  • guarantee Chromium dialog callbacks resolve even if renderer close notification throws
  • trap focus inside the modal overlay and cover busy keyboard handling
  • bound text by Unicode code point instead of splitting surrogate pairs
  • remove the hidden mutation from the dialog getter and document the trusted automation-only response path
  • add cancellation, disposal, file:// sanitization, untrusted IPC, page-scope, and focus regressions
  • move dialog IPC coverage into a focused test file to stay within the max-lines gate
  • add Spanish, Japanese, Korean, and Chinese catalog entries

Validation on current main: 7 focused test files / 198 tests passed; root typecheck passed; focused oxlint and formatting passed; localization catalog verification passed.

@dgk-dev
dgk-dev force-pushed the fix/worktree-scoped-browser-dialogs branch from f2ee24e to 33bf754 Compare August 4, 2026 05:37

@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 (1)
src/main/browser/browser-javascript-dialog-controller.ts (1)

59-62: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense this implementation comment.

Keep the non-obvious Electron internal-event rationale in one concise line. Do not describe the event flow.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f1785844-a55f-4d6f-af5f-0a76512fbdde

📥 Commits

Reviewing files that changed from the base of the PR and between f2ee24e60f743b29aaedd3f8e834f6f5d9e3e2f7 and 33bf754.

📒 Files selected for processing (6)
  • src/main/browser/agent-browser-bridge.test.ts
  • src/main/browser/agent-browser-bridge.ts
  • src/main/browser/browser-javascript-dialog-controller.test.ts
  • src/main/browser/browser-javascript-dialog-controller.ts
  • src/main/browser/browser-manager.test.ts
  • src/main/browser/browser-manager.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/browser/browser-manager.test.ts
  • src/main/browser/agent-browser-bridge.test.ts
  • src/main/browser/browser-manager.ts
  • src/main/browser/agent-browser-bridge.ts

@Jinwoo-H

Copy link
Copy Markdown
Contributor

Closing this submitted branch and routing the bug to canonical owner issue #17577. We will carry the work ourselves on current main and will not request contributor follow-up. Full contributor credit is preserved for @dgk-dev. No action is requested from you. Thank you.

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.

6 participants