Repository navigation
Conversation
`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
📝 WalkthroughWalkthroughAdds host focus guard helpers that capture and restore valid native 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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.
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 winRestore focus in a
finallyblock.A rejected/timed-out dispatch after
mousePressedskips 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 intry/finally.src/main/browser/cdp-bridge.ts#L246-L274: wrap the drag dispatch sequence intry/finally.src/main/browser/cdp-bridge.ts#L473-L501: wrap the check dispatch sequence intry/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 valueCondense 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
📒 Files selected for processing (4)
src/main/browser/cdp-bridge-integration.test.tssrc/main/browser/cdp-bridge.tssrc/main/browser/host-focus-guard.test.tssrc/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.
|
Thanks — both addressed in 96f4b64. Restore in Module comment (Nitpick): condensed to the native-vs-DOM focus contract; dropped the implementation history.
|
|
Heads-up after the The paths the CLI actually uses are:
So the capture/restore guard would need to wrap |
|
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:
The design and measurements are in |
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.dispatchMouseEventwithmousePressedmakes 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:Input.insertTextfill,typeDOM.focusreplay (#7041) +webContents.focus()Runtime.evaluateevalInput.dispatchMouseEventclick,drag,checkThe exclusion for
Runtime.evaluatealready states the intent incdp-ws-proxy.ts:This PR completes that intent for the remaining path.
New
host-focus-guard.tscaptures the focused hostWebContentsbefore dispatching synthetic mouse events and hands focus back afterwards, in afinallyso a rejected or timed-out dispatch cannot strand focus on the guest. Applied toclick,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.clickthenfill) 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
WebContentscan churn selection).Screenshots
No visual change— main-process focus routing only, no UI surface touched.Testing
pnpm lint— fails onmaintoo, in files this PR does not touch.verify:localization-coveragerejects untranslated"Ghostty"keywords interminal-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 viaconfig/localization-coverage-allowlist.jsonhere, since those strings belong to another change.oxlintreports 0 findings on the four files changed in this PR.pnpm typecheck— exit 0pnpm test— 3462 passed / 8 files failed, all from my local Node version, not from the repo or this PR. The repo pinsengines.node: 24; I ran on v25.8.1, where the globallocalStorageshadows the jsdom one. Every one of the 43 failures iswindow.localStorage.clear/getItem/removeItem is not a functioninsrc/relay/andsrc/renderer/— none insrc/main/browser/, and they reproduce identically on unmodifiedorigin/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 changespnpm build— not runhost-focus-guard.test.tscovers 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
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 intry/finallyat all three call sites, with a test asserting restoration on throw.WebContentscan churn selection in some editors, and restoring when the guest legitimately owns focus would start a focus fight. Both guarded, both tested.clickis the trigger" rather than "the other paths are proven risk-free";type/inserttextare explicitly left out of scope below.document.hasFocus()never returns true for these guest views (consistent with [Bug]: Regression of #7035 — embedded browser tab reportsdocument.hasFocus()===false, soInput.insertText/execCommandno-op in rich editors (X/Draft.js) #10375/fix(browser): emulate CDP page focus for rich-editor insertText #10376 and Electron 43+ trackingWebContentsViewfocus 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()andfocus()— 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
guestIdand aWebContentshandle obtained from Electron.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.restoreHostFocusis a bounded, non-recursive call with no retry loop; thefinallyplacement means it runs exactly once per operation.Notes
Repro — related to #8139, which was blocked at
cannot_repro: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:snapshot/get/is/networkeval(DOM.click()+ value set)fillclickOrder-reversed crossover, excluding a warm-up or time-of-day confound:
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
Input.dispatchMouseEventis changed.Input.insertText(type,inserttext) andPage.bringToFront(tab switch --focus) still callwebContents.focus()by design;type/inserttextwere not measured.Emulation.setFocusEmulationEnabled) is untested. That PR touchescdp-bridge.tsandcdp-ws-proxy.tsand changes whatdocument.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 againstmain.Test-side change:
cdp-bridge-integration.test.tsneededgetFocusedWebContentsadded to itselectronmock; 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.