Skip to content

fix(browser): stop agent browser input from stealing the user's focus - #11732

Closed
songminsns wants to merge 6 commits into
stablyai:mainfrom
songminsns:fix/agent-browser-input-steals-user-focus
Closed

songminsns wants to merge 6 commits into
stablyai:mainfrom
songminsns:fix/agent-browser-input-steals-user-focus

Conversation

@songminsns

@songminsns songminsns commented Jul 31, 2026 •

Copy link
Copy Markdown

The problem

While an agent drives the built-in browser, its keystrokes land in whatever the user is typing into.

CDP input only reaches an Electron <webview> guest while that guest holds native DOM focus. Without it Chromium routes the event to whichever surface actually has focus — the user's terminal — and the CDP call still resolves ok, so the agent never learns its input went somewhere else. It retries, and the user's prompt fills with fragments of the agent's typing.

The same root cause shows up as focus theft: mousePressed moves focus onto the guest and nothing gives it back, so the user's cursor silently jumps out of the terminal they were working in.

Why main can't fix it

webContents.focus() is a no-op for a <webview> guest — the guest is a DOM element owned by the host renderer, so only the renderer can focus it. Confirmed by measurement: text reached the page only when a human physically clicked into it. Page.bringToFront, tab switch --focus, and bringing the app to the foreground all failed to make input land.

The fix

Route the focus handoff through the host renderer.

main (cdp-ws-proxy)                renderer (BrowserPane)
──────────────────────────────────────────────────────────
input command detected
  → 'begin' + guestId ───────────→ save document.activeElement
                                    focusWebviewNow()
  ← granted / refused ───────────  did the guest actually take focus?
  forward CDP input ─────────────→ guest holds focus → input lands
  → 'end' ───────────────────────→ restore the saved element

Main cannot see whether the guest took focus — only the pane hosting it can — so the pane answers the borrow and main acts on the answer:

  • granted → forward the input.
  • refused → fail the command. A guest can refuse focus while staying perfectly alive: a hidden or detached pane still answers CDP, so forwarding would put the keystroke back in whatever the user is typing into. Failing is what lets the agent learn its input did not land, instead of getting the ok that hid this bug in the first place.
  • silence → fail it too. The host renderer accepted the announcement, so no answer means no pane is holding this guest — it is mounting, unmounting, or being swapped out — and none of those can take focus. The wait is bounded at 250 ms, which is slack for a busy renderer rather than an expected pause; a mounted pane answers immediately and never reaches it.

Only a guest with no host renderer at all — offscreen, headless — skips the borrow and forwards straight through, exactly as it did before this handoff existed.

Scope is deliberately narrow:

  • Input.insertText / Input.dispatchKeyEvent always borrow — key events reach nothing without focus.
  • Input.dispatchMouseEvent borrows only for mousePressed. Moves, wheels and releases never take focus, so borrowing for them would create the very focus hop this prevents.
  • Runtime.evaluate, screenshots, and read-only traffic are untouched.

The renderer listener is intentionally not gated on the pane being active. Agents drive background tabs while the user works elsewhere — that is exactly when the leak happened. Panes filter by guest webContents id so only the addressed one reacts.

Also included: orca tab create never sent activate, even though TabCreate documents "User-initiated opens focus the tab; agent/automation opens stay background." Every agent-created tab surfaced the browser pane and took focus. It now mirrors tab switch — --focus is opt-in.

How this was verified

Measured per command by focusing a probe input in the page, firing the command, then reading the field back. A command is "leaking" when the field stays empty and the text appears in the user's terminal instead.

Command Before After
inserttext / type / keypress leaked into the user's terminal lands in the page
mouse down / up, click stole focus, never returned focus returns to the user
tab create surfaced the pane, took focus stays in the background
eval, screenshot, mouse move already fine unchanged
snapshot, set device, goto, tab switch, tab close already fine unchanged

Every command an agent session had actually issued was measured, not just the suspected ones — the innocent ones were confirmed innocent so the fix could stay minimal.

