Skip to content

[Windows] Propagate HybridWebView initialization failures and bound device-test waits - #40818

Merged
kubaflo merged 2 commits into
mainfrom
fix-hybridwebview-ready
Nov 29, 2026
Merged

kubaflo merged 2 commits into
mainfrom
fix-hybridwebview-ready

Conversation

@kubaflo

@kubaflo kubaflo commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 3eec8791098beea08fbb2e411202fb58d7d1c435

Dimension Assessment Rationale
Change confidence 8/10 ↑ Final-head device-test build 1704477 succeeded; HybridWebView passed in both Windows modes (104 passed, 4 skipped each). All three regression tests executed in the unpackaged log. The existing polling harness passes 3/3 locally.
↓ Two successful runs per mode cannot eliminate an intermittent native initialization failure.
Diagnosis confidence 7/10 ↑ WinUI catches controller-creation errors and reports them through CoreWebView2Initialized, so EnsureCoreWebView2Async can complete with a null core; the old false-result path drops JavaScript requests.
↓ Build 1704369 did not record the native error; teardown/shared-environment causality is not established.
Evidence fit 8/10 ↑ Raw logs in builds 1704453 and 1704477 confirm four passing Windows HybridWebView category executions, including the previously stalled Invoke_NoParam_ReturnTaskComplex and focused failure-path tests.
↓ This is bounded-failure protection and improved diagnostics, not proof that the underlying native failure has been eliminated.

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Target Branch

This PR is for Initial base
New features, API changes, or .NET 12 work (including .NET 12 fixes) main
.NET 11 servicing fixes net11, for review
Older servicing, release integration, infrastructure, or documentation The branch designated for that work

For .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into net11; agents must not retarget or merge.

Description of Change

Follow-up to #40796, not a revert. Keep the null-core guard, but distinguish a disconnected handler from an initialization failure:

  • Capture the native error from CoreWebView2Initialized, fault the ready task, and retain the error as the inner exception.
  • Propagate failed initialization (including a false ready result) to EvaluateJavaScriptAsync instead of abandoning its completion source.
  • Log failures in fire-and-forget navigation/raw-message operations without an unhandled dispatcher exception.
  • Do not navigate or subscribe events for a disconnected or replaced platform view after asynchronous initialization.
  • Bound HybridWebView page/status polling, including an individual JavaScript evaluation that never completes. Bound test operations separately.
  • Add three focused regression cases for faulted initialization, false initialization, and a stalled polling evaluation. Adapt the existing source-polling Pester harness to the helper's internal visibility and cancellation-token dependency.

Evidence: build 1704369, raw log 836, Windows controls unpackaged. Last TEST_START at 18:05:48Z is Invoke_NoParam_ReturnTaskComplex; no further test progress precedes the task timeout at 19:47:16Z. Packaged passed in that build; the six preceding supplied builds passed HybridWebView in both Windows jobs. This is one occurrence, not proof that #40796 caused the underlying native failure.

Why a null core does not prove teardown: WinUI WebView2.cpp, CreateCoreWebViewFromEnvironment, catches hresult_error, fires CoreWebView2Initialized(hr), and completes its coroutine. EnsureCoreWebView2Async awaits that operation. No native HRESULT was recorded in the failing run, so this PR exposes it rather than guessing at an environment workaround or adding blind retries.

Duplicate check: searched open/recent PRs for HybridWebView Windows, EnsureCoreWebView2Async, and CoreWebView2 null. #40796/#40771 add the valid null guard; #38569 handles regular WebView; #36742 fixes a memory-test initialization wait. No open duplicate addressing HybridWebView failure propagation and bounded waits was found.

