Repository navigation
fix(browser): stop agent browser input from stealing the user's focus - #11732
songminsns wants to merge 6 commits into
Conversation
Greptile SummaryThis PR fixes two related focus bugs in the agent browser: CDP input events leaking into the user's terminal because the
Confidence Score: 5/5Safe 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.
|
| 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
Reviews (4): Last reviewed commit: "fix(browser): keep the focus borrow open..." | Re-trigger Greptile
|
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 Borrows are now counted: only the outermost mouseReleased overborrow. Correct, only the press takes focus. Also added the missing |
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (14)
🚧 Files skipped from review as they are similar to previous changes (14)
📝 WalkthroughWalkthroughThe CLI adds a 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
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.tssrc/cli/specs/browser-basic.tssrc/main/browser/cdp-ws-proxy-focus-replay.test.tssrc/main/browser/cdp-ws-proxy-test-harness.tssrc/main/browser/cdp-ws-proxy.test.tssrc/main/browser/cdp-ws-proxy.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/browser-pane/BrowserPane.tsxsrc/renderer/src/components/browser-pane/browser-focus.test.tssrc/renderer/src/components/browser-pane/browser-focus.tssrc/renderer/src/web/web-preload-api.ts
|
@coderabbitai both findings were correct — fixed in 3f74b8b. Wait for Added the deferred-dispatch test you asked for: it holds tab-create contract test. Right, the exact Verified against |
|
Tip For best results, initiate chat on the files or code changes.
🐇 ✅ 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. |
3f74b8b to
a2aa122
Compare
|
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. |
There was a problem hiding this comment.
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.tssrc/cli/handlers/browser-tab.tssrc/cli/specs/browser-basic.tssrc/main/browser/cdp-ws-proxy-focus-borrow.test.tssrc/main/browser/cdp-ws-proxy-focus-replay.test.tssrc/main/browser/cdp-ws-proxy-test-harness.tssrc/main/browser/cdp-ws-proxy.test.tssrc/main/browser/cdp-ws-proxy.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/browser-pane/BrowserPane.tsxsrc/renderer/src/components/browser-pane/browser-focus.test.tssrc/renderer/src/components/browser-pane/browser-focus.tssrc/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
|
Rebased onto current
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:
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? |
|
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 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 |
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.
93ef180 to
e8828f4
Compare
|
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. |
|
Checking in on where this stands before I put time into the rebase it now needs. Current state. This conflicts with CI has never run here. In this PR's whole life the check list has only ever held the review bots — no Overlap with #10875. #15309 flagged the two of us together and I think that flag was right. #10875 restores the host So: is this one you want to take? If yes, I will rebase onto current |
|
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. |
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 resolvesok, 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:
mousePressedmoves 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 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:
okthat hid this bug in the first place.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.dispatchKeyEventalways borrow — key events reach nothing without focus.Input.dispatchMouseEventborrows only formousePressed. 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
webContentsid so only the addressed one reacts.Also included:
orca tab createnever sentactivate, even thoughTabCreatedocuments "User-initiated opens focus the tab; agent/automation opens stay background." Every agent-created tab surfaced the browser pane and took focus. It now mirrorstab switch—--focusis 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.
inserttext/type/keypressmouse down/up,clicktab createeval,screenshot,mouse movesnapshot,set device,goto,tab switch,tab closeEvery 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-proxysuites 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 nativewebContents.focus().cdp-ws-proxy-focus-borrow.test.tscovers what main does with each answer — forwards on a grant, fails the command on a refusal (key events andInput.insertTextboth), fails on silence, and skips the ask entirely when the guest has no host renderer.browser-focus.test.tscovers 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-paneandsrc/cli/browser.test.ts, on top of the currentmain.Code review summary
hostWebContents,send, and DOM focus are Electron/DOM APIs available on macOS, Linux, and Windows. Verified on macOS; the logic contains nothing OS-specific.<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.Runtime.evaluate, screenshots, mouse moves) are untouched.Testing notes
<webview>path.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