Reproduced in the failing configuration — browser as a background tab while the user typed in a floating terminal — before and after. Focus stayed with the user and the input reached the page.

The refused-focus case is covered by tests rather than by hand: it needs a guest that stays alive while its pane cannot hold focus, which the suites drive directly through the borrow reply.

No visual change

This changes focus behavior only. No UI is added, removed, or restyled, so there are no screenshots to attach.

Tests

cdp-ws-proxy suites updated and extended: the mock now carries a host renderer that answers borrows the way a mounted pane does, and the input paths assert the borrow is announced (ui:browserAgentInput / begin) instead of the old native webContents.focus().

cdp-ws-proxy-focus-borrow.test.ts covers what main does with each answer — forwards on a grant, fails the command on a refusal (key events and Input.insertText both), fails on silence, and skips the ask entirely when the guest has no host renderer. browser-focus.test.ts covers the pane side: a failed focus is reported as such, and still unwinds its borrow so later restores are not swallowed.

980 tests pass across src/main/browser, src/renderer/src/components/browser-pane and src/cli/browser.test.ts, on top of the current main.

Code review summary

  • Cross-platform — No platform branches. hostWebContents, send, and DOM focus are Electron/DOM APIs available on macOS, Linux, and Windows. Verified on macOS; the logic contains nothing OS-specific.
  • SSH / remote / local — Remote panes stream a viewport instead of hosting a local <webview>, so they never take this path; the web preload API gets a no-op stub for both directions. Offscreen/headless guests have no host renderer, so they skip the borrow entirely rather than waiting on an answer that cannot come.
  • Agents / integrations — Only the agent-browser CDP path is affected. No agent, git provider, or integration-specific behavior is touched.
  • Performance — Input now waits for the pane's answer instead of a fixed frame, so the common path got faster: the old 16 ms per key event and per mouse press is gone. A guest whose pane never answers pays the 250 ms bound before failing, and one with no host renderer pays nothing. Wait-polling and read-only probes (Runtime.evaluate, screenshots, mouse moves) are untouched.
  • UI quality — No visual change. Focus visibly returns to where the user left it rather than parking on the browser pane.
  • Security — The IPC carries a phase string, a numeric guest id and a numeric borrow id outbound, and a borrow id plus a boolean inbound. No new privilege, no page content, no user data crosses the boundary.

Testing notes

  • Verified on macOS with a local worktree and the desktop <webview> path.
  • Remote/SSH and headless paths are covered by construction (stub + skipped borrow) but were not exercised on real remote hosts.
  • Rebased onto current main (54a9b58). browser-pane/ was refactored substantially in the meantime; there were no textual conflicts and the suites above pass on top of it.

X: @songminsns63384

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes two related focus bugs in the agent browser: CDP input events leaking into the user's terminal because the <webview> guest lacked native focus, and tab create always surfacing the browser pane and stealing the user's cursor. The fix routes focus handoff through the host renderer via IPC (ui:browserAgentInput begin/end), adds a depth counter in createAgentInputFocusBorrow to handle the overlapping begin/end pairs produced by keyDown/keyPress/keyUp triplets, and makes tab create default to activate:false.

  • cdp-ws-proxy.ts: notifyAgentInput sends begin/end over IPC to the host renderer; withBorrowedFocus waits one animation frame after begin so the renderer can move DOM focus before the CDP command fires; the finally-block ensures end is always sent even on error.
  • browser-focus.ts / BrowserPane.tsx: createAgentInputFocusBorrow tracks borrow depth so only the outermost begin captures document.activeElement and only the outermost end restores it; the renderer effect filters by guest webContentsId to prevent cross-pane interference.
  • browser-tab.ts: tab create now sends activate: flags.has('focus'), matching tab switch opt-in semantics; tests and CLI spec updated accordingly.

Confidence Score: 5/5

Safe to merge — the changes are narrowly scoped to CDP input paths and tab activation, the depth-counter approach correctly handles overlapping borrow pairs, and the IPC message carries only a phase string and numeric guest id.

