Skip to content

Fix iOS BlazorWebView callbacks after disconnection - #39430

Merged
kubaflo merged 1 commit into
dotnet:inflight/currentfrom
sheiksyedm:fix/blazorwebview-ios-disconnect-34407
Oct 19, 2026
Merged

kubaflo merged 1 commit into
dotnet:inflight/currentfrom
sheiksyedm:fix/blazorwebview-ios-disconnect-34407

Conversation

@sheiksyedm

Copy link
Copy Markdown
Contributor

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!

Description of Change

Navigating away from a BlazorWebView during initialization can leave queued native callbacks running after its handler has disconnected.

  • Ignore late scheme requests when the web view manager is unavailable, including when request interception disconnects the handler.
  • Cancel late navigation callbacks before accessing the detached virtual view.
  • Add iOS/Mac Catalyst device regression tests for both callback paths and disconnection during interception.

Reproduced the reported null-reference crash in Sandbox before applying the fix. Afterward, Sandbox completed 20 navigation cycles without either lifecycle exception.

Issues Fixed

Fixes #34407

Ignore late resource requests after the web view manager is disconnected and cancel navigation callbacks after the virtual view is detached. Add device regressions for late requests, reentrant disconnection, and late navigation.

Fixes dotnet#34407.
Copilot AI balanced review requested due to automatic review settings October 16, 2026 15:16
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 39430

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 39430"

@sheiksyedm sheiksyedm added the community ✨ Community Contribution label Oct 16, 2026
@dotnet-policy-service dotnet-policy-service Bot added the partner/syncfusion Issues / PR's with Syncfusion collaboration label Oct 16, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@github-actions github-actions Bot added area-blazor Blazor Hybrid / Desktop, BlazorWebView platform/ios platform/macos macOS / Mac Catalyst labels Oct 16, 2026

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

Native lifecycle changes need human review supported by verified passing iOS/Mac Catalyst device-test results.

0 open findings

What changed in this PR

Addresses #34407 by guarding iOS/Mac Catalyst BlazorWebView callbacks after handler disconnection.

Changes:

  • Ignore scheme requests when the web view manager is unavailable.
  • Cancel navigation callbacks when the virtual view is detached.
  • Add device regression tests for late callbacks and disconnection during interception.
File Description
src/​BlazorWebView/​tests/​DeviceTests/​Elements/​BlazorWebViewTests.Disconnection.iOS.cs Adds three disconnection regression tests.
src/​BlazorWebView/​src/​Maui/​iOS/​IOSWebViewManager.cs Cancels navigation after disconnection.
src/​BlazorWebView/​src/​Maui/​iOS/​BlazorWebViewHandler.iOS.cs Guards manager access during scheme requests.

🧠 Review effort: Balanced

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Oct 16, 2026
@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

/review gate was not started: another review or Gate is already running for this PR.

This command is not queued. Submit it again after the current run finishes.

@kubaflo

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

/review gate was not started: another review or Gate is already running for this PR.

This command is not queued. Submit it again after the current run finishes.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

AI Review Summary

@sheiksyedm — new AI review results are available based on commit 347c4bd.

Gate Inconclusive Confidence Low Platform iOS


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ⚠️ INCONCLUSIVE

Platform: IOS · Base: main · Merge base: 3a7d7287

🩺 Could not verify — environment/infrastructure error. The gate ran the tests but hit an environment error (an emulator/simulator/Appium/XHarness flake, a device that would not boot, or an empty/invalid result file), so it could not record a real pass/fail. The ⚠️ ENV ERROR marks below are infrastructure, not test failures — this is not a problem with your PR. Comment /review to retry on a fresh agent.

XHarness did not produce the expected fresh result 'testResults.xml' for requested class(es) 'Microsoft.Maui.MauiBlazorWebView.DeviceTests.Elements.BlazorWebViewTests' (the target tests did not run).

Test Without Fix (expect FAIL) With Fix (expect PASS)
📱 BlazorWebViewTests (SchemeRequestsAfterDisconnectionAreIgnored, SchemeRequestsDisconnectingDuringInterceptionAreIgnored, NavigationAfterDisconnectionIsCancelled) Category=BlazorWebView ⚠️ ENV ERROR ⚠️ ENV ERROR
🔴 Without fix — 📱 BlazorWebViewTests (SchemeRequestsAfterDisconnectionAreIgnored, SchemeRequestsDisconnectingDuringInterceptionAreIgnored, NavigationAfterDisconnectionIsCancelled): ⚠️ ENV ERROR · 238s

