Skip to content

fix(browser): restore programmatic focus for CDP text insertion - #7041

Merged
nwparker merged 12 commits into
stablyai:mainfrom
rodboev:pr/restore-cdp-focus-text-insertion
Jul 3, 2026
Merged

nwparker merged 12 commits into
stablyai:mainfrom
rodboev:pr/restore-cdp-focus-text-insertion

Conversation

@rodboev

@rodboev rodboev commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

Agent-browser drives the embedded Electron webview over a CDP WebSocket proxy. To type into a field it sends DOM.focus (to focus the target element) followed by Input.insertText. The proxy calls the native webContents.focus() immediately before forwarding Input.insertText (Electron webview guests need native focus for synthetic input). That native focus blurs the element DOM.focus had just selected, so Input.insertText lands on nothing and the text is silently dropped.

This restores programmatic focus by remembering each session's last DOM.focus params and replaying that DOM.focus in between the native webContents.focus() and the Input.insertText — re-selecting the intended element so the text actually goes in.

Key properties of the fix (src/main/browser/cdp-ws-proxy.ts):

  • Per-session pending-focus map, keyed by the resolved debugger session id, so root-frame and OOPIF (out-of-process iframe) inserts stay independent.
  • One-shot / invalidated aggressively: the stored focus is only valid for the immediately following Input.insertText. Any other CDP command (Page.bringToFront, Page.captureScreenshot, navigate/reload, eval traffic, …) clears it, because those can move DOM focus.
  • Pipelining-race safe: the map entry is set() synchronously before any await, so an Input.insertText pipelined in the same tick still finds the pending focus (covered by a test where Input.insertText is dispatched while DOM.focus is still in flight).
  • Disconnect-safe: forwardInsertText re-checks isActiveClient after each await (the initial focus and the replay round-trip), so a client that disconnects mid-flight never injects a stray DOM.focus or Input.insertText into the live user page. Cleared on client disconnect/replacement.
  • A failed DOM.focus is never stored/replayed; a replay that fails surfaces the error on the insert instead of typing into the wrong place.

Evidence

Bug is real and present on main — main's Input.insertText path only calls webContents.focus() and forwards, with no DOM.focus replay. A focused repro on origin/main produces the sequence ['DOM.focus', 'Input.insertText'] (no replay); with the fix it is ['DOM.focus', 'DOM.focus', 'Input.insertText'].

# repro on origin/main (FAIL)
AssertionError: expected [ 'DOM.focus', 'Input.insertText' ]
             to deeply equal [ 'DOM.focus', 'DOM.focus', 'Input.insertText' ]
# same repro with the fix (PASS)
Test Files  1 passed (1) · Tests  1 passed (1)

Unit coverage — 11 targeted tests in cdp-ws-proxy-focus-replay.test.ts (root + OOPIF replay, no-replay after eval, failed-focus not replayed, replay-error surfaced, pipelining race, Page.bringToFront/Page.captureScreenshot invalidation, reconnect isolation, and two disconnect-mid-flight guards), plus the existing cdp-ws-proxy suite.

Test Files  2 passed (2)
     Tests  41 passed (41)
pnpm run typecheck   → clean (node + cli + web)
oxlint / oxlint react-doctor / oxfmt --check  → clean

ELI5

The robot types by first "clicking" a text box, then typing. But right before typing, the app has to tap the window to wake it up — and that tap un-clicks the box, so the letters go nowhere. This change re-clicks the box in the split second between the tap and the typing, so the words land where they're supposed to.

Trade-offs

  • Adds one extra DOM.focus round-trip per Input.insertText that follows a focus. This is inherent to the native-focus constraint (native focus must happen, and it blurs), and it only occurs on the focus→insert pattern, not on read-only eval/wait polling.
  • The pending focus is deliberately single-use and invalidated by any intervening command; it is not a general focus-state cache. This keeps it from ever replaying stale focus into an unrelated insert.
  • No behavior change for callers that don't send DOM.focus before Input.insertText. No regressions to the printToPDF / screenshot / navigate / reload paths.