The fix replaces a simple one-liner (webContents.focus()) with a renderer-mediated borrow/restore cycle, and the implementation handles the important edge cases: overlapping begin/end from keyDown/keyPress/keyUp triplets (depth counter), unmatched ends on fresh listener mounts (Math.max guard), destroyed host renderer (isDestroyed check + empty catch), and cross-pane interference (guestId filter). The tab create activate change is a one-field addition with tests. No new privilege, no page content crosses IPC, and remote/headless paths degrade gracefully via the no-op stub.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/main/browser/cdp-ws-proxy.ts Core fix: replaces webContents.focus() with IPC-based borrow pattern via notifyAgentInput/withBorrowedFocus; covers insertText, dispatchKeyEvent, and mousePressed; error handling and destroyed-webContents guards are correct throughout
src/renderer/src/components/browser-pane/browser-focus.ts New createAgentInputFocusBorrow factory uses a depth counter to safely handle overlapping keyDown/keyPress/keyUp begin/end pairs; unmatched-end guard prevents counter going negative; logic is sound
src/renderer/src/components/browser-pane/BrowserPane.tsx Subscribes to onBrowserAgentInput in a new useEffect; focusWebviewNow is a stable useCallback([]) so the borrow closure is created once per pane mount; guest-id filter prevents cross-pane interference; not gated on isActive, which is the intentional design for background tabs
src/cli/handlers/browser-tab.ts tab create now explicitly sends activate:false by default; --focus flag opts in to activate:true, matching tab switch behavior
src/main/browser/cdp-ws-proxy.test.ts New tests cover dispatchKeyEvent borrow (begin+end), mousePressed borrow (begin), and mouseReleased/mouseMoved non-borrow; dispatchKeyEvent test asserts both phases
src/main/browser/cdp-ws-proxy-focus-replay.test.ts Updated to assert hostWebContents.send with phase:'begin'; new timing test verifies 'end' is not sent until insertText resolves; adds BrowserWindow mock needed by the focus borrow path
src/renderer/src/components/browser-pane/browser-focus.test.ts Tests for createAgentInputFocusBorrow cover single borrow, nested borrows, partial-end, and unmatched-end cases; good coverage of the depth-counter logic
src/preload/index.ts Adds onBrowserAgentInput IPC subscriber that forwards ui:browserAgentInput events to the renderer; cleanup function correctly removes the listener on unsubscribe
src/renderer/src/web/web-preload-api.ts No-op stub for onBrowserAgentInput in the web (remote/SSH) client; correct since remote panes stream a viewport and have no local webview to focus
src/preload/api-types.ts Adds onBrowserAgentInput type to PreloadApi; types match the IPC payload shape exactly
src/cli/browser.test.ts Tests verify tab create defaults to activate:false and that --focus sets activate:true
src/cli/specs/browser-basic.ts Updated usage string and allowedFlags for tab create to include --focus
src/main/browser/cdp-ws-proxy-test-harness.ts Mock updated with hostWebContents (isDestroyed + send) and webContents.id; minimal additions, correctly typed

Sequence Diagram

sequenceDiagram
    participant Agent as Agent (CDP client)
    participant Proxy as cdp-ws-proxy (main)
    participant Renderer as BrowserPane (renderer)
    participant Webview as webview guest

    Agent->>Proxy: Input.insertText / dispatchKeyEvent / mousePressed

    Proxy->>Renderer: "IPC ui:browserAgentInput { phase:'begin', guestId }"
    Note over Renderer: captureOwner() saves document.activeElement if depth===0, then increments depth, calls focusWebviewNow()
    Renderer->>Webview: webview.focus()

    Note over Proxy: await 16ms (one animation frame)

    Proxy->>Webview: CDP command (debugger.sendCommand)
    Webview-->>Proxy: result

    Proxy->>Renderer: "IPC ui:browserAgentInput { phase:'end', guestId }"
    Note over Renderer: depth--, if depth===0 restore(savedOwner)
    Renderer->>Renderer: savedOwner.focus() (e.g. terminal)

    Proxy-->>Agent: CDP response
Loading