No log file found

🟢 With fix — 📱 BlazorWebViewTests (SchemeRequestsAfterDisconnectionAreIgnored, SchemeRequestsDisconnectingDuringInterceptionAreIgnored, NavigationAfterDisconnectionIsCancelled): ⚠️ ENV ERROR · 104s

No log file found

⚠️ Failure Details

  • ⚠️ BlazorWebViewTests (SchemeRequestsAfterDisconnectionAreIgnored, SchemeRequestsDisconnectingDuringInterceptionAreIgnored, NavigationAfterDisconnectionIsCancelled) without fix: XHarness did not produce the expected fresh result 'testResults.xml' for requested class(es) 'Microsoft.Maui.MauiBlazorWebView.DeviceTests.Elements.BlazorWebViewTests' (the target tests did not run).
  • ⚠️ BlazorWebViewTests (SchemeRequestsAfterDisconnectionAreIgnored, SchemeRequestsDisconnectingDuringInterceptionAreIgnored, NavigationAfterDisconnectionIsCancelled) with fix: XHarness did not produce the expected fresh result 'testResults.xml' for requested class(es) 'Microsoft.Maui.MauiBlazorWebView.DeviceTests.Elements.BlazorWebViewTests' (the target tests did not run).
📁 Fix files reverted (2 files)
  • src/BlazorWebView/src/Maui/iOS/BlazorWebViewHandler.iOS.cs
  • src/BlazorWebView/src/Maui/iOS/IOSWebViewManager.cs

📋 Pre-Flight — Context & Validation

Pre-Flight Context

Reported problem

The exact PR title, description, linked issue, and discussion are unknown because the read-only PR/issue endpoints returned a transport error. Based on the submitted diff and test names, the reported scenario is late or reentrant iOS WebKit callbacks after a BlazorWebView handler has disconnected:

  • A custom app:// scheme request can continue after _webviewManager has been cleared, reaching a null-forgiving dereference.
  • Disconnection can occur reentrantly while WebResourceRequested is being intercepted.
  • A retained WKNavigationDelegate can receive a navigation callback after the handler no longer has a VirtualView.

The intended behavior encoded by the patch is to ignore disconnected scheme requests and explicitly cancel disconnected navigation requests rather than processing torn-down state.

Changed files and mechanism

File Change
src/BlazorWebView/src/Maui/iOS/BlazorWebViewHandler.iOS.cs Before resolving a Blazor resource, snapshots _webviewManager with a null guard. If disconnected, logs a debug message and returns without invoking any IWKUrlSchemeTask completion callback. Passes the captured manager into GetResponseBytes, replacing the existing _webviewManager! field dereference.
src/BlazorWebView/src/Maui/iOS/IOSWebViewManager.cs At the beginning of WebViewNavigationDelegate.DecidePolicy, checks the retained handler’s IViewHandler.VirtualView. If null, invokes the decision callback with WKNavigationActionPolicy.Cancel and returns. Adds using Microsoft.Maui for IViewHandler.
src/BlazorWebView/tests/DeviceTests/Elements/BlazorWebViewTests.Disconnection.iOS.cs Adds three iOS device tests covering scheme requests after disconnection, reentrant disconnection during interception, and navigation after disconnection.

Relevant indexed baseline source confirms that:

  • _webviewManager is nullable.
  • The pre-change resource path dereferences it with _webviewManager!.
  • The disconnect path stops WebKit loading and contains a lifecycle path that sets _webviewManager = null.
  • IOSWebViewManager.InitializeWebView installs a WebViewNavigationDelegate that retains the BlazorWebViewHandler.
  • The existing startup-test helper creates a BlazorWebViewHandler and exposes both it and its platform WKWebView to the test callback.

The new local-manager parameter also avoids rereading the nullable field after the guard. It does not, by itself, establish whether disposal can overlap use of the captured manager.

Platform-sensitive paths

  • The requested validation platform is iOS.
  • The implementation directly exercises WKWebView, WKNavigationDelegate, IWKUrlSchemeTask, NSUrlRequest, and native callback lifetimes.
  • Disconnection during WebResourceRequested is a reentrancy-sensitive path: the new manager guard intentionally occurs after interception and before internal resource resolution.
  • The navigation fix depends on VirtualView becoming null as part of the handler-disconnection contract. The shared handler implementation could not be retrieved before GitHub code-search rate limiting, so that contract remains unconfirmed in this context.
  • By repository filename conventions, .iOS.cs sources may also compile for Mac Catalyst. Whether this test project includes and executes the new test on Mac Catalyst is unknown; the specified validation requirement remains iOS.
  • Existing delegate retention and disposal behavior beyond the retrieved snippets is unknown.