Validation

  • git diff --check — passed.
  • dotnet format Microsoft.Maui.sln --no-restore --include src/Core/src/Handlers/HybridWebView/HybridWebViewHandler.Windows.cs src/Core/src/Platform/Windows/MauiHybridWebView.cs src/Controls/tests/DeviceTests/Elements/HybridWebView/HybridWebViewTestsBase.cs src/Controls/tests/DeviceTests/Elements/HybridWebView/HybridWebViewTests_EvaluateJavaScriptAsync.cs src/Controls/tests/DeviceTests/Elements/HybridWebView/HybridWebViewTests_EvaluateJavaScriptAsync.Windows.cs --exclude Templates/src --exclude-diagnostics CA1822 --verbosity quiet — completed successfully; formatting, not Windows compilation.
  • pwsh -NoProfile -Command '$c = New-PesterConfiguration; $c.Run.Path = "./eng/devices/Direct-TestDevice.Tests.ps1"; $c.Filter.FullName = "HybridWebView startup polling budget*"; $c.Run.Exit = $true; $c.Output.Verbosity = "Detailed"; Invoke-Pester -Configuration $c' — passed, 3/3.
  • Windows tests are not run locally (macOS host). Requested /azp run maui-pr-devicetests.
  • Final-head build 1704477 succeeded. Its tested merge b5b01d2dc0a35d5763f3e108f320ebfc0ce7e0ad has PR head 3eec8791098beea08fbb2e411202fb58d7d1c435 as a parent. Both Windows controls jobs succeeded. Packaged raw log 777 and unpackaged raw log 747 each report HybridWebView 104 succeeded / 0 failed / 4 skipped. Unpackaged logs show the three new tests at 20:58:15–17Z and Invoke_NoParam_ReturnTaskComplex at 20:59:08Z, followed by the successful summary at 20:59:53Z. Packaged completes the category at 21:01:07Z.
  • Build 1704453, product/test revision 49ef2ab01b92e20a7b6115a87323241761d04e4f: packaged raw log 747 and unpackaged raw log 771 each report HybridWebView 104 succeeded / 0 failed / 4 skipped. The entire build failed because unpackaged Entry failed UnFocusOnEntryAfterPagePop (EntryTests.cs:186); no Entry code was changed. Entry passes in the final-head build.
  • First admission 1704451 was canceled before execution. Each requested run needed a second /azp run maui-pr-devicetests comment before admission.
  • Full Pester on the first revision failed: three source-polling tests were directly affected by the extraction signature and are now repaired/locally validated. Other reported release/pipeline/model-policy failures concern files outside this diff. The overall PR still has a failing Pester check; no claim that every required check is green.

Two successful runs in each Windows mode are useful evidence, not proof against a rare recurrence. The underlying native initialization error remains unknown.

Issues Fixed

Relates to #40796. Addresses the Windows HybridWebView device-test hang in build 1704369; no separate issue has been filed.

Let AI finish this PR

  • Let the MAUI agent address review feedback and fix remaining issues on this PR. Maintainers still decide whether it is merged. For PRs from forks, the agent opens a follow-up PR that keeps your commits.

…d test waits

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 29, 2026 20:04
@kubaflo

kubaflo commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

@dalexsoto stamp

@kubaflo

This comment has been minimized.

@kubaflo
kubaflo temporarily deployed to copilot-pat-pool November 29, 2026 20:04 — with GitHub Actions Inactive
@github-actions

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@kubaflo

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

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.

🟡 Changes recommended

The new Windows tests bypass native initialization-error handling, leaving exception capture and inner-exception preservation without regression coverage.

1 open issue
What changed in this PR

This follow-up to #40796 improves Windows HybridWebView failure handling in .NET MAUI and bounds device-test waits so stalled JavaScript operations can fail rather than hang indefinitely.

Changes:

  • Propagates initialization failures to JavaScript evaluation tasks, logs fire-and-forget failures, and guards against stale initialization continuations.
  • Adds deadlines for page readiness, status polling, and test operations.
  • Adds regression tests for faulted/false readiness tasks and stalled polling, plus troubleshooting documentation.