Reviews (4): Last reviewed commit: "fix(browser): keep the focus borrow open..." | Re-trigger Greptile

Comment thread src/main/browser/cdp-ws-proxy.ts Resolved
@songminsns

Copy link
Copy Markdown
Author

Thanks — both findings were real. Fixed in 45427ed.

Overlapping begin/end race. You're right that this defeated the fix for the most common case. A single typed character sends keyDown/char/keyUp and each announces its own pair, so the second begin overwrote the saved owner with null (the guest already had focus by then) and no end had anything to restore — focus stayed parked on the webview, exactly the symptom this PR is about.

Borrows are now counted: only the outermost begin captures the owner, only the outermost end restores. An unmatched end (a command already in flight when the listener mounts) is floored at zero so it can't swallow the next real restore. The rule is extracted to createAgentInputFocusBorrow in browser-focus.ts so it's testable on its own — covered for single, nested, partially-closed, and unmatched-end sequences.

mouseReleased overborrow. Correct, only the press takes focus. takesFocus is now mousePressed only, so a click no longer pays a frame of latency on the release.

Also added the missing end-phase assertions you noted, plus coverage that releases and moves announce nothing.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a1f7f030-aa7c-4f9f-aa5e-0fc8ff46d153

📥 Commits

Reviewing files that changed from the base of the PR and between e172a51 and e8828f4.

📒 Files selected for processing (14)
  • src/cli/browser.test.ts
  • src/cli/handlers/browser-tab.ts
  • src/cli/specs/browser-basic.ts
  • src/main/browser/cdp-ws-proxy-focus-borrow.test.ts
  • src/main/browser/cdp-ws-proxy-focus-replay.test.ts
  • src/main/browser/cdp-ws-proxy-test-harness.ts
  • src/main/browser/cdp-ws-proxy.test.ts
  • src/main/browser/cdp-ws-proxy.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-focus.test.ts
  • src/renderer/src/components/browser-pane/browser-focus.ts
  • src/renderer/src/web/web-preload-api.ts
🚧 Files skipped from review as they are similar to previous changes (14)
  • src/cli/specs/browser-basic.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/cli/browser.test.ts
  • src/preload/api-types.ts
  • src/cli/handlers/browser-tab.ts
  • src/main/browser/cdp-ws-proxy-focus-borrow.test.ts
  • src/preload/index.ts
  • src/main/browser/cdp-ws-proxy.test.ts
  • src/main/browser/cdp-ws-proxy-focus-replay.test.ts
  • src/main/browser/cdp-ws-proxy-test-harness.ts
  • src/renderer/src/components/browser-pane/browser-focus.test.ts
  • src/renderer/src/components/browser-pane/BrowserPane.tsx
  • src/main/browser/cdp-ws-proxy.ts
  • src/renderer/src/components/browser-pane/browser-focus.ts

📝 Walkthrough

Walkthrough

The CLI adds a --focus option to tab create and maps it to browser tab activation. CDP input forwarding now borrows guest focus for text, keyboard, and mouse-press events, then returns focus after command completion. The main process emits typed focus phase events through the preload bridge. Local browser panes handle matching guest events with nested focus borrowing and restoration. Tests cover routing, event phases, replay cases, and focus restoration.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% 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 and concisely describes the primary fix: preventing agent browser input from stealing user focus.
Description check ✅ Passed The description explains the problem, solution, testing, cross-platform review, security audit, and lack of visual changes in sufficient detail.
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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 40212531-7a14-4b1f-943c-003f8ea650dc

📥 Commits

Reviewing files that changed from the base of the PR and between 9d473c8 and fcaf842faeca43847b598b078c0b8dd49b184872.

📒 Files selected for processing (12)
  • src/cli/handlers/browser-tab.ts
  • src/cli/specs/browser-basic.ts
  • src/main/browser/cdp-ws-proxy-focus-replay.test.ts
  • src/main/browser/cdp-ws-proxy-test-harness.ts
  • src/main/browser/cdp-ws-proxy.test.ts
  • src/main/browser/cdp-ws-proxy.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-focus.test.ts
  • src/renderer/src/components/browser-pane/browser-focus.ts
  • src/renderer/src/web/web-preload-api.ts

