Skip to content

fix(webview2): guard Focus() until controller initialisation completes - #5568

Merged
leaanthony merged 4 commits into
masterfrom
fix/webview2-focus-race-5446
Jun 13, 2026
Merged

leaanthony merged 4 commits into
masterfrom
fix/webview2-focus-race-5446

Conversation

@leaanthony

@leaanthony leaanthony commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

Description

Fixes the production startup crash from #5446 (successor to the partial #4835 fix).

CreateCoreWebView2ControllerCompleted assigns e.controller partway through the callback (chromium.go:338) but only flips the inited atomic after all COM setup succeeds (line 389). The Windows message pump runs during that window, so the WndProc can dispatch WM_SETFOCUS re-entrantly and reach Chromium.Focus() while the controller is non-nil but partially configured. The v3-side GetController() != nil guards (added for #4835) pass, MoveFocus fails with E_INVALIDARG ("The parameter is incorrect"), and errorCallback exits the process. With no controller at all, Focus() dereferenced nil.

Fix

  • Add Chromium.IsReady() — atomic load of inited, the flag that already means "fully initialised".
  • Focus() becomes a no-op until IsReady(). Dropping a focus request during startup is harmless (the window manager re-delivers focus on interaction); calling into a partially-initialised controller is fatal.

Guarding inside Focus() makes every call site safe — including the four TOCTOU-shaped GetController() != nil → Focus() patterns in v3's webview_window_windows.go — without v3 code changes. Once this ships in a webview2 release, the existing bump-webview2-v3 automation picks it up; the v3 call sites can optionally migrate to IsReady() afterwards as a cleanup.

Verification (win-node1, windows/amd64, go1.26.2)

  • Negative control: a Focus-before-init probe against unfixed chromium.go crashes with MoveFocus(0x0, …) nil-pointer panic — the reported failure mode.
  • With the fix: TestFocusBeforeControllerReady and TestFocusBeforeControllerReadyConcurrent (16 goroutines × 1000 iterations) pass; full pkg/edge suite passes; go vet clean for the changed file (remaining warnings are pre-existing COM interop patterns).

Fixes #5446

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Checklist:

  • My code follows the general coding style of this project
  • I have added tests that prove my fix is effective

Summary by CodeRabbit

  • Bug Fixes

    • Focus requests during controller startup are safely ignored to prevent errors or crashes.
    • Focus failures after initialization are logged instead of terminating the process.
    • Script execution failures that previously caused termination are now treated as recoverable and logged.
  • Tests

    • Added Windows-only tests confirming focus is a safe no-op before initialization, including concurrent stress tests.

The WndProc can dispatch WM_SETFOCUS re-entrantly while
CreateCoreWebView2ControllerCompleted is still configuring the
controller: e.controller is assigned partway through the callback, but
inited only flips after all COM setup succeeds. In that window
GetController() != nil checks at call sites pass, yet MoveFocus fails
with E_INVALIDARG and errorCallback exits the process. With no
controller at all, Focus() dereferenced nil.

Add IsReady() (atomic load of inited) and make Focus() a no-op until it
reports true. Dropping a focus request during startup is harmless; the
window manager re-delivers focus once the user interacts with the
window.

Fixes #5446
Copilot AI review requested due to automatic review settings June 10, 2026 22:03
@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 516c1ce7-c7f0-4728-96d9-768a692da2c4

📥 Commits

Reviewing files that changed from the base of the PR and between 72d1c45 and 28559e9.

📒 Files selected for processing (1)
  • webview2/pkg/edge/chromium.go

Walkthrough

Chromium gains an IsReady() method that reports initialization completion via the inited flag. Eval and Focus() now log recoverable failures instead of invoking the fatal error callback; Focus() returns immediately when not ready. Two Windows-only tests validate safe no-op behavior before readiness, including a concurrent stress test.

Changes

Focus readiness guard and initialization safety

Layer / File(s) Summary
IsReady, Eval, and Focus guard implementation
webview2/pkg/edge/chromium.go
Adds IsReady() to atomically report inited; changes Eval to log non-ERROR_IO_PENDING ExecuteScript failures instead of calling errorCallback; updates Focus() to return early when !IsReady() and to log.Printf MoveFocus errors instead of invoking the fatal error callback.
Focus pre-readiness test coverage
webview2/pkg/edge/chromium_focus_test.go
Adds TestFocusBeforeControllerReady and TestFocusBeforeControllerReadyConcurrent (Windows-only) to assert that pre-init Focus() calls are safe no-ops and resilient under concurrent calls.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • wailsapp/wails#5315: Both PRs prevent fatal WebView2 Focus() failures during pre-controller initialization by changing Chromium focus behavior to no-op/early-return when the controller isn’t ready and by avoiding invoking the fatal error callback on such errors.

Suggested labels

reviewed ✅

Poem

🐰 Hopping soft through startup's haze,
I check the flag before the gaze.
If inited sleeps, I wait my turn,
No crash, no call, no bridge to burn.
A tiny guard, a safer run!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.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 accurately reflects the main changes: adding a guard to prevent Focus() calls until the controller is fully initialized.
Description check ✅ Passed The description comprehensively explains the bug, fix, and verification, though missing some template sections like test configuration and platform coverage checkboxes.
Linked Issues check ✅ Passed The changes address all requirements from #5446: preventing TOCTOU race via IsReady() guard, making Focus() safe without v3 changes, and treating focus errors as non-fatal. Tests verify the fix handles both startup re-entrancy and concurrent access.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing the #5446 focus race: IsReady() method, Focus() guard, error handling changes, and two new tests. The Eval non-fatal change is a supporting improvement mentioned in PR objectives.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/webview2-focus-race-5446

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


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 and usage tips.

Copilot AI 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.

Pull request overview

This PR fixes a Windows WebView2 startup crash caused by Focus() being called re-entrantly (e.g., via WM_SETFOCUS) while the WebView2 controller exists but has not finished COM setup. It does this by introducing a readiness check based on the existing inited atomic flag and making Focus() a safe no-op until initialization is fully complete.

Changes:

  • Add (*Chromium).IsReady() which reports full controller initialization by atomically reading inited.
  • Guard (*Chromium).Focus() so it returns early unless IsReady() is true, preventing calls into a partially configured controller.
  • Add Windows-only tests to assert Focus() is safe before readiness, including a concurrent stress test.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
webview2/pkg/edge/chromium.go Adds IsReady() and uses it to guard Focus() until controller initialization is fully complete.
webview2/pkg/edge/chromium_focus_test.go Adds regression tests for calling Focus() before controller readiness (single-threaded + concurrent).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

MoveFocus can fail after initialisation too: E_INVALIDARG when the
window is hidden or minimised to the tray (#4158
reproduces this 100% on tray-click restore). Routing that error
through errorCallback exits the process. Log it instead — a failed
focus request is never worth killing the application.
@leaanthony

Copy link
Copy Markdown
Member Author

Scope update: while triaging #4158 (same crash signature, reported a year earlier) a commenter provided a 100% reproducible variant: minimize to tray → click the tray icon → instant crash. That path fails after initialisation — MoveFocus returns E_INVALIDARG for a hidden/tray-minimised window — so the IsReady() guard alone doesn't cover it.

Added one commit: Focus() no longer routes MoveFocus errors through errorCallback (which exits the process); a failed focus request is logged instead. Between the init guard and the non-fatal error path, both the startup race (#5446) and the tray-restore crash (#4158) are covered. Build + focus tests re-verified on win-node1.

ExecuteScript fails transiently while the browser process reconfigures,
e.g. RESOURCE_NOT_IN_CORRECT_STATE during a DPI transition when the
window is dragged between mixed-DPI monitors (#5544
verification). Script execution is fire-and-forget: dropping a script
during a transition is recoverable, exiting the process is not. Log
instead, matching the Focus change.
@leaanthony

Copy link
Copy Markdown
Member Author

Scope addition from #5544's verification: dragging a window between mixed-DPI monitors exposed that Eval also routes transient COM errors (RESOURCE_NOT_IN_CORRECT_STATE during the DPI transition) through the fatal errorCallback. Same disease, same cure as Focus: fire-and-forget script execution now logs failures instead of exiting the process. Build + edge suite re-verified on win-node1.

@leaanthony
leaanthony merged commit 960065c into master Jun 13, 2026
14 of 16 checks passed
@leaanthony
leaanthony deleted the fix/webview2-focus-race-5446 branch June 13, 2026 03:15
leaanthony added a commit that referenced this pull request Jun 21, 2026
The resync added a w.chromium.IsReady() guard, but IsReady() exists only
in unreleased webview2 source (added in #5568) — it is not in the webview2
module version v3 pins (v1.0.24), so it fails to cross-compile and would
break end-user builds. The guard was defense-in-depth only; the real #5605
protection is the DPI-change gate, and the existing GetController()==nil
check still covers the unavailable-controller case. Re-add the IsReady guard
once a webview2 release including it lands and v3's go.mod is bumped.
leaanthony added a commit that referenced this pull request Jun 21, 2026
)

* ci(webview2): auto-release on webview2 source changes to master

Add a push trigger (branches: master, paths: webview2/**) to the existing
Release webview2 workflow so any change to the webview2 module cuts a new
patch tag automatically, then the existing bump-webview2-v3 opens the v3
go.mod bump PR. Prevents the gap where webview2 source gains an API (e.g.
IsReady() in #5568) that v3 cannot use because no release was cut (see #5616).

Loop-safe: the release pushes a tag (not a master commit) and the bump only
edits v3/**, so neither re-triggers this workflow. Adds a concurrency group
to serialise near-simultaneous releases.

* fix(ci): strip leading v in webview2 auto-increment to avoid vv tag

The auto-increment path derived MAJOR from "v1.0.24" as "v1" and then
prefixed another v, producing webview2/vv1.0.25. Stripping the leading v
(webview2/v prefix) yields the correct webview2/v1.0.25. This path becomes
the default once the push trigger fires, so it must be correct.
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.

[v3] (*Chromium).Focus race on production startup — #4835 fix has TOCTOU window

2 participants