Validation requirements

The gate is inconclusive: tests could not be built or run because of a build or environment error. The change is therefore unverified, but this is not evidence that the fix fails.

Later iOS validation should establish that:

  1. A scheme task started after disconnection receives no response, data, finish, or failure callback and does not throw.
  2. Disconnection from inside WebResourceRequested is observed before internal resource resolution, with no scheme-task completion callback or exception.
  3. A late navigation invokes its decision callback exactly once with Cancel and does not throw.
  4. Normal connected scheme handling, resource interception, and navigation policy behavior remain unchanged.
  5. The tests build for the actual iOS device-test target represented by $(MauiDeviceTestsPlatforms) and run through the repository’s device-test infrastructure.

Remaining uncertainties

  • Exact user-visible symptoms, exception type/stack, reproduction steps, linked issue, affected versions, PR base/head metadata, author rationale, comments, and review discussion are unknown because PR context retrieval was unavailable.
  • The build/environment error behind the gate was not provided.
  • It is unknown whether returning from StartUrlSchemeTask without completing or failing the native scheme task has lifecycle consequences beyond those asserted by the new tests.
  • The submitted tests cover disconnection before manager lookup, including reentrant disconnection during interception; they do not visibly cover disconnection or disposal after the manager has been captured but before or during TryGetResponseContentInternal.
  • Mac Catalyst compilation and runtime coverage are unknown.
  • This is context gathering from the submitted diff and limited relevant source, not an exhaustive code review or a determination between competing approaches.

🔬 Code Review — Deep Analysis

Expert Review — Submitted PR Fix

Verdict: NEEDS_DISCUSSION
Confidence: low
Inline findings: 0

Independent Assessment

The submitted fix hardens two iOS WebKit callback paths against handler disconnection:

  • BlazorWebViewHandler.iOS.cs checks and captures _webviewManager after request interception, then passes the captured manager into GetResponseBytes. This prevents a late or reentrant disconnect from reaching the former _webviewManager! field dereference.
  • IOSWebViewManager.cs checks the retained handler's IViewHandler.VirtualView before navigation-policy processing. A disconnected handler completes the native decision callback once with WKNavigationActionPolicy.Cancel and returns.
  • BlazorWebViewTests.Disconnection.iOS.cs adds focused coverage for a scheme request after disconnect, disconnect during interception, and a navigation callback after disconnect.

The expert review found no concrete defect on an added or modified line. The required inline-findings.json therefore contains an empty JSON array.

Source and Test Evidence

Mechanism Evidence Assessment
Late scheme request BlazorWebViewHandler.iOS.cs:287-294 guards and captures the manager after interception Prevents the disconnected-field null dereference and observes reentrant disconnection
Stable manager use BlazorWebViewHandler.iOS.cs:321 accepts the captured IOSWebViewManager Avoids rereading the nullable handler field after the guard
Late navigation IOSWebViewManager.cs:269-273 calls the decision handler with Cancel and immediately returns Avoids detached VirtualView access while preserving exactly-once completion on the new branch
Scheme regression coverage BlazorWebViewTests.Disconnection.iOS.cs:13-44 Covers disconnect before callback processing and during request interception
Navigation regression coverage BlazorWebViewTests.Disconnection.iOS.cs:46-65 Verifies cancellation and callback invocation after disconnect

Failure-Mode Probing

  • Disconnect during interception: the manager guard runs after the user interception callback, so a reentrant disconnect is observed before internal resource resolution.
  • Disconnect after manager capture: the local capture removes the nullable field reread. No concrete unsafe use of the captured manager was established from the reviewed lifecycle.
  • Late navigation after detach: the new guard cancels before code accesses the detached virtual view.
  • Callback multiplicity: the new disconnected navigation branch invokes decisionHandler once and returns; no second invocation is reachable on that branch.
  • Normal connected operation: both guards fall through to the existing behavior when the manager and virtual view remain available.

Blast Radius and Validation

The behavior is localized to iOS/Mac Catalyst BlazorWebView callback plumbing; it does not add static or startup state. Confidence remains low because the trusted Gate was inconclusive after a build/environment error and the submitted regression tests were not executed. This is missing validation evidence, not evidence that the fix fails.

Refinement Decision