Comment thread src/cli/handlers/browser-tab.ts Resolved
Comment thread src/main/browser/cdp-ws-proxy.ts Resolved
@songminsns

Copy link
Copy Markdown
Author

@coderabbitai both findings were correct — fixed in 3f74b8b.

Wait for Input.insertText before ending the borrow. This was a real hole in the fix. forwardCommand queues the debugger call and returns, so the borrow ended while Chromium had not processed the insert yet; the renderer handed focus back first and the text could still land in the user's window — exactly the leak this PR closes. forwardInsertText now awaits sendDebuggerCommand for the final dispatch and answers the client from there, so the borrow outlives the event.

Added the deferred-dispatch test you asked for: it holds Input.insertText unresolved, asserts begin was announced and end was not, then resolves and asserts end follows.

tab-create contract test. Right, the exact toHaveBeenCalledWith broke. Updated it to expect activate: false and added a --focus case expecting activate: true.

Verified against main: the remaining suite failures (wsl-hook-relay-live.integration, agent-exec-handler, and a flaky hosted-review-gitea) reproduce on the base branch and are unrelated to this change.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@songminsns Confirmed. forwardInsertText now keeps the focus borrow active until the final debugger dispatch completes. The deferred-dispatch test verifies the required begin/end ordering. The tab-create tests now cover both activate: false and --focus with activate: true.

🐇 ✅


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

@AmethystLiang
AmethystLiang requested a review from OrcaWin July 31, 2026 16:50
@songminsns
songminsns force-pushed the fix/agent-browser-input-steals-user-focus branch from 3f74b8b to a2aa122 Compare August 8, 2026 13:24
@coderabbitai

coderabbitai Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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: Pro Plus

Run ID: 6ea21e2b-fbb1-4328-afd9-0cc47a4b8bf9

📥 Commits

Reviewing files that changed from the base of the PR and between 54a9b58 and a2aa1226103d535248c56ec2e56be80a776865ac.

📒 Files selected for processing (14)
  • src/cli/browser.test.ts
  • src/cli/handlers/browser-tab.ts
  • src/cli/specs/browser-basic.ts
  • src/main/browser/cdp-ws-proxy-focus-borrow.test.ts
  • src/main/browser/cdp-ws-proxy-focus-replay.test.ts
  • src/main/browser/cdp-ws-proxy-test-harness.ts
  • src/main/browser/cdp-ws-proxy.test.ts
  • src/main/browser/cdp-ws-proxy.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-focus.test.ts
  • src/renderer/src/components/browser-pane/browser-focus.ts
  • src/renderer/src/web/web-preload-api.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/cli/handlers/browser-tab.ts
  • src/cli/specs/browser-basic.ts
  • src/renderer/src/components/browser-pane/BrowserPane.tsx
  • src/renderer/src/components/browser-pane/browser-focus.test.ts
  • src/main/browser/cdp-ws-proxy-focus-replay.test.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/cli/browser.test.ts

Comment thread src/main/browser/cdp-ws-proxy.ts Resolved
@songminsns

Copy link
Copy Markdown
Author

Rebased onto current main (54a9b58) and closed a gap this PR left open.

focusWebviewNow() reports whether the guest ended up holding focus, and the borrow was discarding that. A guest can refuse focus while staying alive — a hidden or detached pane still answers CDP — so the input went out anyway and landed in whatever the user was typing into, which is the leak this PR is about.

The pane now answers the borrow. Main forwards on a grant, fails the command on a refusal so the agent learns its input did not land, and falls through on silence so guests with no pane — offscreen, headless, not yet mounted — behave exactly as they did before the handoff existed. Waiting for the real signal also replaces the fixed 16 ms per key event and mouse press, so the common path got faster rather than slower.

Writing the tests turned up a second bug on the way: Input.insertText dropped the rejection from its borrow, so a refused borrow left the client hanging with no reply at all. Fixed alongside — forwardInsertText answers its own failures, so only the refused borrow needed catching.