@ghost

ghost commented Jul 1, 2026 •

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 3 individual chapters for you:

Title
1 Introduce session ID utility and state tracking
2 Implement DOM focus replay for text insertion
3 Verify focus replay with integration tests
Open in Stage

Chapters generated by Stage for commit 0bbc5c1 on Jul 1, 2026 9:46pm UTC.

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This change adds per-session tracking of pending DOM.focus commands in CdpWsProxy. The proxy now stores focus parameters by effective session id, clears them on non-focus traffic and client close, and replays DOM.focus before Input.insertText when needed. The test suite adds ordering checks plus scenarios for OOPIF sessions, suppression, failure handling, pipelining, intervention commands, and client reconnects.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The renderer test formatting-only change is unrelated to the CDP focus fix and appears outside the linked issue scope. Remove or justify the ai-vault-session-resume.test.ts formatting-only edit, or split it into a separate housekeeping PR.
Description check ⚠️ Warning The description is missing the required template sections for Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes. Rewrite the PR description to follow the template and add the missing sections, including testing results, screenshots/no visual change, review report, security audit, and notes.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The proxy replay logic and tests address #7035 by restoring focus before Input.insertText and leaving unrelated traffic unchanged.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title matches the main change: restoring programmatic focus for CDP text insertion.

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: 1

🧹 Nitpick comments (2)
src/main/browser/cdp-ws-proxy.ts (1)

280-309: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a "Why" comment for the pending-focus invalidation design.

The rule that DOM.focus is only replayed for the immediately next Input.insertText — and is silently invalidated by Page.bringToFront (Line 282), Page.captureScreenshot (Line 295), or any other intervening command (Line 309) — is a non-obvious constraint central to this fix. A future edit to this fallthrough could easily break the replay guarantee without realizing it.

As per coding guidelines, "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."

📝 Suggested comment
+    // Why: only replay DOM.focus for the immediately next Input.insertText — any
+    // other intervening command (tab switch, screenshot, eval, navigation) means
+    // the stored focus target may no longer be relevant, so drop it.
     const effectiveSessionId = this.getEffectiveSessionId(msg.sessionId)

Source: Coding guidelines

src/main/browser/cdp-ws-proxy.test.ts (1)

331-503: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Solid coverage of the replay/suppression/error paths — consider also covering the bringToFront/captureScreenshot invalidation branches.

These new tests correctly validate replay ordering, session-id propagation, suppression after intervening traffic, and both failure paths (initial focus fails vs. replay fails), matching the implementation in cdp-ws-proxy.ts. One gap: there's no test exercising that Page.bringToFront or Page.captureScreenshot clears a pending DOM.focus (Lines 282 and 295 in cdp-ws-proxy.ts), even though those are explicit new branches in this PR.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 91345e4c-b111-4d74-836c-dd6e55487996

📥 Commits

Reviewing files that changed from the base of the PR and between ff44d36 and 684ec36.

📒 Files selected for processing (2)
  • src/main/browser/cdp-ws-proxy.test.ts
  • src/main/browser/cdp-ws-proxy.ts

Comment thread src/main/browser/cdp-ws-proxy.ts Resolved
nwparker and others added 9 commits July 3, 2026 12:54
# Conflicts:
#	src/main/browser/cdp-ws-proxy.test.ts
#	src/main/browser/cdp-ws-proxy.ts
Collapse the three per-handler deletes (Page.bringToFront, Page.captureScreenshot,
catch-all) of the pending DOM.focus replay into a single guarded delete keyed on
'not DOM.focus and not Input.insertText'. States the invariant in one place and
removes the trap where a future early-returning handler forgets to clear the
stale focus. Also clear the map on client teardown and shorten the field comment.

Co-authored-by: Orca <[email protected]>
# Conflicts:
#	src/main/browser/cdp-ws-proxy.ts
@nwparker

