Repository navigation
Conversation
…r/DragLeave (dotnet#40441) <!-- 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 directly there. 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 On iOS, `DragEventArgs.GetPosition()` can throw a `NullReferenceException` inside a `DragOver` or `DragLeave` handler. The exception crashes the app. **CI evidence.** The `DropEventCoordinates` UI test crashed the HostApp on both attempts on the iOS CoreCLR lane of SR2 candidate dotnet#40116 (maui-pr-uitests [1690394](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1690394), iOS latest Editor..Fr job). The job's `.ips` reports show SIGABRT from `xamarin_process_managed_exception` under `-[UIDropInteraction _dragDestinationGestureStateChanged:]`. The logarchive shows the managed exception: ``` System.NullReferenceException at DragAndDropDelegate.CalculatePosition(IElement, WeakReference, WeakReference) at DragAndDropBetweenLayouts.OnDragOver(...) // HostApp calls e.GetPosition(...) at DragAndDropDelegate.<HandleDragOver>... at DragAndDropDelegate.SendEventArgs(...) at DragAndDropDelegate.HandleDragOver(...) at DragAndDropDelegate.SessionDidUpdate(...) ``` **Root cause.** - `SessionDidUpdate` and `SessionDidExit` pass `session.LocalDragSession`, a transient managed wrapper of the native local drag session, into `HandleDragOver` and `HandleDragLeave`. - Those methods put only a `WeakReference` to it in the `GetPosition` callback, and nothing else on the path keeps it alive: `PlatformDragEventArgs` holds the outer `IUIDropSession`, not the local drag session. - A GC while the user's handler is running can therefore collect the wrapper. `CalculatePosition` then calls `LocationInView` on a null session. - Separately, `HandleDragOver` built a weak reference even when `LocalDragSession` is null (a drag from another app), so `GetPosition` always threw in that case. `HandleDragLeave` and `HandleDrop` already return null there. The weak references date from 2023, and the code is identical on `net11`, the candidate and `main`. This is a latent bug that the CoreCLR lane's GC timing exposed, not a candidate regression. **Fix** (`DragAndDropDelegate.cs`, iOS/Mac Catalyst): - `HandleDragOver` and `HandleDragLeave` call `GC.KeepAlive(session)` after dispatching to the recognizers. The session stays alive while handlers can synchronously call `GetPosition`, and the event args still don't hold it strongly. - `HandleDragOver` uses a null `sessionRef` when there is no local drag session, matching `HandleDragLeave` and `HandleDrop`. - `CalculatePosition` returns `null` when the session reference is missing or its target has already been collected, instead of dereferencing null. This covers a `GetPosition` call made after the handler returns. **Tests** (`DragAndDropTests.iOS.cs`, `Gesture` category): - `DragPositionIsAvailableAfterGarbageCollectionDuringHandler(dragLeave: false/true)`: a fake drop session returns a fresh local drag session wrapper each time, the handler forces a full GC and then calls `GetPosition`, and the test asserts the fake session's location. - `DragOverPositionIsNullWithoutLocalDragSession`: with no local drag session, `GetPosition` in `DragOver` returns `null`. **Validation** (iOS 18.5 simulator, Release, CoreCLR, the same runtime as the failing CI lane): | Command | Result | | --- | --- | | `pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -TestFilter "Category=Gesture" -DeviceUdid <iOS 18.5 sim> -SkipXcodeVersionCheck` with only the new tests (no fix) | **Failed**: 45 passed, 3 failed. All three new cases throw `NullReferenceException` at `DragAndDropDelegate.CalculatePosition`, the same frame as the CI crash. | | Same command with the fix | **Passed**: 48 passed, 0 failed | | `dotnet format whitespace --folder --include <changed files> --verify-no-changes` | Passed | The UI test itself was not rerun locally, because its crash depends on when a GC happens. ### Issues Fixed No existing issue; found while investigating SR2 candidate dotnet#40116 CI. Searched for related issues and PRs and found no duplicate. dotnet#28416/dotnet#28417 is an unrelated Mac Catalyst `DragAndDropDelegate` NRE. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Window.Destroying() disconnected the window's own handler but never the handlers of the pages it presents. When the next window gets a new page, the old page tree stayed connected: a BlazorWebView kept its WebViewManager, its components were never disposed, and their timers kept running next to the new instance. On Android that happens after every configuration change the activity does not handle, and after every Back on the root page followed by a relaunch, since Android keeps the process. Destroying() now calls DisconnectHandlers() on the modal pages and the page, which respects HandlerDisconnectPolicy.Manual. It runs after the window handler is disconnected, so the page's HandlerChanged cannot subscribe the alert manager again, and before the window scope is disposed, so handlers can still use it while they disconnect. Fixes dotnet#40056
An app that reuses one page instance can already have put it into a newer window when the old window is destroyed; disconnecting it then tore down the handlers of the window the user is looking at. Destroying() now disconnects only pages whose parent is still the destroyed window, and disposes the window scope in a finally block so a throwing handler cannot leave it behind.
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 40457Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 40457" |
|
Hey there @Kebechet! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
PR Test Gate
🧪 Gate analysis — click to expand⚠ Inconclusive. Setup, build, or execution did not produce a conclusive result. This does not prove the fix is incorrect. No interpretable test-group summary was produced. No additional test execution is inferred. Setup did not capture a verified PR head; no commit is claimed as tested. No immutable without-fix baseline was prepared. |
A modal page pushed onto one window stays in that window's modal stack after it is put into a newer window. Without the Parent check in Window.DisconnectPresentedPages, destroying the old window would disconnect the handlers the newer window now uses. Also link the issue from the two other destroy tests in WindowsTests.
This comment has been minimized.
This comment has been minimized.
PR Test Gate
🧪 Gate analysis — click to expand⚠ Inconclusive. Setup, build, or execution did not produce a conclusive result. This does not prove the fix is incorrect. No interpretable test-group summary was produced. No additional test execution is inferred. Setup did not capture a verified PR head; no commit is claimed as tested. No immutable without-fix baseline was prepared. |
There was a problem hiding this comment.
Expert Review — 0 findings
Reviewed commit a23b8bd.
0eb47dd
into
dotnet:candidate/11.0.1xx-sr2
… device tests (#40486) <!-- 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 directly there. 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). This is SR2 candidate integration work for #40116, so it targets `candidate/11.0.1xx-sr2`. #40457 was merged straight into the candidate (0eb47dd) and `net11` doesn't have it, so there is nothing to revert on `net11`. ### Description of Change This reverts #40457 ("Window: Disconnect page handlers when the window is destroyed"), which crashes the Controls device-test apps on Android, iOS and Windows and leaves MacCatalyst Controls device tests without results. #40457 changed `Window.Destroying()` to disconnect the handlers of the window's page and modal stack. Platform callbacks still run after `Destroying()`, and when they reach the now-disconnected handlers the process crashes: | Platform | Crash | Stack | | --- | --- | --- | | iOS (CoreCLR + Mono, iOS 18 and 26 queues), Controls.DeviceTests-General | `InvalidOperationException: Page cannot be null here` | `ControlsModalWrapper.UpdateBackgroundColor` ← `ControlsModalWrapper.ViewWillAppear` (the modal is dismissed after window teardown) | | iOS (CoreCLR + Mono), Controls.DeviceTests-Shell | `InvalidOperationException: VirtualView cannot be null here` | `ShellPageRendererTracker.Dispose` ← `ShellSectionHandler.DisposePage` ← `OnPopRequested` | | Android (CoreCLR + Mono), API 33 | `ArgumentNullException` for `context` | `ShellSectionRenderer.OnCreateView`. A pending fragment transaction runs after teardown, and `FindMauiContext()` returns null. | | Windows (packaged + unpackaged) | `0xc000027b`, faulting module `Microsoft.UI.Xaml.dll` | Process crash during the Controls device tests (attributed by mechanism; not reproduced locally) | | MacCatalyst (CoreCLR, osx.15 + osx.26) | No test results | osx.15 `Controls Tests` ran into the 3600 s XHarness timeout (exit 94, `TEST_RESULTS_MISSING`; the app was still alive). On osx.26 the app exited after about 6 minutes with no results file, and XHarness still reported success. Without #40457, both queues report 1636–1777 tests in about 12 minutes (8 runs in builds 1690816, 1692066, 1692670, 1692736). Attributed by correlation; not reproduced locally. | **CI** (`maui-pr-devicetests` on the candidate branch): | Build | Candidate head | Contains #40457 | Result | | --- | --- | --- | --- | | [1692670](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1692670) | b828f7b | no | Controls device tests passed | | [1692843](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1692843) | e064224 | yes | Helix work items crash: iOS General + Shell on all four iOS legs; Android CoreCLR + Mono; Windows packaged + unpackaged; MacCatalyst `Controls Tests` produced no results on either queue | The revert is a full `git revert` of 0eb47dd (5 files, +2/−214). It restores `Window.cs` and removes the tests #40457 added: - `BlazorWebViewTests.WindowDestroying.cs` and `DisposalTrackingComponent.razor`; - the `WindowsTests` and `ModalNavigationPlatformTests` unit tests for the destroy-disconnect behavior. These tests are removed together with the behavior they assert. No unrelated test is changed. #40457 merged without a `maui-pr-devicetests` run, so these crashes first showed up after it landed on the candidate. ### Local evidence Each run starts from candidate head a6d3ad9. The "re-apply" step reverts the revert (`git revert --no-commit HEAD`), which gives back a tree byte-identical to a6d3. **iOS, `Category=Modal`** (CoreSimulator iPhone 16 Pro, iOS 26.5): | Step | Result | | --- | --- | | a6d3 (with #40457) | RED: APP_CRASH, `Page cannot be null here` from `ControlsModalWrapper.UpdateBackgroundColor` | | This revert | GREEN: 222/222 passed | | Re-apply #40457 | RED: same exception | | Revert restored | GREEN: 222/222 passed | **Android, `Category=Shell`** (emulator API 35, arm64): | Step | Result | | --- | --- | | a6d3 (with #40457) | RED: APP_CRASH (XHarness exit 80), FATAL `ArgumentNullException: context` at `ShellSectionRenderer.OnCreateView`, right after `FlyoutContentUpdatesAfterChange` (identical to CI) | | This revert | No crash | | Re-apply #40457 | RED: same FATAL | | Revert restored | GREEN: 197/197 passed, XHarness exit 0, no FATAL | The first revert run had 4 `ShellRendererTransitionTests` failures (193/197). They didn't come back when the revert was restored (197/197), so they're intermittent and unrelated to this change. **iOS, `Category=Shell`** on this branch: no crash; the `VirtualView cannot be null here` path is gone. - On iOS 26.5, `FlyoutHeaderLabelsAreArrangedWhenBoundTextChangesWithoutResizingHeader` (#39877) failed 2/552. It is a layout assertion, and this PR doesn't touch layout. - The same `Category=Shell` run on an iPhone 11 Pro **iOS 18.5** simulator (the device CI uses is iPhone 11 Pro, iOS 18.1) passed 552/552, XHarness exit 0. - CI b828 also passed that test on iOS. So the iOS 26.5 failure is local-environment only and unrelated to this revert. ### Re-landing #40056's fix The BlazorWebView disposal leak from #40056 is still worth fixing. A re-land needs to tolerate callbacks that arrive after `Window.Destroying()`: - the iOS modal wrapper's `ViewWillAppear`/dismissal; - Android fragment transactions that are still pending; - Windows window close. It should also run `maui-pr-devicetests` (Controls: Modal, Shell, General) on all platforms before merging. cc @Kebechet ### Issues Fixed Relates to #40056 and #40116 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
@Kebechet, heads-up: this PR has been reverted on What breaks.
Evidence
Re-landing. #40056 is still open. A re-land needs to tolerate callbacks that arrive after the window is destroyed (modal dismissal, Shell page pop/dispose, pending Android fragment transactions), and should get a |
<!-- 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! ### 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). ### Description of Change **Root cause:** `Window.Destroying()` disconnects the window's own handler but never the handlers of the pages it presents, `Window.Page` and the modal stack. When the next window gets a new page (the templates' `CreateWindow` returns `new Window(new MainPage())`), nothing ever disconnects the old page tree. For a `BlazorWebView` that means `BlazorWebViewHandler.DisconnectHandler` never runs: the `WebViewManager` is not disposed, components never get `Dispose`/`DisposeAsync`, and their timers, loops and JS calls keep running next to the new instance. On Android it is not limited to rotation. Measured with the Blazor Hybrid template on MAUI 10.0.130 (Pixel 6, Android 16), with a component that logs a tick every 2 seconds and logs its disposal: | Trigger | Result | | --- | --- | | System font size change (not in the template's `ConfigurationChanges`) | The activity is recreated with a new window and a new `MainPage`; the old component keeps ticking and is never disposed | | Back on the root route, then opening the app again, both times started through a launcher intent (`monkey -c android.intent.category.LAUNCHER`) | Back finishes the activity (`OnDestroy`, `IsChangingConfigurations` false) while Android keeps the process; the relaunch starts a second Blazor app and the first one's component keeps ticking | A language change and rotation without `ConfigChanges.Orientation` take the same activity-recreation path; I did not measure them separately. **Fix:** `Window.Destroying()` calls `DisconnectHandlers()` on the modal pages and the page it presents, so `HandlerDisconnectPolicy.Manual` is respected. - **Only pages that still belong to this window** (`Parent == this`). An app that reuses one page instance can already have put it into a newer window when the old one is destroyed, and its handlers then belong to the new window. - **After the window's own handler is disconnected.** Disconnecting the page raises `HandlerChanged`, and `Window.OnPageHandlerChanged` subscribes the alert manager whenever the window still has a handler, so earlier it would subscribe the destroyed window again. - **Before `DisposeWindowScope()`** (iOS, Mac Catalyst, Windows), so handlers can still use the window's services while they disconnect. The scope is disposed in a `finally`, so a handler that throws does not leave it behind. This is a behaviour change for every app: a destroyed window now tears down its page tree instead of leaving it connected. | Case | Before | After | | --- | --- | --- | | New page in the new window (templates) | Old page tree stays connected for the life of the process | Disconnected when the old window is destroyed | | Same page instance shown again in a new window, after the old window is destroyed | The new window creates new handlers; `Element.SetHandler` disconnects the old ones | Old handlers disconnected at destroy; the new window creates new handlers | | Same page instance already moved to a newer window | Untouched | Untouched (`Parent` is the newer window) | | A view with `HandlerDisconnectPolicy.Manual` | Untouched | Untouched, with its subtree | | Windows: a `BlazorWebView` in a closed window | `BlazorWebView.Windows.cs` already closes the WebView2 on `Window.Destroying` | Same, then the handler disconnects | ### Tests Unit tests (`Controls.Core.UnitTests`): - `WindowsTests.DestroyingDisconnectsHandlersOfThePage`: a page, a layout and a button, each with a handler; after `Destroying()` all three are disconnected. - `WindowsTests.DestroyingKeepsHandlersWithManualDisconnectPolicy`: a layout with `HandlerDisconnectPolicy.Manual` keeps its handler and its child's; the page is still disconnected. - `WindowsTests.DestroyingKeepsHandlersOfAPageMovedToANewerWindow`: the page moves to a second window and gets a new handler; destroying the first window leaves that handler connected. - `ModalNavigationPlatformTests.DestroyingDisconnectsRootAndModalPageHandlers`: the root page and a pushed modal page are both disconnected. - `ModalNavigationPlatformTests.DestroyingKeepsHandlersOfAModalPageMovedToANewerWindow`: a pushed modal page is put into a second window and gets a new handler, while the first window's modal stack still lists it; destroying the first window disconnects its root page and leaves the modal's new handler connected. Device test (`MauiBlazorWebView.DeviceTests`): - `BlazorWebViewTests.DestroyingWindowDisposesRootComponents`: a `BlazorWebView` in a page in a window renders a component that records its disposal; after `Destroying()` the component is disposed and the `BlazorWebView` has no handler. Run locally on this branch's base `net11` (d1bb681), devices on Android only (Pixel 6, Android 16); iOS, Mac Catalyst and Windows were not run: | Run | Without the fix | This branch | | --- | --- | --- | | The new unit tests | The first three fail. `DestroyingKeepsHandlersOfAPageMovedToANewerWindow` was added with the `Parent` check and fails on this PR's first commit, which had none. `DestroyingKeepsHandlersOfAModalPageMovedToANewerWindow` fails with only the modal `Parent` check removed | 5 of 5 pass (a23b8bd) | | `Controls.Core.UnitTests`, all | | 6738 passed, 30 skipped, 0 failed (a23b8bd) | | `MauiBlazorWebView.DeviceTests`, all | 69 run: 64 passed, 4 skipped, 1 failed (the new test times out: the component is never disposed) | 69 run: 65 passed, 4 skipped, 0 failed (f55e17c; a23b8bd only adds unit tests) | End to end, on the same Pixel 6 with the Controls gallery built from this branch: I switched its start page to `BlazorPage` and made its index component log a tick every 2 seconds and its disposal (local edits, not part of this PR). Two font-size changes each disposed the old component before the new one started, and Back on the root route followed by a relaunch through the launcher disposed it as well. Only the newest component kept ticking. Not measured: whether the old `MainPage`/`BlazorWebView` instances are garbage-collected afterwards, which the issue's expected result also mentions. This PR makes sure they are disconnected and their components disposed. ### What NOT to Do (for future agents) - ❌ **Don't disconnect `Window.Page` unconditionally.** A reused page can already belong to a newer window; check `Parent == this`. - ❌ **Don't disconnect the pages before the window handler.** The page's `HandlerChanged` would subscribe the alert manager on a window that is being destroyed. - ❌ **Don't fix this in `BlazorWebViewHandler`.** The handler cannot know that its window went away; every handler that owns work of its own has the same problem. ### Issues Fixed Fixes #40056 --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… device tests (#40486) <!-- 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 directly there. 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). This is SR2 candidate integration work for #40116, so it targets `candidate/11.0.1xx-sr2`. #40457 was merged straight into the candidate (0eb47dd) and `net11` doesn't have it, so there is nothing to revert on `net11`. ### Description of Change This reverts #40457 ("Window: Disconnect page handlers when the window is destroyed"), which crashes the Controls device-test apps on Android, iOS and Windows and leaves MacCatalyst Controls device tests without results. #40457 changed `Window.Destroying()` to disconnect the handlers of the window's page and modal stack. Platform callbacks still run after `Destroying()`, and when they reach the now-disconnected handlers the process crashes: | Platform | Crash | Stack | | --- | --- | --- | | iOS (CoreCLR + Mono, iOS 18 and 26 queues), Controls.DeviceTests-General | `InvalidOperationException: Page cannot be null here` | `ControlsModalWrapper.UpdateBackgroundColor` ← `ControlsModalWrapper.ViewWillAppear` (the modal is dismissed after window teardown) | | iOS (CoreCLR + Mono), Controls.DeviceTests-Shell | `InvalidOperationException: VirtualView cannot be null here` | `ShellPageRendererTracker.Dispose` ← `ShellSectionHandler.DisposePage` ← `OnPopRequested` | | Android (CoreCLR + Mono), API 33 | `ArgumentNullException` for `context` | `ShellSectionRenderer.OnCreateView`. A pending fragment transaction runs after teardown, and `FindMauiContext()` returns null. | | Windows (packaged + unpackaged) | `0xc000027b`, faulting module `Microsoft.UI.Xaml.dll` | Process crash during the Controls device tests (attributed by mechanism; not reproduced locally) | | MacCatalyst (CoreCLR, osx.15 + osx.26) | No test results | osx.15 `Controls Tests` ran into the 3600 s XHarness timeout (exit 94, `TEST_RESULTS_MISSING`; the app was still alive). On osx.26 the app exited after about 6 minutes with no results file, and XHarness still reported success. Without #40457, both queues report 1636–1777 tests in about 12 minutes (8 runs in builds 1690816, 1692066, 1692670, 1692736). Attributed by correlation; not reproduced locally. | **CI** (`maui-pr-devicetests` on the candidate branch): | Build | Candidate head | Contains #40457 | Result | | --- | --- | --- | --- | | [1692670](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1692670) | b828f7b | no | Controls device tests passed | | [1692843](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1692843) | e064224 | yes | Helix work items crash: iOS General + Shell on all four iOS legs; Android CoreCLR + Mono; Windows packaged + unpackaged; MacCatalyst `Controls Tests` produced no results on either queue | The revert is a full `git revert` of 0eb47dd (5 files, +2/−214). It restores `Window.cs` and removes the tests #40457 added: - `BlazorWebViewTests.WindowDestroying.cs` and `DisposalTrackingComponent.razor`; - the `WindowsTests` and `ModalNavigationPlatformTests` unit tests for the destroy-disconnect behavior. These tests are removed together with the behavior they assert. No unrelated test is changed. #40457 merged without a `maui-pr-devicetests` run, so these crashes first showed up after it landed on the candidate. ### Local evidence Each run starts from candidate head a6d3ad9. The "re-apply" step reverts the revert (`git revert --no-commit HEAD`), which gives back a tree byte-identical to a6d3. **iOS, `Category=Modal`** (CoreSimulator iPhone 16 Pro, iOS 26.5): | Step | Result | | --- | --- | | a6d3 (with #40457) | RED: APP_CRASH, `Page cannot be null here` from `ControlsModalWrapper.UpdateBackgroundColor` | | This revert | GREEN: 222/222 passed | | Re-apply #40457 | RED: same exception | | Revert restored | GREEN: 222/222 passed | **Android, `Category=Shell`** (emulator API 35, arm64): | Step | Result | | --- | --- | | a6d3 (with #40457) | RED: APP_CRASH (XHarness exit 80), FATAL `ArgumentNullException: context` at `ShellSectionRenderer.OnCreateView`, right after `FlyoutContentUpdatesAfterChange` (identical to CI) | | This revert | No crash | | Re-apply #40457 | RED: same FATAL | | Revert restored | GREEN: 197/197 passed, XHarness exit 0, no FATAL | The first revert run had 4 `ShellRendererTransitionTests` failures (193/197). They didn't come back when the revert was restored (197/197), so they're intermittent and unrelated to this change. **iOS, `Category=Shell`** on this branch: no crash; the `VirtualView cannot be null here` path is gone. - On iOS 26.5, `FlyoutHeaderLabelsAreArrangedWhenBoundTextChangesWithoutResizingHeader` (#39877) failed 2/552. It is a layout assertion, and this PR doesn't touch layout. - The same `Category=Shell` run on an iPhone 11 Pro **iOS 18.5** simulator (the device CI uses is iPhone 11 Pro, iOS 18.1) passed 552/552, XHarness exit 0. - CI b828 also passed that test on iOS. So the iOS 26.5 failure is local-environment only and unrelated to this revert. ### Re-landing #40056's fix The BlazorWebView disposal leak from #40056 is still worth fixing. A re-land needs to tolerate callbacks that arrive after `Window.Destroying()`: - the iOS modal wrapper's `ViewWillAppear`/dismissal; - Android fragment transactions that are still pending; - Windows window close. It should also run `maui-pr-devicetests` (Controls: Modal, Shell, General) on all platforms before merging. cc @Kebechet ### Issues Fixed Relates to #40056 and #40116 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
<!-- 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! ### 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). ### Description of Change **Root cause:** `Window.Destroying()` disconnects the window's own handler but never the handlers of the pages it presents, `Window.Page` and the modal stack. When the next window gets a new page (the templates' `CreateWindow` returns `new Window(new MainPage())`), nothing ever disconnects the old page tree. For a `BlazorWebView` that means `BlazorWebViewHandler.DisconnectHandler` never runs: the `WebViewManager` is not disposed, components never get `Dispose`/`DisposeAsync`, and their timers, loops and JS calls keep running next to the new instance. On Android it is not limited to rotation. Measured with the Blazor Hybrid template on MAUI 10.0.130 (Pixel 6, Android 16), with a component that logs a tick every 2 seconds and logs its disposal: | Trigger | Result | | --- | --- | | System font size change (not in the template's `ConfigurationChanges`) | The activity is recreated with a new window and a new `MainPage`; the old component keeps ticking and is never disposed | | Back on the root route, then opening the app again, both times started through a launcher intent (`monkey -c android.intent.category.LAUNCHER`) | Back finishes the activity (`OnDestroy`, `IsChangingConfigurations` false) while Android keeps the process; the relaunch starts a second Blazor app and the first one's component keeps ticking | A language change and rotation without `ConfigChanges.Orientation` take the same activity-recreation path; I did not measure them separately. **Fix:** `Window.Destroying()` calls `DisconnectHandlers()` on the modal pages and the page it presents, so `HandlerDisconnectPolicy.Manual` is respected. - **Only pages that still belong to this window** (`Parent == this`). An app that reuses one page instance can already have put it into a newer window when the old one is destroyed, and its handlers then belong to the new window. - **After the window's own handler is disconnected.** Disconnecting the page raises `HandlerChanged`, and `Window.OnPageHandlerChanged` subscribes the alert manager whenever the window still has a handler, so earlier it would subscribe the destroyed window again. - **Before `DisposeWindowScope()`** (iOS, Mac Catalyst, Windows), so handlers can still use the window's services while they disconnect. The scope is disposed in a `finally`, so a handler that throws does not leave it behind. This is a behaviour change for every app: a destroyed window now tears down its page tree instead of leaving it connected. | Case | Before | After | | --- | --- | --- | | New page in the new window (templates) | Old page tree stays connected for the life of the process | Disconnected when the old window is destroyed | | Same page instance shown again in a new window, after the old window is destroyed | The new window creates new handlers; `Element.SetHandler` disconnects the old ones | Old handlers disconnected at destroy; the new window creates new handlers | | Same page instance already moved to a newer window | Untouched | Untouched (`Parent` is the newer window) | | A view with `HandlerDisconnectPolicy.Manual` | Untouched | Untouched, with its subtree | | Windows: a `BlazorWebView` in a closed window | `BlazorWebView.Windows.cs` already closes the WebView2 on `Window.Destroying` | Same, then the handler disconnects | ### Tests Unit tests (`Controls.Core.UnitTests`): - `WindowsTests.DestroyingDisconnectsHandlersOfThePage`: a page, a layout and a button, each with a handler; after `Destroying()` all three are disconnected. - `WindowsTests.DestroyingKeepsHandlersWithManualDisconnectPolicy`: a layout with `HandlerDisconnectPolicy.Manual` keeps its handler and its child's; the page is still disconnected. - `WindowsTests.DestroyingKeepsHandlersOfAPageMovedToANewerWindow`: the page moves to a second window and gets a new handler; destroying the first window leaves that handler connected. - `ModalNavigationPlatformTests.DestroyingDisconnectsRootAndModalPageHandlers`: the root page and a pushed modal page are both disconnected. - `ModalNavigationPlatformTests.DestroyingKeepsHandlersOfAModalPageMovedToANewerWindow`: a pushed modal page is put into a second window and gets a new handler, while the first window's modal stack still lists it; destroying the first window disconnects its root page and leaves the modal's new handler connected. Device test (`MauiBlazorWebView.DeviceTests`): - `BlazorWebViewTests.DestroyingWindowDisposesRootComponents`: a `BlazorWebView` in a page in a window renders a component that records its disposal; after `Destroying()` the component is disposed and the `BlazorWebView` has no handler. Run locally on this branch's base `net11` (d1bb681), devices on Android only (Pixel 6, Android 16); iOS, Mac Catalyst and Windows were not run: | Run | Without the fix | This branch | | --- | --- | --- | | The new unit tests | The first three fail. `DestroyingKeepsHandlersOfAPageMovedToANewerWindow` was added with the `Parent` check and fails on this PR's first commit, which had none. `DestroyingKeepsHandlersOfAModalPageMovedToANewerWindow` fails with only the modal `Parent` check removed | 5 of 5 pass (a23b8bd) | | `Controls.Core.UnitTests`, all | | 6738 passed, 30 skipped, 0 failed (a23b8bd) | | `MauiBlazorWebView.DeviceTests`, all | 69 run: 64 passed, 4 skipped, 1 failed (the new test times out: the component is never disposed) | 69 run: 65 passed, 4 skipped, 0 failed (f55e17c; a23b8bd only adds unit tests) | End to end, on the same Pixel 6 with the Controls gallery built from this branch: I switched its start page to `BlazorPage` and made its index component log a tick every 2 seconds and its disposal (local edits, not part of this PR). Two font-size changes each disposed the old component before the new one started, and Back on the root route followed by a relaunch through the launcher disposed it as well. Only the newest component kept ticking. Not measured: whether the old `MainPage`/`BlazorWebView` instances are garbage-collected afterwards, which the issue's expected result also mentions. This PR makes sure they are disconnected and their components disposed. ### What NOT to Do (for future agents) - ❌ **Don't disconnect `Window.Page` unconditionally.** A reused page can already belong to a newer window; check `Parent == this`. - ❌ **Don't disconnect the pages before the window handler.** The page's `HandlerChanged` would subscribe the alert manager on a window that is being destroyed. - ❌ **Don't fix this in `BlazorWebViewHandler`.** The handler cannot know that its window went away; every handler that owns work of its own has the same problem. ### Issues Fixed Fixes #40056 --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… device tests (#40486) <!-- 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 directly there. 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). This is SR2 candidate integration work for #40116, so it targets `candidate/11.0.1xx-sr2`. #40457 was merged straight into the candidate (0eb47dd) and `net11` doesn't have it, so there is nothing to revert on `net11`. ### Description of Change This reverts #40457 ("Window: Disconnect page handlers when the window is destroyed"), which crashes the Controls device-test apps on Android, iOS and Windows and leaves MacCatalyst Controls device tests without results. #40457 changed `Window.Destroying()` to disconnect the handlers of the window's page and modal stack. Platform callbacks still run after `Destroying()`, and when they reach the now-disconnected handlers the process crashes: | Platform | Crash | Stack | | --- | --- | --- | | iOS (CoreCLR + Mono, iOS 18 and 26 queues), Controls.DeviceTests-General | `InvalidOperationException: Page cannot be null here` | `ControlsModalWrapper.UpdateBackgroundColor` ← `ControlsModalWrapper.ViewWillAppear` (the modal is dismissed after window teardown) | | iOS (CoreCLR + Mono), Controls.DeviceTests-Shell | `InvalidOperationException: VirtualView cannot be null here` | `ShellPageRendererTracker.Dispose` ← `ShellSectionHandler.DisposePage` ← `OnPopRequested` | | Android (CoreCLR + Mono), API 33 | `ArgumentNullException` for `context` | `ShellSectionRenderer.OnCreateView`. A pending fragment transaction runs after teardown, and `FindMauiContext()` returns null. | | Windows (packaged + unpackaged) | `0xc000027b`, faulting module `Microsoft.UI.Xaml.dll` | Process crash during the Controls device tests (attributed by mechanism; not reproduced locally) | | MacCatalyst (CoreCLR, osx.15 + osx.26) | No test results | osx.15 `Controls Tests` ran into the 3600 s XHarness timeout (exit 94, `TEST_RESULTS_MISSING`; the app was still alive). On osx.26 the app exited after about 6 minutes with no results file, and XHarness still reported success. Without #40457, both queues report 1636–1777 tests in about 12 minutes (8 runs in builds 1690816, 1692066, 1692670, 1692736). Attributed by correlation; not reproduced locally. | **CI** (`maui-pr-devicetests` on the candidate branch): | Build | Candidate head | Contains #40457 | Result | | --- | --- | --- | --- | | [1692670](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1692670) | b828f7b | no | Controls device tests passed | | [1692843](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1692843) | e064224 | yes | Helix work items crash: iOS General + Shell on all four iOS legs; Android CoreCLR + Mono; Windows packaged + unpackaged; MacCatalyst `Controls Tests` produced no results on either queue | The revert is a full `git revert` of 0eb47dd (5 files, +2/−214). It restores `Window.cs` and removes the tests #40457 added: - `BlazorWebViewTests.WindowDestroying.cs` and `DisposalTrackingComponent.razor`; - the `WindowsTests` and `ModalNavigationPlatformTests` unit tests for the destroy-disconnect behavior. These tests are removed together with the behavior they assert. No unrelated test is changed. #40457 merged without a `maui-pr-devicetests` run, so these crashes first showed up after it landed on the candidate. ### Local evidence Each run starts from candidate head a6d3ad9. The "re-apply" step reverts the revert (`git revert --no-commit HEAD`), which gives back a tree byte-identical to a6d3. **iOS, `Category=Modal`** (CoreSimulator iPhone 16 Pro, iOS 26.5): | Step | Result | | --- | --- | | a6d3 (with #40457) | RED: APP_CRASH, `Page cannot be null here` from `ControlsModalWrapper.UpdateBackgroundColor` | | This revert | GREEN: 222/222 passed | | Re-apply #40457 | RED: same exception | | Revert restored | GREEN: 222/222 passed | **Android, `Category=Shell`** (emulator API 35, arm64): | Step | Result | | --- | --- | | a6d3 (with #40457) | RED: APP_CRASH (XHarness exit 80), FATAL `ArgumentNullException: context` at `ShellSectionRenderer.OnCreateView`, right after `FlyoutContentUpdatesAfterChange` (identical to CI) | | This revert | No crash | | Re-apply #40457 | RED: same FATAL | | Revert restored | GREEN: 197/197 passed, XHarness exit 0, no FATAL | The first revert run had 4 `ShellRendererTransitionTests` failures (193/197). They didn't come back when the revert was restored (197/197), so they're intermittent and unrelated to this change. **iOS, `Category=Shell`** on this branch: no crash; the `VirtualView cannot be null here` path is gone. - On iOS 26.5, `FlyoutHeaderLabelsAreArrangedWhenBoundTextChangesWithoutResizingHeader` (#39877) failed 2/552. It is a layout assertion, and this PR doesn't touch layout. - The same `Category=Shell` run on an iPhone 11 Pro **iOS 18.5** simulator (the device CI uses is iPhone 11 Pro, iOS 18.1) passed 552/552, XHarness exit 0. - CI b828 also passed that test on iOS. So the iOS 26.5 failure is local-environment only and unrelated to this revert. ### Re-landing #40056's fix The BlazorWebView disposal leak from #40056 is still worth fixing. A re-land needs to tolerate callbacks that arrive after `Window.Destroying()`: - the iOS modal wrapper's `ViewWillAppear`/dismissal; - Android fragment transactions that are still pending; - Windows window close. It should also run `maui-pr-devicetests` (Controls: Modal, Shell, General) on all platforms before merging. cc @Kebechet ### Issues Fixed Relates to #40056 and #40116 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…#40457) <!-- 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! ### 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). ### Description of Change **Root cause:** `Window.Destroying()` disconnects the window's own handler but never the handlers of the pages it presents, `Window.Page` and the modal stack. When the next window gets a new page (the templates' `CreateWindow` returns `new Window(new MainPage())`), nothing ever disconnects the old page tree. For a `BlazorWebView` that means `BlazorWebViewHandler.DisconnectHandler` never runs: the `WebViewManager` is not disposed, components never get `Dispose`/`DisposeAsync`, and their timers, loops and JS calls keep running next to the new instance. On Android it is not limited to rotation. Measured with the Blazor Hybrid template on MAUI 10.0.130 (Pixel 6, Android 16), with a component that logs a tick every 2 seconds and logs its disposal: | Trigger | Result | | --- | --- | | System font size change (not in the template's `ConfigurationChanges`) | The activity is recreated with a new window and a new `MainPage`; the old component keeps ticking and is never disposed | | Back on the root route, then opening the app again, both times started through a launcher intent (`monkey -c android.intent.category.LAUNCHER`) | Back finishes the activity (`OnDestroy`, `IsChangingConfigurations` false) while Android keeps the process; the relaunch starts a second Blazor app and the first one's component keeps ticking | A language change and rotation without `ConfigChanges.Orientation` take the same activity-recreation path; I did not measure them separately. **Fix:** `Window.Destroying()` calls `DisconnectHandlers()` on the modal pages and the page it presents, so `HandlerDisconnectPolicy.Manual` is respected. - **Only pages that still belong to this window** (`Parent == this`). An app that reuses one page instance can already have put it into a newer window when the old one is destroyed, and its handlers then belong to the new window. - **After the window's own handler is disconnected.** Disconnecting the page raises `HandlerChanged`, and `Window.OnPageHandlerChanged` subscribes the alert manager whenever the window still has a handler, so earlier it would subscribe the destroyed window again. - **Before `DisposeWindowScope()`** (iOS, Mac Catalyst, Windows), so handlers can still use the window's services while they disconnect. The scope is disposed in a `finally`, so a handler that throws does not leave it behind. This is a behaviour change for every app: a destroyed window now tears down its page tree instead of leaving it connected. | Case | Before | After | | --- | --- | --- | | New page in the new window (templates) | Old page tree stays connected for the life of the process | Disconnected when the old window is destroyed | | Same page instance shown again in a new window, after the old window is destroyed | The new window creates new handlers; `Element.SetHandler` disconnects the old ones | Old handlers disconnected at destroy; the new window creates new handlers | | Same page instance already moved to a newer window | Untouched | Untouched (`Parent` is the newer window) | | A view with `HandlerDisconnectPolicy.Manual` | Untouched | Untouched, with its subtree | | Windows: a `BlazorWebView` in a closed window | `BlazorWebView.Windows.cs` already closes the WebView2 on `Window.Destroying` | Same, then the handler disconnects | ### Tests Unit tests (`Controls.Core.UnitTests`): - `WindowsTests.DestroyingDisconnectsHandlersOfThePage`: a page, a layout and a button, each with a handler; after `Destroying()` all three are disconnected. - `WindowsTests.DestroyingKeepsHandlersWithManualDisconnectPolicy`: a layout with `HandlerDisconnectPolicy.Manual` keeps its handler and its child's; the page is still disconnected. - `WindowsTests.DestroyingKeepsHandlersOfAPageMovedToANewerWindow`: the page moves to a second window and gets a new handler; destroying the first window leaves that handler connected. - `ModalNavigationPlatformTests.DestroyingDisconnectsRootAndModalPageHandlers`: the root page and a pushed modal page are both disconnected. - `ModalNavigationPlatformTests.DestroyingKeepsHandlersOfAModalPageMovedToANewerWindow`: a pushed modal page is put into a second window and gets a new handler, while the first window's modal stack still lists it; destroying the first window disconnects its root page and leaves the modal's new handler connected. Device test (`MauiBlazorWebView.DeviceTests`): - `BlazorWebViewTests.DestroyingWindowDisposesRootComponents`: a `BlazorWebView` in a page in a window renders a component that records its disposal; after `Destroying()` the component is disposed and the `BlazorWebView` has no handler. Run locally on this branch's base `net11` (d1bb681), devices on Android only (Pixel 6, Android 16); iOS, Mac Catalyst and Windows were not run: | Run | Without the fix | This branch | | --- | --- | --- | | The new unit tests | The first three fail. `DestroyingKeepsHandlersOfAPageMovedToANewerWindow` was added with the `Parent` check and fails on this PR's first commit, which had none. `DestroyingKeepsHandlersOfAModalPageMovedToANewerWindow` fails with only the modal `Parent` check removed | 5 of 5 pass (a23b8bd) | | `Controls.Core.UnitTests`, all | | 6738 passed, 30 skipped, 0 failed (a23b8bd) | | `MauiBlazorWebView.DeviceTests`, all | 69 run: 64 passed, 4 skipped, 1 failed (the new test times out: the component is never disposed) | 69 run: 65 passed, 4 skipped, 0 failed (f55e17c; a23b8bd only adds unit tests) | End to end, on the same Pixel 6 with the Controls gallery built from this branch: I switched its start page to `BlazorPage` and made its index component log a tick every 2 seconds and its disposal (local edits, not part of this PR). Two font-size changes each disposed the old component before the new one started, and Back on the root route followed by a relaunch through the launcher disposed it as well. Only the newest component kept ticking. Not measured: whether the old `MainPage`/`BlazorWebView` instances are garbage-collected afterwards, which the issue's expected result also mentions. This PR makes sure they are disconnected and their components disposed. ### What NOT to Do (for future agents) - ❌ **Don't disconnect `Window.Page` unconditionally.** A reused page can already belong to a newer window; check `Parent == this`. - ❌ **Don't disconnect the pages before the window handler.** The page's `HandlerChanged` would subscribe the alert manager on a window that is being destroyed. - ❌ **Don't fix this in `BlazorWebViewHandler`.** The handler cannot know that its window went away; every handler that owns work of its own has the same problem. ### Issues Fixed Fixes dotnet#40056 --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…ntrols device tests (dotnet#40486) <!-- 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 directly there. 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). This is SR2 candidate integration work for dotnet#40116, so it targets `candidate/11.0.1xx-sr2`. dotnet#40457 was merged straight into the candidate (0eb47dd) and `net11` doesn't have it, so there is nothing to revert on `net11`. ### Description of Change This reverts dotnet#40457 ("Window: Disconnect page handlers when the window is destroyed"), which crashes the Controls device-test apps on Android, iOS and Windows and leaves MacCatalyst Controls device tests without results. dotnet#40457 changed `Window.Destroying()` to disconnect the handlers of the window's page and modal stack. Platform callbacks still run after `Destroying()`, and when they reach the now-disconnected handlers the process crashes: | Platform | Crash | Stack | | --- | --- | --- | | iOS (CoreCLR + Mono, iOS 18 and 26 queues), Controls.DeviceTests-General | `InvalidOperationException: Page cannot be null here` | `ControlsModalWrapper.UpdateBackgroundColor` ← `ControlsModalWrapper.ViewWillAppear` (the modal is dismissed after window teardown) | | iOS (CoreCLR + Mono), Controls.DeviceTests-Shell | `InvalidOperationException: VirtualView cannot be null here` | `ShellPageRendererTracker.Dispose` ← `ShellSectionHandler.DisposePage` ← `OnPopRequested` | | Android (CoreCLR + Mono), API 33 | `ArgumentNullException` for `context` | `ShellSectionRenderer.OnCreateView`. A pending fragment transaction runs after teardown, and `FindMauiContext()` returns null. | | Windows (packaged + unpackaged) | `0xc000027b`, faulting module `Microsoft.UI.Xaml.dll` | Process crash during the Controls device tests (attributed by mechanism; not reproduced locally) | | MacCatalyst (CoreCLR, osx.15 + osx.26) | No test results | osx.15 `Controls Tests` ran into the 3600 s XHarness timeout (exit 94, `TEST_RESULTS_MISSING`; the app was still alive). On osx.26 the app exited after about 6 minutes with no results file, and XHarness still reported success. Without dotnet#40457, both queues report 1636–1777 tests in about 12 minutes (8 runs in builds 1690816, 1692066, 1692670, 1692736). Attributed by correlation; not reproduced locally. | **CI** (`maui-pr-devicetests` on the candidate branch): | Build | Candidate head | Contains dotnet#40457 | Result | | --- | --- | --- | --- | | [1692670](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1692670) | b828f7b | no | Controls device tests passed | | [1692843](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1692843) | e064224 | yes | Helix work items crash: iOS General + Shell on all four iOS legs; Android CoreCLR + Mono; Windows packaged + unpackaged; MacCatalyst `Controls Tests` produced no results on either queue | The revert is a full `git revert` of 0eb47dd (5 files, +2/−214). It restores `Window.cs` and removes the tests dotnet#40457 added: - `BlazorWebViewTests.WindowDestroying.cs` and `DisposalTrackingComponent.razor`; - the `WindowsTests` and `ModalNavigationPlatformTests` unit tests for the destroy-disconnect behavior. These tests are removed together with the behavior they assert. No unrelated test is changed. dotnet#40457 merged without a `maui-pr-devicetests` run, so these crashes first showed up after it landed on the candidate. ### Local evidence Each run starts from candidate head a6d3ad9. The "re-apply" step reverts the revert (`git revert --no-commit HEAD`), which gives back a tree byte-identical to a6d3. **iOS, `Category=Modal`** (CoreSimulator iPhone 16 Pro, iOS 26.5): | Step | Result | | --- | --- | | a6d3 (with dotnet#40457) | RED: APP_CRASH, `Page cannot be null here` from `ControlsModalWrapper.UpdateBackgroundColor` | | This revert | GREEN: 222/222 passed | | Re-apply dotnet#40457 | RED: same exception | | Revert restored | GREEN: 222/222 passed | **Android, `Category=Shell`** (emulator API 35, arm64): | Step | Result | | --- | --- | | a6d3 (with dotnet#40457) | RED: APP_CRASH (XHarness exit 80), FATAL `ArgumentNullException: context` at `ShellSectionRenderer.OnCreateView`, right after `FlyoutContentUpdatesAfterChange` (identical to CI) | | This revert | No crash | | Re-apply dotnet#40457 | RED: same FATAL | | Revert restored | GREEN: 197/197 passed, XHarness exit 0, no FATAL | The first revert run had 4 `ShellRendererTransitionTests` failures (193/197). They didn't come back when the revert was restored (197/197), so they're intermittent and unrelated to this change. **iOS, `Category=Shell`** on this branch: no crash; the `VirtualView cannot be null here` path is gone. - On iOS 26.5, `FlyoutHeaderLabelsAreArrangedWhenBoundTextChangesWithoutResizingHeader` (dotnet#39877) failed 2/552. It is a layout assertion, and this PR doesn't touch layout. - The same `Category=Shell` run on an iPhone 11 Pro **iOS 18.5** simulator (the device CI uses is iPhone 11 Pro, iOS 18.1) passed 552/552, XHarness exit 0. - CI b828 also passed that test on iOS. So the iOS 26.5 failure is local-environment only and unrelated to this revert. ### Re-landing dotnet#40056's fix The BlazorWebView disposal leak from dotnet#40056 is still worth fixing. A re-land needs to tolerate callbacks that arrive after `Window.Destroying()`: - the iOS modal wrapper's `ViewWillAppear`/dismissal; - Android fragment transactions that are still pending; - Windows window close. It should also run `maui-pr-devicetests` (Controls: Modal, Shell, General) on all platforms before merging. cc @Kebechet ### Issues Fixed Relates to dotnet#40056 and dotnet#40116 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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
mainnet11, for reviewDescription of Change
Root cause:
Window.Destroying()disconnects the window's own handler but never the handlers of the pages it presents,Window.Pageand the modal stack. When the next window gets a new page (the templates'CreateWindowreturnsnew Window(new MainPage())), nothing ever disconnects the old page tree. For aBlazorWebViewthat meansBlazorWebViewHandler.DisconnectHandlernever runs: theWebViewManageris not disposed, components never getDispose/DisposeAsync, and their timers, loops and JS calls keep running next to the new instance.On Android it is not limited to rotation. Measured with the Blazor Hybrid template on MAUI 10.0.130 (Pixel 6, Android 16), with a component that logs a tick every 2 seconds and logs its disposal:
ConfigurationChanges)MainPage; the old component keeps ticking and is never disposedmonkey -c android.intent.category.LAUNCHER)OnDestroy,IsChangingConfigurationsfalse) while Android keeps the process; the relaunch starts a second Blazor app and the first one's component keeps tickingA language change and rotation without
ConfigChanges.Orientationtake the same activity-recreation path; I did not measure them separately.Fix:
Window.Destroying()callsDisconnectHandlers()on the modal pages and the page it presents, soHandlerDisconnectPolicy.Manualis respected.Parent == this). An app that reuses one page instance can already have put it into a newer window when the old one is destroyed, and its handlers then belong to the new window.HandlerChanged, andWindow.OnPageHandlerChangedsubscribes the alert manager whenever the window still has a handler, so earlier it would subscribe the destroyed window again.DisposeWindowScope()(iOS, Mac Catalyst, Windows), so handlers can still use the window's services while they disconnect. The scope is disposed in afinally, so a handler that throws does not leave it behind.This is a behaviour change for every app: a destroyed window now tears down its page tree instead of leaving it connected.
Element.SetHandlerdisconnects the old onesParentis the newer window)HandlerDisconnectPolicy.ManualBlazorWebViewin a closed windowBlazorWebView.Windows.csalready closes the WebView2 onWindow.DestroyingTests
Unit tests (
Controls.Core.UnitTests):WindowsTests.DestroyingDisconnectsHandlersOfThePage: a page, a layout and a button, each with a handler; afterDestroying()all three are disconnected.WindowsTests.DestroyingKeepsHandlersWithManualDisconnectPolicy: a layout withHandlerDisconnectPolicy.Manualkeeps its handler and its child's; the page is still disconnected.WindowsTests.DestroyingKeepsHandlersOfAPageMovedToANewerWindow: the page moves to a second window and gets a new handler; destroying the first window leaves that handler connected.ModalNavigationPlatformTests.DestroyingDisconnectsRootAndModalPageHandlers: the root page and a pushed modal page are both disconnected.ModalNavigationPlatformTests.DestroyingKeepsHandlersOfAModalPageMovedToANewerWindow: a pushed modal page is put into a second window and gets a new handler, while the first window's modal stack still lists it; destroying the first window disconnects its root page and leaves the modal's new handler connected.Device test (
MauiBlazorWebView.DeviceTests):BlazorWebViewTests.DestroyingWindowDisposesRootComponents: aBlazorWebViewin a page in a window renders a component that records its disposal; afterDestroying()the component is disposed and theBlazorWebViewhas no handler.Run locally on this branch's base
net11(d1bb681), devices on Android only (Pixel 6, Android 16); iOS, Mac Catalyst and Windows were not run:DestroyingKeepsHandlersOfAPageMovedToANewerWindowwas added with theParentcheck and fails on this PR's first commit, which had none.DestroyingKeepsHandlersOfAModalPageMovedToANewerWindowfails with only the modalParentcheck removedControls.Core.UnitTests, allMauiBlazorWebView.DeviceTests, allEnd to end, on the same Pixel 6 with the Controls gallery built from this branch: I switched its start page to
BlazorPageand made its index component log a tick every 2 seconds and its disposal (local edits, not part of this PR). Two font-size changes each disposed the old component before the new one started, and Back on the root route followed by a relaunch through the launcher disposed it as well. Only the newest component kept ticking.Not measured: whether the old
MainPage/BlazorWebViewinstances are garbage-collected afterwards, which the issue's expected result also mentions. This PR makes sure they are disconnected and their components disposed.What NOT to Do (for future agents)
Window.Pageunconditionally. A reused page can already belong to a newer window; checkParent == this.HandlerChangedwould subscribe the alert manager on a window that is being destroyed.BlazorWebViewHandler. The handler cannot know that its window went away; every handler that owns work of its own has the same problem.Issues Fixed
Fixes #40056