browser-pane/ was refactored substantially in the meantime; there were no textual conflicts. 980 tests pass across src/main/browser, src/renderer/src/components/browser-pane and src/cli/browser.test.ts, plus typecheck, oxlint, oxfmt and the max-lines ratchet.

One thing I can't do from my side: no CI has run on this PR at any point — the check list only ever had the review bots, so the workflows look to be waiting on a maintainer to approve them for an outside fork. Could you kick those off?

@songminsns

Copy link
Copy Markdown
Author

Good catch — that one was real, and it undercut the fix in exactly the case the PR is about.

That timeout is only reachable after the host renderer accepted the announcement, so silence there never meant "no handoff needed" — it meant no pane is holding this guest, because it is mounting, unmounting, or being swapped out. None of those can take focus, and resolving them as granted sent the keystroke out unfocused, into whatever the user was typing into. The comment I left there described the situation correctly and then drew the wrong conclusion from it: "pre-handoff behaviour" is just the bug this PR exists to remove.

Silence now fails the command like an outright refusal, in 93ef180. The hostless path stays separate as you suggested — a guest with no host renderer never announces a borrow at all and forwards straight through, so offscreen and headless are untouched.

I also raised the bound from 64 ms to 250 ms. It used to be a fixed pause to absorb; now it decides whether a command fails, so it needs slack for a renderer that is briefly busy rather than being tuned to one frame. The granted path never reaches it — a mounted pane answers immediately — so nothing gets slower.

Test updated to expect the failure, and the hostless case keeps its forwarding coverage. 980 tests still pass across src/main/browser, browser-pane/ and cli/browser.test.ts, along with typecheck, oxlint and oxfmt.

Agent-driven CDP input only reaches an Electron <webview> guest while that guest
holds native DOM focus. Without it Chromium routes the event to whichever surface
actually has focus — the terminal the user is typing into — yet the CDP call still
resolves ok, so the agent never learns its keystrokes landed somewhere else.

The main process cannot fix this on its own: webContents.focus() is a no-op for a
<webview> guest, because the guest is a DOM element owned by the host renderer.
Route the handoff through that renderer instead. Before dispatching input the proxy
announces a borrow, the pane records document.activeElement and focuses the guest,
and once the event has been forwarded the pane restores the element that had it.

Scope is deliberately narrow:

- Input.insertText / Input.dispatchKeyEvent always borrow, since key events reach
  nothing without focus.
- Input.dispatchMouseEvent borrows only for mousePressed/mouseReleased. Moves and
  wheels never take focus, so borrowing for them would create the very focus hop
  this change prevents.
- Runtime.evaluate, screenshots and read-only traffic are untouched.

The listener is intentionally not gated on the pane being active: agents drive
background tabs while the user works elsewhere, which is exactly when the leak
happened. Panes filter by guest webContents id so only the addressed one reacts.

Also fixes `orca tab create`, which never sent `activate` even though TabCreate
documents "agent/automation opens stay background". Every agent-created tab
surfaced the browser pane and took focus. It now mirrors `tab switch`: --focus is
opt-in.
Review caught two problems with the borrow protocol.

A single agent action nests borrows: typing one character sends keyDown/char/keyUp,
and each announces its own begin/end. The pane recorded the previous owner on every
begin, so the second one overwrote it with null — the guest already held focus by
then — and no end had anything left to restore. Focus stayed parked on the browser
for the rest of the session, which is the exact symptom this change set out to fix.

Count the borrows instead: only the outermost begin captures the owner and only the
outermost end gives focus back. An unmatched end (a command already in flight when
the listener mounted) is floored at zero so it cannot swallow the next real restore.
The rule lives in browser-focus as createAgentInputFocusBorrow so it is testable on
its own.

Also stop borrowing for mouseReleased. Only the press moves focus onto the guest, so
the release was paying a frame of latency on every click for nothing.