nwparker commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Took this over to get it across the line, @rodboev. Summary of what I validated and changed:

Validated

  • Reproduced the bug on origin/main: the Input.insertText path there only calls native webContents.focus() and forwards, with no DOM.focus replay, so the sequence is ['DOM.focus', 'Input.insertText'] and text is dropped. With this PR it becomes ['DOM.focus', 'DOM.focus', 'Input.insertText'].
  • Security re-screen of the full diff vs main: no change to the CDP proxy's auth/binding (still bound to 127.0.0.1, connection-level), no focus/input reaching non-agent pages, no exfiltration/dep/CI changes. The feature operates only on the proxy's own guest webContents.
  • Merged latest main forward (resolved cleanly; adopted upstream Fix main typecheck: pin Buffer<ArrayBuffer> in cdp-ws-proxy mid-print test #7263's Buffer<ArrayBuffer> pin in the mid-print test). Final diff is exactly 4 browser files.
  • pnpm run typecheck clean (node + cli + web), oxlint/oxfmt clean, 41 unit tests passing.

Changed on top of your work (review-driven)

  • forwardInsertText now re-checks isActiveClient after each await — the initial DOM.focus and the replay round-trip — matching the pattern in navigateWithLifecycle/reloadWithLifecycle. Without this, a client that disconnected mid-flight could still inject a stray DOM.focus/Input.insertText into the live user page. Added two regression tests (each verified to fail without its guard).
  • Added an explicit return-type annotation to the extracted createMockWebContents harness so the exported inferred type stays nameable under composite declaration emit (tsgo TS2883); otherwise the vi.fn() mocks leak @vitest/spy's Procedure.

Thanks for the fix — the core focus-replay design (per-session, one-shot, synchronously-stored to close the pipelining race) held up well under review.

@nwparker
nwparker merged commit cede986 into stablyai:main Jul 3, 2026
1 check passed
@nwparker

nwparker commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Merged (squash) — thanks @rodboev! This passed the full review bar: the DOM.focus-replay fix is validated against a real, reproduced-on-main bug (native webContents.focus() blurs the programmatically-focused element, so Input.insertText no-ops), the diff is cleanly scoped to the CDP proxy + its tests, security re-screen was clean (no auth/binding change), and full typecheck + lint + 41 unit tests are green. Your core design — per-session, one-shot pending focus stored synchronously to close the pipelining race — held up well. I added two small guards (re-check the active client after each await in forwardInsertText, with regression tests) and an explicit harness return type for tsgo portability. Appreciate the fix!

@nwparker

nwparker commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

Thanks Rod 🙏 The native-focus-blurs-the-DOM-selection insight is chef's kiss — that's a nasty, invisible bug and you nailed the mechanism exactly. Always a pleasure reviewing your stuff. 🐋

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…lyai#7041)

* fix(browser): restore programmatic focus for CDP text insertion

* test(browser): cover the DOM focus replay error path

* fix(browser): serialize DOM.focus replay against pipelined Input.insertText

* refactor(browser): consolidate pending-focus invalidation into one guard

Collapse the three per-handler deletes (Page.bringToFront, Page.captureScreenshot,
catch-all) of the pending DOM.focus replay into a single guarded delete keyed on
'not DOM.focus and not Input.insertText'. States the invariant in one place and
removes the trap where a future early-returning handler forgets to clear the
stale focus. Also clear the map on client teardown and shorten the field comment.

Co-authored-by: Orca <[email protected]>

* test(browser): annotate mock webContents return type for portable declaration emit

Co-authored-by: Orca <[email protected]>

* fix(browser): drop pending focus replay when the client disconnects mid-flight

Co-authored-by: Orca <[email protected]>

* fix(browser): re-check active client after DOM.focus replay round-trip

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Neil <[email protected]>
Co-authored-by: Orca <[email protected]>
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.

3 participants