Skip to content

fix(browser): restore host focus after synthetic mouse presses - #10875

Closed
grboy6770 wants to merge 2 commits into
stablyai:mainfrom
grboy6770:fix/browser-click-restores-host-focus
Closed

grboy6770 wants to merge 2 commits into
stablyai:mainfrom
grboy6770:fix/browser-click-restores-host-focus

Conversation

@grboy6770

@grboy6770 grboy6770 commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Background browser automation stole the host's keyboard focus on every click, pulling the caret out of whatever pane the user was typing in.

Input.dispatchMouseEvent with mousePressed makes Chromium hand native focus to the guest view that received the press. The two neighbouring input paths already compensate for this — the synthetic mouse path did not:

CDP path orca command Compensation today
Input.insertText fill, type DOM.focus replay (#7041) + webContents.focus()
Runtime.evaluate eval Deliberately excluded from auto-focus
Input.dispatchMouseEvent click, drag, check none

The exclusion for Runtime.evaluate already states the intent in cdp-ws-proxy.ts:

Do not auto-focus generic Runtime.evaluate/callFunctionOn traffic: wait polling and read-only JS probes use those methods heavily, and focusing on every eval steals the user's foreground window while background automation is running.

This PR completes that intent for the remaining path.

New host-focus-guard.ts captures the focused host WebContents before dispatching synthetic mouse events and hands focus back afterwards, in a finally so a rejected or timed-out dispatch cannot strand focus on the guest. Applied to click, drag, check.

DOM focus still follows the click — only the OS/app-level focus owner is restored, so automation that relies on document.activeElement (e.g. click then fill) is unaffected.

Guarded edge cases: guest already owns focus → no restore (the user is driving that view); captured contents destroyed mid-click → no-op; focus never moved → no re-focus (re-focusing an already-focused WebContents can churn selection).

Screenshots

No visual change — main-process focus routing only, no UI surface touched.

Testing

  • pnpm lint — fails on main too, in files this PR does not touch. verify:localization-coverage rejects untranslated "Ghostty" keywords in terminal-advanced-platform-search.ts / terminal-pane-appearance-search.ts (last touched by Show Terminal and Window settings by default in Appearance pane #10628). Deliberately not silenced via config/localization-coverage-allowlist.json here, since those strings belong to another change. oxlint reports 0 findings on the four files changed in this PR.
  • pnpm typecheck — exit 0
  • pnpm test — 3462 passed / 8 files failed, all from my local Node version, not from the repo or this PR. The repo pins engines.node: 24; I ran on v25.8.1, where the global localStorage shadows the jsdom one. Every one of the 43 failures is window.localStorage.clear/getItem/removeItem is not a function in src/relay/ and src/renderer/ — none in src/main/browser/, and they reproduce identically on unmodified origin/main (verified in a detached worktree). CI runs Node 24, so it is authoritative here.
  • pnpm exec vitest run --config config/vitest.config.ts src/main/browser/ — 29 files, 526 passed, the module this PR changes
  • pnpm build — not run
  • Added tests: host-focus-guard.test.ts covers capture/restore, guest-already-focused, destroyed contents, no-op restoration, third-view focus change, and the rejection path (dispatch throws → restore still runs)

AI Review Report

Reviewed with Claude (Sonnet 4.5) plus an independent Codex pass used adversarially against my own conclusions.

Risks checked and what changed as a result

  • Rejection path — flagged by CodeRabbit and fixed in 96f4b64d: the first revision restored focus after the awaits, so a rejected or timed-out dispatch skipped restoration and left focus on the guest — the exact failure mode the guard exists to prevent. Now wrapped in try/finally at all three call sites, with a test asserting restoration on throw.
  • Over-restoring — re-focusing an already-focused WebContents can churn selection in some editors, and restoring when the guest legitimately owns focus would start a focus fight. Both guarded, both tested.
  • Scope of the claim — Codex pushed back on inferring "eval is safe" from a single measurement window. Rule-of-three on the sample gives roughly a 1.8% per-command upper bound, so the finding is stated as "click is the trigger" rather than "the other paths are proven risk-free"; type/inserttext are explicitly left out of scope below.
  • Instrument validity — document.hasFocus() never returns true for these guest views (consistent with [Bug]: Regression of #7035 — embedded browser tab reports document.hasFocus()===false, so Input.insertText/execCommand no-op in rich editors (X/Draft.js) #10375/fix(browser): emulate CDP page focus for rich-editor insertText #10376 and Electron 43+ tracking WebContentsView focus more strictly), so it was discarded as a measurement tool and the finding rests on order-reversed observation instead.

Cross-platform: reviewed explicitly. The change uses only webContents.getFocusedWebContents(), isDestroyed() and focus() — no platform branches, no paths, no shell, no shortcuts or labels. focus() semantics differ per platform in how the OS raises a view, but the guard only restores whatever owned focus beforehand, so it cannot introduce a platform-specific ordering that did not already exist. The measurements were taken on macOS; the logic is platform-neutral but has not been exercised on Linux or Windows.

Security Audit

  • Input handling — no user input parsed; the only inputs are an integer guestId and a WebContents handle obtained from Electron.
  • Command execution / path handling — none introduced.
  • Auth / secrets — none touched. No credentials, tokens or storage read or written.
  • IPC — no new IPC surface. The guard runs inside existing main-process CDP command handlers.
  • Privilege / cross-view exposure — the restore target is captured from getFocusedWebContents() immediately before dispatch and is only ever handed focus back to itself; the guard cannot move focus to a view that did not already hold it. It never reads or writes guest content.
  • Denial of service — restoreHostFocus is a bounded, non-recursive call with no retry loop; the finally placement means it runs exactly once per operation.
  • Follow-up — none identified.

Notes

Repro — related to #8139, which was blocked at cannot_repro:

Needs an isolated computer-use automation that asserts keyboard focus ownership during agent typing. Not reproduced here.

It did not reproduce because the trigger is not in the typing path. Measured on 1.4.158 (macOS), driving a scratch file:// tab while a human typed continuously in a terminal pane in the same window:

Command Commands issued Caret in user's pane
snapshot / get / is / network 32 held
eval (DOM .click() + value set) 224 @ 1.5/s held
fill 37 + 38, both orders held
click 39 + 38, both orders lost

Order-reversed crossover, excluding a warm-up or time-of-day confound:

Run Order click segment fill segment
1 click → fill caret lost caret held
2 fill → click caret lost caret held

Each segment carried execution evidence (a page-side click counter and the final input value) so a silently-skipped command could not be mistaken for a clean run.

Scope / what this does not cover

  • Only Input.dispatchMouseEvent is changed. Input.insertText (type, inserttext) and Page.bringToFront (tab switch --focus) still call webContents.focus() by design; type/inserttext were not measured.
  • Marked Related to rather than Fixes [Bug]: Keyboard is taken over when using Orca browser skill #8139 for that reason — the reporter described typing, and I only have evidence for the mouse path. Happy to retarget if a maintainer confirms the remaining paths are in scope.
  • Interaction with fix(browser): emulate CDP page focus for rich-editor insertText #10376 (Emulation.setFocusEmulationEnabled) is untested. That PR touches cdp-bridge.ts and cdp-ws-proxy.ts and changes what document.hasFocus() reports; this change is orthogonal (OS-level focus owner, not page-level focus emulation) but the two are worth verifying together. GitHub currently reports this branch as mergeable against main.
  • Verified on macOS only.

Test-side change: cdp-bridge-integration.test.ts needed getFocusedWebContents added to its electron mock; that is the only non-source edit.

ELI5

When an agent clicked something in a browser tab in the background, your computer decided the browser was now the thing you were typing into — so your cursor vanished out of the terminal mid-sentence. Typing and running scripts already knew not to do that. Clicking didn't. Now it puts your cursor back where it was.

`Input.dispatchMouseEvent` with `mousePressed` makes Chromium hand native
focus to the guest view that received the press. Background automation
clicking in a browser tab therefore pulled the caret out of whatever pane
the user was typing in.

The two neighbouring input paths already compensate for this:
- `Input.insertText` re-applies the pending `DOM.focus` (stablyai#7041)
- `Runtime.evaluate` is deliberately excluded from auto-focus

The synthetic mouse path had no such compensation. Capture the focused
host WebContents before dispatching and hand focus back afterwards.

DOM focus still follows the click; only the OS/app-level focus owner is
restored, so automation relying on `document.activeElement` is unaffected.

Applied to the three call sites that dispatch `mousePressed`: click, drag
and check.

Related to stablyai#8139
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds host focus guard helpers that capture and restore valid native WebContents focus. CDP click, drag, and check operations use these helpers around synthetic mouse interactions. Tests cover focus ownership, destroyed contents, no-op restoration, and third-view focus changes. The Electron integration mock now includes getFocusedWebContents.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The code restores focus after click/drag/check synthetic mouse presses, matching the linked issue's focus-loss bug.
Out of Scope Changes check ✅ Passed The changes stay focused on host-focus preservation and related tests; no unrelated features or code paths were added.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly summarizes the main change: restoring host focus after synthetic mouse presses.
Description check ✅ Passed The description follows the template and covers summary, screenshots, testing, review, security, and notes with substantive detail.

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/browser/cdp-bridge.ts (1)

184-205: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Restore focus in a finally block.

A rejected/timed-out dispatch after mousePressed skips restoration and leaves keyboard focus on the guest—the failure mode this guard is meant to prevent.

  • src/main/browser/cdp-bridge.ts#L184-L205: wrap the click dispatch sequence in try/finally.
  • src/main/browser/cdp-bridge.ts#L246-L274: wrap the drag dispatch sequence in try/finally.
  • src/main/browser/cdp-bridge.ts#L473-L501: wrap the check dispatch sequence in try/finally, and add rejection-path coverage.
Proposed pattern
 const hostFocus = captureHostFocus(guest.id)
-
- await sender('Input.dispatchMouseEvent', ...)
- await sender('Input.dispatchMouseEvent', ...)
- await sender('Input.dispatchMouseEvent', ...)
-
- restoreHostFocus(hostFocus)
+try {
+  await sender('Input.dispatchMouseEvent', ...)
+  await sender('Input.dispatchMouseEvent', ...)
+  await sender('Input.dispatchMouseEvent', ...)
+} finally {
+  restoreHostFocus(hostFocus)
+}
🧹 Nitpick comments (1)
src/main/browser/host-focus-guard.ts (1)

3-15: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense this module comment.

It repeats implementation history and out-of-scope behavior; retain a short statement of the native-vs-DOM focus contract.

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: 704529d2-9b36-4abd-baf1-6a88bf479357

📥 Commits

Reviewing files that changed from the base of the PR and between a142c84 and 70a46c8.

📒 Files selected for processing (4)
  • src/main/browser/cdp-bridge-integration.test.ts
  • src/main/browser/cdp-bridge.ts
  • src/main/browser/host-focus-guard.test.ts
  • src/main/browser/host-focus-guard.ts

A rejected or timed-out dispatch after mousePressed skipped restoration and
left keyboard focus on the guest — the exact failure mode the guard exists to
prevent. Wrap the mouse dispatch sequences in click, drag and check so focus is
handed back on the rejection path too, and cover it with a test.

Also condenses the module comment per the repo's one-line comment guideline.
@grboy6770

Copy link
Copy Markdown
Contributor Author

Thanks — both addressed in 96f4b64.

Restore in finally (Major): correct, and it was the exact failure mode this guard exists to prevent. A rejected or timed-out dispatch after mousePressed left focus stranded on the guest. click, drag and check now wrap their dispatch sequences so restoration runs on the rejection path, plus a test that asserts restoreHostFocus still fires when the dispatch throws.

Module comment (Nitpick): condensed to the native-vs-DOM focus contract; dropped the implementation history.

pnpm exec vitest run --config config/vitest.config.ts src/main/browser/ — 29 files, 526 passed.

@Fanzzzd

Fanzzzd commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Heads-up after the cdp-bridge split: on current main, nothing in production constructs CdpBridge (grep -rn "new CdpBridge" src only hits tests). The click/drag/check code this PR guards now lives in cdp-pointer-commands.ts and cdp-element-state-commands.ts, and those are also only reachable through CdpBridge.

The paths the CLI actually uses are:

  • orca click / drag / check: agent-browser over cdp-ws-proxy.ts, so Input.dispatchMouseEvent passes through CdpWsProxy.handleMessage.
  • orca mouse click: agent-browser-bridge-mouse-commands.ts, which calls wc.focus() explicitly before dispatching.

So the capture/restore guard would need to wrap mousePressed in the proxy (and the direct mouse command) to affect #8139.

@nwparker

Copy link
Copy Markdown
Contributor

Closing this one as superseded. Thank you for it. The fix for agent browser input and the user's keyboard focus (#20595) landed in #28452, #28453 and #28454, and this PR's investigation helped shape it.

What landed:

  • Agent keys and text go straight to the targeted page as key/character events, never by way of window focus. On a <webview> page, CDP key and text input lands wherever the window's focus is. CDP focus emulation doesn't change that, so emulation alone wasn't enough.
  • Agent clicks move focus into the page no matter how the click is sent. The pane now gives focus back to the user's element when the click ends, and focus emulation keeps the page from seeing a blur.
  • Input that only CDP can deliver borrows focus for that one command and gives it back. If focus can't be protected, the input is refused instead of sent.

The design and measurements are in docs/reference/agent-browser-focus-isolation.md.

@nwparker nwparker closed this Oct 15, 2026
@grboy6770
grboy6770 deleted the fix/browser-click-restores-host-focus branch October 15, 2026 03:51
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.

4 participants