No pr-plus-reviewer refinement is authorized. The expert findings identify neither a concrete actionable defect nor an unresolved behavioral mechanism backed by source/test evidence. Routine Try-Fix was intentionally not requested.


🛠️ Try-Fix — Analysis & Comparison

Alternative generation: not requested

Evidence-first mode intentionally omits routine Try-Fix attempts. This is not a failed
attempt, a completed alternative search, or evidence that alternatives have no value.
The expert review may still produce one evidence-backed PR refinement.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the description accurately preserves the implementation and validation details, but the title should use the repository's platform-and-component format.

Recommended title

[iOS] BlazorWebView: Guard native callbacks after disconnection

Recommended description

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!!
-->

### Description of Change

Navigating away from a BlazorWebView during initialization can leave queued native callbacks running after its handler has disconnected.

- Ignore late scheme requests when the web view manager is unavailable, including when request interception disconnects the handler.
- Cancel late navigation callbacks before accessing the detached virtual view.
- Add iOS/Mac Catalyst device regression tests for both callback paths and disconnection during interception.

Reproduced the reported null-reference crash in Sandbox before applying the fix. Afterward, Sandbox completed 20 navigation cycles without either lifecycle exception.

### Issues Fixed

Fixes #34407

<!--
Are you targeting main? All PRs should target the main branch unless otherwise noted.
-->

🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Phase Status

Phase Status Notes
Pre-Flight ✅ COMPLETE Trusted evidence-first context consumed
Expert Review NEEDS_DISCUSSION (low confidence) 0 errors, 0 warnings, 0 inline findings; validation remains undetermined
Gate ⚠️ INCONCLUSIVE iOS tests could not be built or run because of a build/environment error; this is not a test failure
Try-Fix not requested Evidence-first mode intentionally omitted routine alternative generation
Refinement NOT GENERATED No source- or test-backed actionable defect met the refinement threshold
Report ✅ COMPLETE Compared only the real submitted candidate

Code Review and Candidate Comparison

The raw pr fix is the sole implemented candidate. The expert review found its lifecycle guards coherent: the scheme path observes disconnection after request interception and uses a captured manager, while the navigation path cancels and returns before accessing a detached virtual view. The added tests directly exercise both late callback paths, including reentrant disconnection during interception.

No concrete actionable defect or unresolved behavioral mechanism justified a pr-plus-reviewer patch, and routine Try-Fix alternatives were intentionally not requested. The raw pr therefore wins the candidate comparison. It cannot be recommended for approval in this run because the trusted Gate is inconclusive and the expert verdict remains NEEDS_DISCUSSION with low confidence until the submitted iOS regression tests are built and executed. This records missing evidence rather than treating the fix as failing.

Summary

The submitted change is localized and technically sound on source inspection, with no expert inline findings. Approval is withheld because the required runtime evidence is unavailable, not because a code defect was established.

Root Cause

Native WebKit callbacks can outlive the connected BlazorWebView handler. A scheme request could continue after request interception had reentrantly disconnected the handler and cleared _webviewManager, while a retained navigation delegate could process a callback after the handler's VirtualView had detached.

Fix Quality

The fix guards both stale callback paths at their point of use, preserves normal connected behavior, and completes a disconnected navigation decision exactly once with Cancel. Its focused iOS/Mac Catalyst device tests cover the reported lifecycle transitions, but the Gate's build/environment blocker means those regressions remain unvalidated in this run.


🔗 Regression Cross-Reference

🔍 Regression Cross-Reference

⚠ Overlaps with prior bug-fix PRs — same files modified, but no exact line revert detected.

File Fix PR Fixed issue(s)
src/BlazorWebView/src/Maui/iOS/BlazorWebViewHandler.iOS.cs #39247 #39227

🧭 Next Steps — review latest findings

No alternative fix was selected for this run. Review the session findings and CI results before merging.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Oct 16, 2026

@github-actions github-actions 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.

Expert Review — 0 findings

Reviewed commit 347c4bd.

@kubaflo
kubaflo requested a balanced review from Copilot October 16, 2026 22:52
This was referenced Nov 16, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 19, 2026

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 347c4bdc Deployed Oct 16, 2026 by sheiksyedm via conclusion #2379
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-blazor Blazor Hybrid / Desktop, BlazorWebView community ✨ Community Contribution partner/syncfusion Issues / PR's with Syncfusion collaboration platform/ios platform/macos macOS / Mac Catalyst s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BlazorWebViewHandler.iOS.cs NullReferenceException when web view has been disconnected

4 participants