File Description
src/​Core/​src/​Platform/​Windows/​MauiHybridWebView.cs Validates initialization and logs fire-and-forget failures.
src/​Core/​src/​Handlers/​HybridWebView/​HybridWebViewHandler.Windows.cs Captures native initialization errors, propagates evaluation failures, and adds lifecycle guards.
src/​Controls/​tests/​DeviceTests/​Elements/​HybridWebView/​HybridWebViewTestsBase.cs Bounds polling and test-operation waits.
src/​Controls/​tests/​DeviceTests/​Elements/​HybridWebView/​HybridWebViewTests_EvaluateJavaScriptAsync.Windows.cs Tests evaluation failures from faulted and false readiness tasks.
src/​Controls/​tests/​DeviceTests/​Elements/​HybridWebView/​HybridWebViewTests_EvaluateJavaScriptAsync.cs Tests timeout handling for a stalled polling evaluation.
docs/​DevelopmentTips.md Documents timeout budgets and Windows initialization diagnostics.

Review effort: Balanced

Comment on lines +368 to +370
if (initializationException is not null)
{
throw new InvalidOperationException("Failed to initialize HybridWebView's CoreWebView2.", initializationException);
…ed waits

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@kubaflo

kubaflo commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

@dalexsoto stamp

Copilot AI balanced review requested due to automatic review settings November 29, 2026 20:37
@kubaflo

This comment has been minimized.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines will not run the associated pipelines, because the pull request was updated after the run command was issued. Review the pull request again and issue a new run command.

@kubaflo

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

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.

🔵 Needs a closer look

The readiness helper can incorrectly time out after a successful predicate, and the Windows tests bypass native initialization-failure handling, leaving exception capture and propagation unverified.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Preserve readiness success when deadline expires during settling delay

src/​Controls/​tests/​DeviceTests/​Elements/​HybridWebView/​HybridWebViewTestsBase.cs:89

A readiness predicate that succeeds during the last 250 ms of its budget is still reported as a timeout: the following settling delay uses the same deadline token, so its cancellation falls through to createExceptionWithTimeoutMS even though tryAction returned true. This can reject a page that became ready within the advertised 60-second limit. Preserve success if the deadline expires during this post-success delay, while retaining the deadline for pending or false predicates.

Review effort: Balanced

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stamping as requested by @kubaflo; no code review performed.

@kubaflo

kubaflo commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

Validated final head 3eec879 in maui-pr-devicetests build 1704477 (succeeded). Raw logs 777 (packaged) and 747 (unpackaged) each show HybridWebView 104 passed, 0 failed, 4 skipped; both Windows controls jobs succeeded. Unpackaged logs explicitly show all three regression tests and Invoke_NoParam_ReturnTaskComplex executing. Previous build 1704453 also passed HybridWebView in both modes. Two passes per mode are encouraging, not proof against a rare native initialization failure. The PR body records the remaining Pester check separately. No merge or retarget performed.

@kubaflo
kubaflo merged commit 9f667bb into main Nov 29, 2026
57 of 71 checks passed
@kubaflo
kubaflo deleted the fix-hybridwebview-ready branch November 29, 2026 21:22
kubaflo added a commit that referenced this pull request Nov 30, 2026
…st (#40830)

<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `7ee8698e98df805214190e5d14220b08536ca648`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8/10 | ↑ Build 1704530 compiled the final head and
the exact test passed in packaged and unpackaged Windows TRX; native and
MAUI focus assertions remain.<br>↓ Only one CI run per mode; broader
packaged Controls job failed in a separate Shell host. |
| Diagnosis confidence | 7/10 | ↑ Builds 1704506 and 1704247 fail at the
final count assertion; source has unawaited UI dispatches, navigation
and reused/reset cross-phase signals.<br>↓ Original logs do not print
the actual event count or focus ordering, so they cannot rule out a
product issue. |
| Evidence fit | 8/10 | ↑ Raw logs 686 and 698 in build 1704530 report
Entry passed (54 passed, 4 skipped each); both genuine TRX files mark
the exact second-show test Passed.<br>↓ One run per mode is limited
positive evidence, not statistical proof of flake elimination. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it after CI validates that final base. Do not merge
individual
fixes into net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

<!-- Enter description of the fix in this section -->

Stabilize `[Entry] Unfocus will work when page is shown a 2nd time`
(`UnFocusOnEntryAfterPagePop`) on Windows without changing product focus
behavior or adding a delay.

**Evidence:** raw `maui-pr-devicetests` logs for [build
1704506](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704506)
(log 757) and [build
1704247](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704247)
(log 752) both report `Assert.True() Failure` at `EntryTests.cs:186`,
the final `unfocused == 2` assertion. These unrelated PRs reproduce the
same 439–441 ms failure. Neither log includes the actual count.

**Test race:** a worker thread fires and forgets UI dispatches. The
navigation dispatch unfocuses, pushes, pops, then focuses, while the
worker treats a reused `Focused` signal as proof that the entire
dispatch finished. A navigation-generated focus event can wake the
worker before the explicit final `Focus()`. It also resets shared
`Unfocused` signals while transitions remain in flight and reads a
UI-written event count on the worker thread. These signals do not
establish completion of either navigation or the intended focus cycle.

**Fix:** run the sequence on the existing UI-thread fixture, await each
native `FocusManager.GotFocus`/`LostFocus` signal subscribed before its
mutation, await `PushAsync` and `PopAsync`, and await the re-shown
Entry's loaded state. Check both MAUI `IsFocused` and native
`FocusManager.GetFocusedElement`, then assert exact counts after each
explicit unfocus. Existing native event waits have bounded timeouts and
remove subscriptions in `finally`. An actual failure to unfocus still
fails this test.

**Scope and limits:** the code establishes a concrete test sequencing
defect, not proof that WinUI can never have a product focus bug. No
product change is justified by the current logs. Search of open/recently
merged PRs across all bases (including release, inflight and net11)
found no duplicate. Related #40818 and #40805 mention this failure but
do not fix this test; #37428 and closed #38679 concern ScrollView
focus/retention.

**Validation:**
- `dotnet format Microsoft.Maui.sln --no-restore --include
src/Controls/tests/DeviceTests/Elements/Entry/EntryTests.cs --exclude
Templates/src --exclude-diagnostics CA1822 --verbosity quiet` — passed;
formatter-only changes outside this test were reverted.
- `git diff origin/main...HEAD --check` — passed.
- Windows device tests — not run locally (macOS host). `/azp run
maui-pr-devicetests` queued **[build
1704530](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704530)**,
validating merge `ea378b0a7b07dc9b17aed2021fa848a389d72ab0` whose second
parent is the assessed head above.
- **Windows controls unpackaged:** raw log **686**, `Category Entry:
passed`, **54 passed / 4 skipped / 0 failed**. Genuine
`categories/Entry/Controls-Entry.trx` marks the exact second-show test
**Passed (502 ms)**. Entire Controls job succeeded.
- **Windows controls packaged:** raw log **698**, `Category Entry:
passed`, **54 passed / 4 skipped / 0 failed**. Genuine
`categories/Entry/Controls-Entry.trx` marks the exact second-show test
**Passed (231 ms)**. The broader Controls job failed later in the
separate **Shell** category host (process exit 57005, MTP exit 7, 39
recovered passing results; last active test `Shell TabBar
UnselectedColor Initializes Correctly`). This is not an Entry failure;
this PR is **not claiming all CI green** or diagnosing that Shell crash.
- Both artifact TRX files were downloaded through the Azure artifact
archive API, not inferred from test attributes. This is one passing
execution per mode, limited positive evidence rather than statistical
proof of eliminating the flake.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

No separate issue; fixes the device-test failure documented by builds
1704506 and 1704247 above.

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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