Tests cover the nesting rule (single, nested, partially-closed, unmatched end) and
assert both phases are announced for key events and presses but not for releases or
moves.
The mock declared send as (channel, phase: string) but the proxy sends
(channel, { phase, guestId }). No runtime impact — the assertions already
matched on the object — but the annotation misled anyone reading the harness.
forwardCommand queues the debugger call and returns, so the borrow ended while
Chromium had not processed Input.insertText yet. The renderer handed focus back
first and the text still landed in the user's window — the leak this change set
out to close. Await the dispatch instead and answer the client from there.

Also updates the tab-create contract test for the activate field and adds a
--focus case, plus a deferred-dispatch test that pins 'end' to command
resolution rather than to queueing.
The borrow announced itself and waited a fixed frame, then forwarded the
input whether or not the guest had actually taken focus. A guest can refuse
focus while staying perfectly alive — a hidden or detached pane still answers
CDP — so the keystroke landed in whatever the user was typing into, which is
the leak this path exists to close.

The pane now answers the borrow. Main forwards on a grant, fails the command
on a refusal so the agent sees it, and falls through on silence so guests with
no pane behave exactly as they did before the handoff existed. Granting also
replaces the fixed frame with the real signal, so input no longer pays 16 ms
per event.
A borrow the host renderer accepted but nobody answered was resolving as
granted, so the input went out with the guest unfocused — into whatever the
user was typing into. Silence there does not mean "no handoff needed"; it
means no pane is holding this guest, because it is mounting, unmounting, or
being swapped out. None of those can take focus.

Silence now fails the command like an outright refusal. Guests with no host
renderer at all still skip the borrow and forward, so offscreen and headless
keep working. The bound grows to 250 ms, since it is now slack for a busy
renderer rather than an expected wait — a mounted pane answers immediately
and never reaches it.
@songminsns
songminsns force-pushed the fix/agent-browser-input-steals-user-focus branch from 93ef180 to e8828f4 Compare August 9, 2026 02:53
@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@songminsns

Copy link
Copy Markdown
Author

Checking in on where this stands before I put time into the rebase it now needs.

Current state. This conflicts with main again — 897 commits have landed since my last push on Aug 9. It is not a plain replay this time: Split browser pane (#14861) and split browser and browser-IPC modules (#14697) moved browser-focus.ts into browser-pane/host-guest/ and reshaped the files around it, so the change has to be re-placed rather than rebased. I am happy to do that. I would just rather know it is wanted first — this would be the third rebase, and the previous two did not move the PR along.

CI has never run here. In this PR's whole life the check list has only ever held the review bots — no static analysis, no typecheck, no tests node 24/26, nothing from pr.yml. An internal PR from the same week carries 40+ checks, so I assume the workflows are waiting on a maintainer to approve them for an outside fork; I cannot trigger that myself. The branch was green locally at every push — 1006 tests across src/main/browser, browser-pane/ and cli/browser.test.ts, plus typecheck, oxlint and oxfmt — but that is my word rather than CI's.

Overlap with #10875. #15309 flagged the two of us together and I think that flag was right. #10875 restores the host WebContents focus owner after mousePressed and deliberately leaves DOM focus alone; this PR lends the guest DOM focus for the duration of the input and hands it back, covering Input.insertText and key events as well as the press. Same symptom, different layers — and both touch the mousePressed path in cdp-ws-proxy.ts. Whichever way you want it to go — land one, land both with one rebased onto the other, or fold them together — I am glad to adapt. I would just rather not rebase into a conflict with something you are about to merge.

So: is this one you want to take? If yes, I will rebase onto current main right away and report back here once it is green. If the direction is #10875 instead, say so and I will close this — no hard feelings; the investigation behind it is written up either way.

@OrcaWin @nwparker

@Jinwoo-H

Copy link
Copy Markdown
Contributor

Thanks @songminsns for the investigation and implementation. We are taking ownership of the browser-focus bug in canonical issue #16674, which covers the current Windows tab-create/switch focus-stealing path. This branch is based on older code and will be superseded by a current-main implementation; no contributor rebase, retest, or other follow-up is requested. Closing this PR while preserving your credit in the issue and owner implementation.

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.

5 participants