Skip to content

[XSG] XIHR: keep the pending patch across throwaway compilations with different C# - #40330

Merged
kubaflo merged 140 commits into
candidate/11.0.1xx-sr2from
stephanedelcroix-xihr-throwaway-compilation-signal
Nov 17, 2026
Merged

kubaflo merged 140 commits into
candidate/11.0.1xx-sr2from
stephanedelcroix-xihr-throwaway-compilation-signal

Conversation

@StephaneDelcroix

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!

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

Base note: this is a follow-up to #40233, which was merged into candidate/11.0.1xx-sr2 and is not in net11 (or main) yet. This change modifies code that only exists there, so the PR targets candidate/11.0.1xx-sr2.

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 #40233, closing the gap it documented: if a throwaway compilation with different user C# (speculative or design-time snapshot) evaluates the edited XAML before the real compilation does, the pending UpdateComponent() patch is lost. The generator couldn't tell this apart from a genuine C#-only edit, which had to emit an empty UpdateComponent() because the runtime classified a delta as a XAML change by the emptiness of that body.

Fix: move the classification to a companion signal type, as @noiseonwires proposed on #36937. The MetadataUpdateHandler is in this repo, so no Roslyn or hot reload agent changes are needed.

  • Generator (UpdateComponentCodeWriter): the .uc.xsg.cs file now also nests a private __XamlHotReloadSignal type in each XIHR root, with Fingerprint() => "<sha256 of the patch body>" ("" when there's no patch). It's emitted on every generation, like UpdateComponent(), so there's no member churn. Its content only changes when the patch changes, so Roslyn lists it in a delta exactly when there's a new patch to apply.
  • Generator (XamlGenerator / XamlHotReloadState): when the XAML is unchanged and a patch is pending, the patch is always re-derived from its baseline, whatever the C# sources are. The output becomes a function of the inputs, not of evaluation order or of which compilation ran first. The UserSourcesFingerprint gate from [XSG] XIHR: re-derive the pending UpdateComponent patch on repeated evaluation #40233 (and the extra compilation input to the pipeline) is removed.
  • Runtime (XamlIncrementalHotReloadHandler): a root that has the companion type counts as a XAML change only if the delta lists the companion and UpdateComponent() isn't empty. This keeps structural changes, which reset the body to empty, out, as before. A companion listed without its root is mapped back to the root. Roots without a companion (older generated code) keep the existing empty-body check. UpdateRequested.HandledTypes and the UpdateApplied/UpdateSkipped/UpdateFailed contract are unchanged.

With this, a C#-only edit re-emits the same patch. UpdateComponent() and the companion are byte-identical, so they aren't in the delta and the patch isn't re-applied. This matters because patches aren't always idempotent: reorders use RemoveAt/Insert. As a side benefit, a XAML edit whose delta was rejected (e.g. it was combined with a C# rude edit) still carries its patch on the next generation instead of an empty body.

Remaining limitation (not addressed here): a throwaway run with different XAML (e.g. an intermediate keystroke) still advances the cached "previous" XAML. The next real patch is then diffed from that intermediate state rather than from what the app last applied. Fixing that would need knowledge of the last applied generation.

Tests

  • XamlIncrementalHotReloadPipelineTests
  • XamlIncrementalHotReloadE2ETests (real MetadataUpdater.ApplyUpdate)
    • CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch checks that a live label changed at runtime isn't overwritten by a C#-only delta.
    • UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated updates the existing classification test.
  • The test harness now lists the companion type among the delta's updated types only when its fingerprint changed, like Roslyn does.
  • Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests: two handler tests cover a root with a companion type and a companion listed alone.

Validation

  • DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj: 855 passed, 0 failed, 0 skipped.
  • With only the generator/state change reverted, 3 new tests fail, including the throwaway test. With only the handler change reverted, the 2 E2E runtime tests fail.
  • dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj: 2250 passed, 2 failed, 8 skipped. The 2 failures (TwoWayDecimalBinding_*) depend on the dev machine's locale and pass with DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1.
  • dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HotReload": 12 passed.
  • dotnet format whitespace --verify-no-changes on the changed files: clean.

Issues Fixed

Fixes #36937

Follow-up to #40233.

github-actions Bot and others added 30 commits November 16, 2026 22:19
… content (#40169)

<!--
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 |

- [ ] 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.

### Issue Description

On Android 16, switching between Entries with different keyboard types
can briefly display the previous keyboard layout before showing the
correct one, causing visible flickering. In the reproduction, each Entry
is dynamically added to a ContentView and replaced with a Label when
another cell is selected.

### Root Cause

RemoveAllViews() detached the focused native EditText without explicitly
clearing its focus. Removing a view is not the same as completing a
focus transition.

Android updates the keyboard through its input-method system
asynchronously. If the outgoing text field is still considered the
active input target, the keyboard can temporarily retain its
configuration while Android processes detachment, transfers focus, and
establishes the incoming Entry’s input connection.


### Description of Change

- Clear native focus from the outgoing ContentView content before
calling RemoveAllViews() on Android.
- Previously, removing content containing a focused Entry could leave
stale input-method state. When switching between Entries with different
keyboard types, the previous keyboard layout could briefly appear before
the correct layout.
- Explicitly clearing focus before removing the native view ensures that
the outgoing Entry relinquishes focus before the next Entry is attached
and focused.


### Issues Fixed
Fixes #38799

### Tested the behaviour in the following platforms
- [x] Android
- [ ] Windows
- [ ] iOS
- [ ] Mac

### Output Screenshot
Before Issue Fix | After Issue Fix |
|----------|----------|
|<video width="300" height="600" alt="Before Fix"
src="https://github.com/user-attachments/assets/62b49b56-86e3-48e8-9ae1-19e92106f5b0">|<video
width="100" height="100" alt="After Fix"
src="https://github.com/user-attachments/assets/55caabe9-2021-43c0-9407-31bbad08db4c">|

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
<!--
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 |

- [ ] 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
This pull request primarily improves shadow rendering support for
Win2D-based shapes on Windows and updates test conditions related to
shadow features. The most significant changes are the addition of logic
to handle `W2DGraphicsView` with `ShapeDrawable` in shadow rendering, as
well as updates to test preprocessor directives and references.

**Shadow rendering improvements:**

*
[`ShadowExtensions.cs`](diffhunk://#diff-6c904999b229ffd792f069a6a0ddaf850a67a046624c4e915b57ece230ca9a09R43-R51):
Added logic in `GetAlphaMaskAsync` to handle `W2DGraphicsView` with
`ShapeDrawable`, using the live visual for shadow rendering since
`RenderTargetBitmap` cannot capture Win2D content.
*
[`ShadowExtensions.cs`](diffhunk://#diff-6c904999b229ffd792f069a6a0ddaf850a67a046624c4e915b57ece230ca9a09R7):
Added necessary using directives for `Microsoft.Maui.Graphics.Win2D` and
aliased `ShapeDrawable` for clarity.
[[1]](diffhunk://#diff-6c904999b229ffd792f069a6a0ddaf850a67a046624c4e915b57ece230ca9a09R7)
[[2]](diffhunk://#diff-6c904999b229ffd792f069a6a0ddaf850a67a046624c4e915b57ece230ca9a09R16)

**Test updates:**

*
[`ShadowFeatureTests.cs`](diffhunk://#diff-560f9cb1cec21af3a1c6ae51a0b30849aea0f019d519990a0b24dba91971d67fL218-R218):
Updated the Windows shadow test exclusion to reference the correct
GitHub issue (`40172` instead of `27732`).
*
[`BoxViewFeatureTests.cs`](diffhunk://#diff-3455b54055dcfe7c51234f9e7cc13af77da827ea7b097f7fe77d44acad4b0f79L163):
Removed the preprocessor directive that disabled shadow tests on
Windows, re-enabling those tests.
[[1]](diffhunk://#diff-3455b54055dcfe7c51234f9e7cc13af77da827ea7b097f7fe77d44acad4b0f79L163)
[[2]](diffhunk://#diff-3455b54055dcfe7c51234f9e7cc13af77da827ea7b097f7fe77d44acad4b0f79L235)
<!-- Enter description of the fix in this section -->

### 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. -->

Fixes #31821 

### Tested the behavior in the following platforms
- [x] Windows
- [ ] Android
- [ ] iOS
- [ ] Mac

| Before Issue Fix | After Issue Fix |
|----------|----------|
| <img width="998" height="944" alt="BeforeFix1821"
src="https://github.com/user-attachments/assets/b4a526d3-a615-4fea-9ede-55129e23314e"
/> | <img width="1259" height="952" alt="AfterFix31821"
src="https://github.com/user-attachments/assets/17282ba8-85cb-48a0-814b-beac7642c7b6"
/> |
<!--
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: Jakub Florkowski <kubaflo123@gmail.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!

<!--
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

Most of the recent `net11` `maui-pr-uitests` red comes from Android API
30 jobs that are cancelled at the 240-minute job limit. The cause is a
lost emulator, not product regressions.

**What happens** (raw logs of build
[1680926](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1680926)
and
[1680462](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1680462),
e.g. API 30 Navigation and API 30 CollectionView3):

1. The emulator boots normally, and tests run for about 9–12 minutes.
2. `[Logcat] Logcat terminated with code 255` appears and adb reports
`device 'emulator-5554' not found`. The emulator is gone.
3. The remaining fixtures of attempt 1 fail quickly once session
recreation fails.
4. `RunUITestsWithRetry` starts **UI test attempt 2** against the
still-missing device. Every fixture now waits about 3.7 minutes in
`AppiumServerContext.CreateUIClientContext`: 11 tries × Appium's
20-second "Could not find a connected Android device".
5. The job runs until Azure DevOps cancels it at 240 minutes. Most of
the failed rows in those builds are these setup failures.

The same tests pass on `candidate/11.0.1xx-sr2`, and none of
`eng/devices`, `UITest.Appium` or `UITest.NUnit` differs between
`net11`, the candidate and `main`. So this is an infrastructure flake
that the retry path amplifies, with no existing fix to backport.

**Fix**

- `RunUITestsWithRetry` gets an optional `beforeAttempt` hook that runs
before **every** attempt, including attempt 1. The iOS, Mac Catalyst and
Windows callers are unchanged.
- Running it only before retries was not enough. In this PR's run
[1682445](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1682445),
three API 30 jobs installed the app and then lost the emulator during
the roughly 2-minute UI-test project build, before attempt 1. Every
fixture in attempt 1 then waited 3 min 40 s (Shell1: 68 fixtures,
CarouselView: 99, 0 passed), and the jobs were cancelled at 240 minutes
before the retry hook could run.
- On Android, the hook checks `sys.boot_completed`:
  - If the device is healthy, it does nothing (one `getprop`).
- If the emulator started by the script is gone, it cleans up, restarts
the emulator through the existing `HandleVirtualDevice` path, and
reinstalls the app with `ExecutePrepareUITests` before the attempt.
- If that cleanup throws (for example `AdbEmuKill` fails), the hook
kills the old emulator process directly before restarting, so the same
AVD is never started twice. In a local fault-injection check, the
previous code left the old PID alive, started a duplicate, and timed out
after about 10 minutes; with this fallback, recovery finished in 39 s.
- Before restarting, the hook waits (bounded by
`EmulatorKillTimeoutSeconds`) until the old process has **confirmed
exited**. If it hasn't, the hook fails the attempt rather than start a
duplicate instance of the same AVD.
- If the device was not started by the script, it logs a warning and
runs the tests as before. Local runs against a user-supplied device are
unchanged.
- `uitest-retry.cake`: a retry no longer leaves never-run ignored tests
as failures. When the device is lost during a fixture's OneTimeSetUp,
NUnit fails every child with `site="Parent"`. If OneTimeTearDown also
throws, the fixture site becomes `TearDown` instead of `SetUp`. Ignored
tests then come back from a green retry as Skipped/Ignored: either a
static `[Ignore]` with the same reason, or a runtime `Assert.Ignore`
with `runstate="Runnable"`. The merge accepted only the
`SetUp`+static-reason shape, so the job failed even though the retry was
green.
- The merge now treats a parent-site error as never-run when the fixture
failed in setup (site `SetUp`, or the child's message starts with
`OneTimeSetUp:`). It accepts a retry that ignores such a test, and
accepts fixtures that contain only such recovered ignores. A test that
actually ran and failed is still never accepted.

**Validation**

- `dotnet cake eng/devices/{android,catalyst,windows,ios}.cake
--target=uitest --dryrun` compiles. iOS has the same pre-existing local
teardown error with and without this change.
- Local end-to-end check on an API 30 arm64 emulator (adb pinned to
`emulator-5554`): a temporary target ran the real `connectToDevice` and
`uitest-prepare` (installed the app), then called
`EnsureDeviceForUITestAttempt` as at the attempt-1 call site.

  | Case | Result |
  | --- | --- |
  | Healthy device | Hook returned in 0.0 s (no-op) |
| `adb emu kill` after install (the 1682445 mode) | `boot_completed` →
null; hook logged the warning, restarted the emulator, and reinstalled
the app (XHarness exit code 0) in 46 s; afterwards `boot_completed` = 1
and `pm path` showed the app |
  | Healthy again after recovery | 0.0 s no-op |
| Missing device not started by the script | Warning logged, no throw |

- Confirmed-exit fault injection (local, API 30):

  | Scenario | Before | After |
  | --- | --- | --- |
| Cleanup returns but the emulator stays alive | Duplicate start; boot
timed out after 10m32s | Attempt fails after 60 s with "did not exit …
not restarting"; no duplicate |
| Emulator killed externally | — | One restart, app reinstalled,
XHarness exit 0 (49 s) |
| Cleanup throws | — | Direct kill, one restart, XHarness exit 0 (41 s)
|

- **CI proof of recovery:** in this PR's run
[1682664](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1682664),
Controls (API 30) Label lost the emulator during attempt 1. All 126
tests failed in OneTimeSetUp, about 3m40s each. Before attempt 2 the
hook restarted Emulator_30 and reinstalled the app, and **attempt 2
passed 124 tests with 2 skipped** in 14 minutes.
- **Retry merge:** that job was still marked failed because two
never-run ignored tests stayed Failed: `Issue488TestsLongTextRotation`
(static `[Ignore]`, fixture site `TearDown`) and
`LabelUITests.IsEnabled` (runtime `Assert.Ignore`). The real TRX and
NUnit XML from both attempts were replayed offline through
`UITestRetry.MergeResults`:

  | Input | Before | After |
  | --- | --- | --- |
| Real 1682664 Label artifacts | Merged outcome Failed (`IsEnabled`,
`Issue488TestsLongTextRotation`) | Completed, 0 failed, no run errors |
  | Retry `IsEnabled` actually fails | — | Failed |
  | Original `IsEnabled` actually ran (site not Parent) | — | Failed |
  | Static ignore reason mismatch | — | Failed |
  | No `OneTimeSetUp:` evidence | — | Failed |

The replay harness was local only; no test was committed, per policy for
CI scripts.
- Final validation is this PR's own `maui-pr-uitests` run.

### Issues Fixed

Fixes Android API 30 `maui-pr-uitests` jobs on `net11` hanging until the
240-minute timeout after the emulator is lost mid-run. Also fixes
recovered retries still failing the job when never-run ignored tests
come back as Skipped/Ignored.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…#40300)

<!-- 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

Follow-up to #40273, which recovers a lost Android emulator **between**
UI test attempts. That recovery cannot help when the emulator dies
**during** an attempt: every remaining fixture then calls
`AppiumServerContext.CreateUIClientContext`, which tries to create a
session 11 times (`retries++ < 10`, about 20s each because UiAutomator2
waits 20s for a device). Each fixture fails only after **3m40s**.

Evidence from `maui-pr-uitests` run
[1682664](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1682664)
(PR #40273), job "Controls (API 30) Label":
- The emulator vanished about 3 minutes into attempt 1.
- All 126 Label tests then failed in `OneTimeSetUp` with `Could not find
a connected Android device in 20000ms`, each after 3m40s.
- The test step took **195 minutes**; normally it takes 16–23 minutes.
- Only after that did the between-attempt recovery restart the emulator.

`net11` run
[1683205](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1683205)
showed the same job still running after 115+ minutes. The candidate
(#40116) and `main` have identical copies of this file, so no existing
fix covers it.

**Change:** after one fixture exhausts all retries, later fixtures in
the same test process get a single attempt. A successful session
restores full retries.
- The first failure still gets the full retry budget, so transient
Appium or device hiccups keep the current tolerance.
- CI retries start a new `dotnet test` process, so each attempt starts
with full retries, and the emulator recovery from #40273 still runs
before it.
- No test is skipped, and no tolerance or baseline changes.

### Validation

Ran a local console harness that references `UITest.Core` and
`UITest.Appium`, starts the real Appium server (uiautomator2 3.9.1), and
calls `CreateUIClientContext` with an Android config and no connected
device. This simulates fixtures after the emulator is lost.

| Build | Fixture 1 | Fixture 2 | Fixture 3 |
| --- | --- | --- | --- |
| `net11` (baseline, d0547a0) | 221s | 221s | — |
| This PR | 221s | 20s | 20s |

For a 126-fixture category, the time to fail after losing the emulator
drops from about 7.7h (capped by the job timeout) to about 45 min. The
same error message is still reported for every test.

### Issues Fixed

Fixes CI hangs in `maui-pr-uitests` Android jobs after mid-attempt
emulator loss (no tracking issue).

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

This pull request updates the following dependencies

[marker]: <> (Begin:f4928934-9e75-4ba7-b3d0-757a5edf906c)
- **Subscription**:
[f4928934-9e75-4ba7-b3d0-757a5edf906c](https://maestro.dot.net/subscriptions?search=f4928934-9e75-4ba7-b3d0-757a5edf906c)
- **Build**:
[20261109.6](https://dev.azure.com/dnceng/internal/_build/results?buildId=3130547)
([340580](https://maestro.dot.net/channel/8298/github:dotnet:dotnet/build/340580))
- **Date Produced**: November 10, 2026 12:07:03 AM UTC
- **Commit**:
[40ce56ee174a4f1914ef78ea848f3198a160e815](dotnet/dotnet@40ce56e)
- **Branch**:
[release/11.0.1xx](https://github.com/dotnet/dotnet/tree/release/11.0.1xx)

[DependencyUpdate]: <> (Begin)

- **Dependency Updates**:
  - From [11.0.0 to 11.0.1][1]
     - Microsoft.AspNetCore.Authentication.Facebook
     - Microsoft.AspNetCore.Authentication.Google
     - Microsoft.AspNetCore.Authentication.MicrosoftAccount
     - Microsoft.AspNetCore.Authorization
     - Microsoft.AspNetCore.Components
     - Microsoft.AspNetCore.Components.Analyzers
     - Microsoft.AspNetCore.Components.Forms
     - Microsoft.AspNetCore.Components.Web
     - Microsoft.AspNetCore.Components.WebAssembly
     - Microsoft.AspNetCore.Components.WebAssembly.Server
     - Microsoft.AspNetCore.Components.WebView
     - Microsoft.AspNetCore.Metadata
     - Microsoft.Extensions.Configuration
     - Microsoft.Extensions.Configuration.Abstractions
     - Microsoft.Extensions.Configuration.Json
     - Microsoft.Extensions.DependencyInjection
     - Microsoft.Extensions.DependencyInjection.Abstractions
     - Microsoft.Extensions.FileProviders.Abstractions
     - Microsoft.Extensions.Hosting.Abstractions
     - Microsoft.Extensions.Logging
     - Microsoft.Extensions.Logging.Abstractions
     - Microsoft.Extensions.Logging.Console
     - Microsoft.Extensions.Logging.Debug
     - Microsoft.Extensions.Primitives
     - Microsoft.JSInterop
     - Microsoft.NETCore.App.Ref
  - From [11.0.0-beta.26555.108 to 11.0.0-beta.26559.106][1]
     - Microsoft.DotNet.Arcade.Sdk
     - Microsoft.DotNet.Build.Tasks.Feed
     - Microsoft.DotNet.Build.Tasks.Installers
     - Microsoft.DotNet.Build.Tasks.Workloads
     - Microsoft.DotNet.Helix.JobMonitor
     - Microsoft.DotNet.Helix.Sdk
     - Microsoft.DotNet.RemoteExecutor
     - Microsoft.DotNet.SharedFramework.Sdk
     - Microsoft.DotNet.XUnitExtensions
  - From [11.0.100-rtm.26555.108 to 11.0.101-servicing.26559.106][1]
     - Microsoft.NET.Sdk

[1]: dotnet/dotnet@1f64ef4...40ce56e

[DependencyUpdate]: <> (End)

[marker]: <> (End:f4928934-9e75-4ba7-b3d0-757a5edf906c)

[marker]: <> (Begin:9a046932-c60c-436e-8fc7-8ea2f5902cb5)
- **Subscription**:
[9a046932-c60c-436e-8fc7-8ea2f5902cb5](https://maestro.dot.net/subscriptions?search=9a046932-c60c-436e-8fc7-8ea2f5902cb5)
- **Build**:
[11.0.1xx-7ff9886196157cc5aea76f227cbf06329629cf6c-1](https://dev.azure.com/devdiv/DevDiv/_build/results?buildId=15967460)
([340520](https://maestro.dot.net/channel/8298/github:dotnet:android/build/340520))
- **Date Produced**: November 9, 2026 7:08:35 PM UTC
- **Commit**:
[7ff9886196157cc5aea76f227cbf06329629cf6c](dotnet/android@7ff9886)
- **Branch**:
[release/11.0.1xx](https://github.com/dotnet/android/tree/release/11.0.1xx)

[DependencyUpdate]: <> (Begin)

- **Dependency Updates**:
  - From [37.2.31 to 37.2.32][2]
     - Microsoft.Android.Sdk.Windows

[2]: dotnet/android@c6663f2...7ff9886

[DependencyUpdate]: <> (End)

[marker]: <> (End:9a046932-c60c-436e-8fc7-8ea2f5902cb5)

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Fixes an infinite loop when synchronizing SelectedIndex and SelectedItem
by only updating SelectedIndex if the value changes. Adds a unit test to
ensure that changing ControlTemplate from SelectedIndexChanged does not
cause recursive events (fixes #8874).

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

### Description of Change

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

### 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. -->

Fixes #8874

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->
<!-- 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.
-->

### Description of Change

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

Restore custom Shape implementations of `IShape.PathForBounds` when a
renderer requests stroke-aware geometry.

**Regression introduced by**

[PR #37319 — Fix Rectangle Rendering as a Thin Line for Small
Heights](#37319).

The supplied reproduction works on MAUI `10.0.120` and fails on
`10.0.130` on Android and iOS.

**Root cause**

That PR introduced the internal `IShapeWithStroke` interface to
distinguish standalone shape geometry from Border stroke-aware geometry.
Platform renderers were updated to prefer this interface over
`IShape.PathForBounds`.

Custom Shapes inherit `IShapeWithStroke` from `Shape`, even when they
re-implement the public `IShape.PathForBounds` contract. The inherited
stroke-aware implementation directly calls the base path-building
method, bypassing the custom implementation. Applications cannot
re-implement `IShapeWithStroke` because it is internal.

In the reported `FieldShape`, the skipped method initializes the
fallback width and height used to construct the outline. Without that
call, the shape uses incorrect dimensions, producing a malformed outline
instead of the expected rounded border and label gap.

**Fix**

- Dispatch `Shape.IShapeWithStroke.PathForBounds` through
`IShape.PathForBounds`, honoring custom implementations.
- Preserve the requested stroke context for built-in shapes using the
base implementation.
- Save and restore that context with `try`/`finally`, including when
path generation throws.
- Leave RoundRectangle's dedicated implementation unchanged.


### 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. -->

Fixes #40129

<!--
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: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…40128)

<!-- 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.
-->


### Description of Change

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

Fixes NavigationPage.TitleView being shifted upward and clipped on iOS
26+ when the navigation bar clips its contents.

The full navigation bar can be taller than UIKit's title area. On the
iOS 26.5 reproduction, the bar is 54 pt high while the title area is 44
pt high. Initializing the title container to the full bar height causes
UIKit to position its wrapper at y = -5, clipping the top of the title.

- Initialize the title container using the navigation bar's width and
the title-height fallback, rather than the full bar height.
- In NavigationRenderer, use the attached superview's height instead of
prioritizing the cached navigation-bar height.
- Apply the initial-height correction to NavigationViewHandler as well.
- Preserve the iOS 26 autoresizing-mask workaround and navigation-bar
layout-change tracking.
- Add regression coverage for automatic, short, and tall title views,
exercised against both navigation implementations.

#### Regression origin

The likely introducing change is
[#32798](#32798), the .NET
10 servicing backport of
[#32341](#32341) ("Fix iOS
26 TitleView covering content in Shell and NavigationPage").

[Commit
3218849](3218849)
introduced both the full-bar-height initial frame and the cached
`_navigationBarHeight` preference in `ToolbarHeight`. The change is
absent from MAUI 10.0.10 and present in 10.0.11, matching the [reported
first failing
version](#40068 (comment)).
This attribution is based on source and release ancestry, not a
parent-versus-commit runtime bisect.

This fix retains the autoresizing-mask workaround from that PR; it
corrects the assumption that the title area must have the same height as
the full navigation bar.

#### Before / after

Both screenshots use the same local Sandbox reproduction on an iPhone 17
Pro simulator running **iOS 26.5**, with `UINavigationBar.ClipsToBounds
= true`. "Before" is the unfixed local framework build, not a separate
MAUI 9 package run.

| Before fix — title clipped | After fix — title visible |
| --- | --- |
| <img
src="https://github.com/user-attachments/assets/9c9f4b39-da15-45de-a0e9-71fb96d08687"
alt="Before fix: Czech title clipped at the top; container height 54 pt
and wrapper y minus 5 pt" width="350" /> | <img
src="https://github.com/user-attachments/assets/e42f4c2e-c2e9-4464-92cb-63f516c81112"
alt="After fix: Czech title and diacritics visible; container height 44
pt and wrapper y zero" width="350" /> |

The navigation bar remains 54 pt high in both runs. The title container
changes from **54 pt to 44 pt**, and the wrapper moves from **y = -5 to
y = 0**.

### 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. -->

Fixes #40068

<!--
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: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…aries (#40103)

### Description of Change

When a `ResourceDictionary` is inflated at runtime (for example a style
dictionary without code-behind loaded through `Source=`), a
`BasedOn="{StaticResource …}"` lookup can only see resources already
added in that same file, plus application resources that already exist.
A base style living in a sibling merged dictionary is not reachable yet,
so loading the dictionary throws `XamlParseException: StaticResource not
found for key ButtonBaseStyle` and crashes the app at startup. Declaring
a global (implicit) style based on a shared keyed style this way is the
scenario from the issue.

**Fix**

In `StaticResourceExtension.ProvideValue`, when the unresolved target is
`Style.BasedOn` and the XAML root being parsed is a `ResourceDictionary`
(one that is still being loaded), defer the lookup to apply time through
the existing `Style.BaseResourceKey` mechanism instead of throwing. The
base style is then resolved through the consuming element's resource
scope, where the merged dictionaries are available. Failed lookups
anywhere else keep throwing exactly as before.

**Tests**

`Maui24667` (Xaml.UnitTests) inflates a page whose resources merge two
source dictionaries — a keyed `ButtonBaseStyle` and an implicit `Button`
style based on it — plus the issue's implicit-`BaseResourceKey` snippet,
and verifies the base setters are applied. The test runs on all three
inflators (Runtime, XamlC, SourceGen).

| | Without fix | With fix |
|---|---|---|
| Implicit style with `BasedOn="{StaticResource …}"` to a keyed style in
a sibling merged dictionary | `XamlParseException`: StaticResource not
found for key ButtonBaseStyle | Style applied, base setters inherited |
| Implicit style with `BaseResourceKey` (issue snippet) | works | works
|
| Full Xaml.UnitTests + Core.UnitTests | — | No new failures |

### Issues Fixed

Fixes #24667
…osite collection (#40102)

### Description of Change

A `RadioButton` whose `ControlTemplate` comes from an application-level
implicit `Style` renders correctly on iOS but never responds to taps
(#14949; the same mechanism is behind #22377 and #19478).

Because `Application.Current` resources are available as soon as an
element is constructed, the implicit style applies the `ControlTemplate`
while the `RadioButton` is still running its base-class constructors:
`StyleableElement`'s constructor applies the merged style, which
triggers `OnApplyTemplate` → `UpdateIsEnabled` →
`GestureRecognizers.Add(...)`. At that point `View`'s constructor body
has not yet subscribed to `_gestureRecognizers.CollectionChanged`, so
the tap gesture never reaches `CompositeGestureRecognizers`. The
iOS/MacCatalyst `GesturePlatformManager` attaches platform recognizers
exclusively from that composite collection, so no
`UITapGestureRecognizer` is ever created. Android and Windows resolve
taps from the raw `GestureRecognizers` collection, which is why only iOS
is affected. With a page-level style the template is applied after
construction (on parenting), so the composite collection stays in sync
and taps work.

**Fix**

After `View`'s constructor subscribes to the gesture collection, sync
any recognizers that were added during base construction into
`CompositeGestureRecognizers` (setting their `Parent`, as the
collection-changed path does). This repairs the general case — any
gesture wired while base constructors run — at no cost to views
constructed normally, whose collection is empty at that point.

**Tests**

| | Without fix | With fix |
| --- | --- | --- |
|
`TemplateFromAppLevelImplicitStyleAddsTapGestureToCompositeRecognizers`
| Fails — `CompositeGestureRecognizers` is empty, so the RadioButton
ignores taps on iOS | Passes — the tap gesture is present in both
collections |
| Full Controls.Core.UnitTests | — | No new failures |

### Issues Fixed

Fixes #14949

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
### Description of Change

When an absolute Shell route is prefixed with `..` segments — e.g.
`GoToAsync("//../../Page2")` while two registered-route pages are pushed
on the current tab — the `..` segments are silently lost.
`ShellUriHandler.FormatUri` only handles `..` on fully relative routes,
so for `//`-prefixed routes the dots reach `ConvertToStandardFormat`,
where standard `Uri` dot-segment normalization deletes them. The request
degrades to a plain `//Page2` tab switch and the pages stay on the
previous tab's navigation stack, so re-selecting that tab shows the old
detail page instead of its root.

Because the navigation target is a different `ShellSection`, the pop
cannot be expressed in the rewritten URI (stack diffing only applies to
the target section) — the pages have to be removed from the section
being navigated away from.

**Fix**

Capture the number of leading `..` segments before the request is
resolved (`ShellUriHandler.CountLeadingDotDotSegments`) and, once the
navigation is accepted and the shell element switch has completed,
remove one page per `..` from the top of the previous section's stack —
the same `RemovePage` pattern the modal cleanup in
`ShellNavigationManager.GoToAsync` already uses. The removal is clamped
at the section root, runs only when the section actually changed
(same-section absolute routes already reset their stack), and never runs
when navigation is cancelled or deferred.

**Tests**

Added to `ShellNavigatingTests` using the issue's exact scenario (tabs
Page1/Page2/Page3, registered routes Page4/Page5 pushed on Page3's tab).

| | Without fix | With fix |
| --- | --- | --- |
| `GoToAsync("//../../Page2")` | Switches to Page2; Page4 and Page5
remain on Page3's stack | Switches to Page2; Page3's stack back to its
root |
| `GoToAsync("//../Page2")` | Switches to Page2; both pages remain |
Switches to Page2; only Page5 popped |
| Existing Shell suites | — | 566/566 pass; full Core.UnitTests has no
new failures |

### Issues Fixed

Fixes #15166

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
… bounds (#40100)

### Description of Change

On Android, a SwipeView stops tracking the swipe as soon as the pointer
leaves the bounds of its content while the gesture is still in progress,
and resumes only when the pointer re-enters — small vertical drift
during a horizontal swipe keeps "freezing" the gesture (very noticeable
with SwipeViews inside a CollectionView).

**Root cause**

Two guards re-evaluate an already-running gesture as if it were a new
one:

- `ProcessTouchMove` returns early when the current point is outside the
content bounds, even when `_isSwiping` is already set.
- `OnTouchEvent` filters `ACTION_MOVE` through `ShouldInterceptTouch`,
which recomputes the swipe direction from the total pointer travel —
once the vertical drift exceeds the horizontal distance it reclassifies
the gesture as Up/Down, finds no items for that direction and drops the
move.

**Fix**

Both checks now only apply before a swipe starts; once `_isSwiping` is
set, moves are processed wherever the pointer is, which is the standard
platform gesture behavior (the drawer, for example, keeps tracking past
its bounds).

A second commit applies non-animated swipe translations directly instead
of going through a zero-duration `ViewPropertyAnimator`. The
zero-duration animator still needs a frame to run, so a programmatic
`Open(animated: false)` followed by detaching the view left a pending
animator keeping the view tree alive — which made the existing
`ItemsDoNotLeak` device test order-sensitive. With the direct assignment
the SwipeView category is stable across repeated runs.

**Tests**

`SwipeViewTests.SwipeKeepsTrackingWhenThePointerLeavesTheBounds`
(Android device test): starts a swipe with synthetic motion events,
moves the pointer below the view bounds while continuing the horizontal
drag, and checks the content keeps following.

| | Without fix | With fix |
|---|---|---|
| Android emulator (API 37) | Fails: `The swipe stopped tracking when
the pointer left the bounds (TranslationX -52, was -52)` | Passes.
SwipeView category 22/22, three consecutive runs |

### Issues Fixed

Fixes #37089

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…ShellSection (#40052)

<!-- 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!

### Description of Change

On Android with the handler-based Shell, an app crashes with
`InvalidOperationException: VirtualView cannot be null here` in
`ShellSectionWrapperFragment.OnResume()` when it resumes after a
ShellItem was replaced while it was in the background.

When a section is removed, `ShellSectionHandlerAdapter.Dispose()`
disconnects its handler. Since #37048 it leaves the wrapper fragment to
`FragmentManager`, which can still resume it. `OnResume()` already
returns early for a disconnected handler, but it checks
`_handler.VirtualView is null`. That reads the typed
`ElementHandler<ShellSection, AView>.VirtualView`, whose getter throws
once disconnected, so the guard itself throws.

The fix checks the untyped `((IElementHandler)_handler).VirtualView`,
the same way `ShellSectionHandler.iOS.cs` does.

Not changed here: several other `VirtualView is null` checks in
`ShellSectionHandler.Android.cs` (for example in
`IsCurrentlyActiveSection()` and `SetupViewPagerAdapter()`) have the
same problem. They aren't reached on this path, so I left them out to
keep this PR small.

### Tests

Added
`ShellHandlerTests_Shell.ResumingFragmentOfRemovedShellSectionDoesNotThrow`.
It creates a section renderer, disposes it the same way
`ShellItemHandler.UpdateSections` does for a removed section, and
resumes its wrapper fragment.

Ran `ShellHandlerTests_Shell` locally on an Android emulator (API 36,
x86_64):
- With the fix: 80/80 pass.
- Without the fix: the new test fails with
`System.InvalidOperationException: VirtualView cannot be null here at
ShellSectionWrapperFragment.OnResume()`; the other 79 pass.

### Issues Fixed

Fixes #40051

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
Generalize context transfer for all BindingBase types in BindableObject,
and ensure correct specificity/context handling in MultiBinding when
targeting BindingContext. Add tests to verify MultiBinding context
behavior in various scenarios.

Fixes #10792

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
Add handling for Binding.DoNothing in value converters to skip
target/source updates in BindingExpression and TypedBinding. Introduce
BindingDoNothingTests to verify correct behavior for one-way, two-way,
initial binding, TargetNullValue, and StringFormat scenarios.

 Fixes #11740

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…9920)

<!-- 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!

### Issue details
On the Project page, iOS VoiceOver reads the names of Tags and Icons but
does not announce whether they are selected or unselected. The expected
behavior is for VoiceOver to announce each item’s name and selection
state.
 
### Root cause
For these selectable CollectionView items, Android and macOS announce
selection state through native accessibility behavior. iOS VoiceOver
does not announce the selected/unselected state, and the item
descriptions contain only the names. Therefore, the state must be
included in the semantic description on iOS; doing so on Android and
macOS would duplicate their native announcement.
 
### Description of changes
Updated the visual states in ProjectDetailPage.xaml to include
“Unselected” in the Normal state and append “Selected” to the item
description in the Selected state on iOS only.
 
### Issues Fixed

Fixes #39907

### Screenshot

| Before Issue Fix | After Issue Fix |
|----------|----------|
| <img width="2000" height="1000"
src="https://github.com/user-attachments/assets/9957c168-b220-43b6-9a1c-63514e73bddc">
| <img width="2000" height="1000"
src="https://github.com/user-attachments/assets/4c930934-937e-485d-aa91-9cae5630825d">
|

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
### Description of Change

When a modal page is pushed at startup, the Shell toolbar gets the
default dark color instead of the colors set on the Shell, and stays
wrong after the modal closes (on Android and Windows, which drive the
toolbar from the resolved `ShellAppearance`).

**Root cause**

`GetAppearanceForPivot` walks up from the pivot's presented page to
collect the `Shell.*` appearance values. For a `ShellSection` pivot,
`WalkToPage` used `IShellSectionController.PresentedPage`, which returns
the top modal page while a modal is open. Modal pages are parented to
the `Window`, not the Shell, so the walk immediately left the Shell
tree, found nothing and returned null — and the toolbar fell back to the
default colors.

**Fix**

`WalkToPage` now resolves the `ShellSection` to the top page of its own
navigation stack — exactly what `PresentedPage` returns when no modal is
open — so appearance resolution gives the same result whether or not a
modal is sitting on top.

**Tests**

`ShellAppearanceTests.AppearanceIsResolvedWhileAModalPageIsOpen`: sets
`Shell.BackgroundColor`, pushes a modal page, then registers an
appearance observer for the current section.

| | Without fix | With fix |
|---|---|---|
| `main` (2f3276c) | Fails: the observer gets a null appearance |
Passes; Controls.Core.UnitTests 6734 passed (the one failure is a
pre-existing decimal-separator locale test that fails on `main` on this
machine too) |

### Issues Fixed

Fixes #18409

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
Refactor BindingCondition to track state via a new attached property,
ensuring triggers apply correctly when the bound value is initially
null. Update property change logic to only raise ConditionChanged on
actual state changes. Add unit tests to verify correct behavior with
null values and MultiTrigger scenarios, addressing issue #6847.

Fixes #6847

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…conversion during repeated rendering (#39909)

<!-- 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!


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

### Root cause

The issue occurs because of missing deterministic disposal of temporary
Android graphics objects during repeated path rendering.
PlatformCanvas.ClipPath created Android Path objects without disposing
them, while arc-conversion helpers created undisposed RectF objects for
each arc segment. Their cleanup depended on garbage collection and
finalization, contributing to memory growth during sustained rendering.

### Solution description

The fix involves using scoped disposal for converted Android paths in
ClipPath, PlatformDrawPath, and FillPath, ensuring cleanup even when
subsequent operations throw. It also replaces temporary RectF
allocations with the coordinate-based ArcTo overload in all three
arc-conversion helpers.

This reduces platform-object allocations while preserving path geometry,
winding rules, and caller-owned PathF instances.

Validated the behavior in the following platforms
 
- [x] Android
- [ ] Windows
- [ ] iOS
- [ ] Mac
 
### Issues Fixed
  
Fixes #39675

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Android| <video
src="https://github.com/user-attachments/assets/252c5f3f-5393-414c-b0f7-b4572b1a9e14">|
<video
src="https://github.com/user-attachments/assets/122e7ef9-acb2-4b5d-9152-1bdeefa46ebf">|

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
… view (#39900)

### Description of Change

With a `FlyoutPage` on Android, a tap on an empty area of the open
flyout fell through to the detail page behind it and clicked its
controls. The flyout view is added to the `DrawerLayout` without
anything consuming the touches its content doesn't handle, so an
unhandled `ACTION_DOWN` inside the open drawer continued to the detail
sibling — the classic Android drawer issue that a plain app solves with
`android:clickable="true"` on the drawer pane.

**Fix**

`MauiDrawerLayout.SetFlyoutView` now subscribes a `Touch` handler on the
flyout view that marks the leftover events handled. `MauiDrawerLayout`
is shared, so this covers both `FlyoutPage` and the Shell flyout.

- Controls inside the flyout are unaffected: the handler only sees
touches no child consumed.
- The drawer's swipe-to-close gesture is unaffected: `DrawerLayout`
intercepts drags before they reach the pane.
- The accessibility tree is unchanged, because an `OnTouchListener`
doesn't mark the view clickable the way `Clickable = true` would.
- There's deliberately no unsubscribe in `Disconnect`: the handler is a
static method that keeps nothing alive, and the Java peer can already be
disposed by the time the Shell handler disconnects, so touching it there
would throw an `ObjectDisposedException`. The subscription on a replaced
flyout view is removed in `SetFlyoutView` itself.

**Tests**

`FlyoutPageTests.TapOnTheOpenFlyoutDoesNotReachTheDetailPage` (Android
device test): opens the flyout, dispatches a tap in the middle of it and
checks the detail's platform view never sees the touch.

| | Without fix | With fix |
|---|---|---|
| Android emulator (API 37) | Fails: the tap reached the detail page |
Passes. FlyoutPage category 18/18, Shell category 184/184 |

### Issues Fixed

Fixes #14609
…ed scrolling (#39882)

<!-- 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!

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

### Description of Change

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

Fix CollectionView height updates after replacing ItemsSource with fewer
items on iOS and Mac Catalyst, while preserving sizing behavior when
CollectionView is nested inside ScrollView.

In #38276, CollectionView retains its previously rendered
height after the item count decreases, leaving unused space and stale
Height/SizeChanged values. The previous fix, #38441, moved
content-size checking exclusively to ViewDidLayoutSubviews. This
introduced the nested-scroll regression reported in #39847:
the CollectionView could remain smaller than its content, creating an
additional vertical scroll range inside the outer ScrollView. That fix
was reverted by #39856.

This replacement builds on the reverted implementation:

- Preserve the existing ViewWillLayoutSubviews content-size check.
- Add a guarded ViewDidLayoutSubviews check to detect self-sizing
content changes resolved during native layout, allowing the
CollectionView to shrink.
- Skip the post-layout check when content exceeds the current bounds in
the scrolling direction, without updating the cached content size. This
leaves growth detection to the pre-layout check and avoids the
nested-scroll regression.
- Refresh empty-source tracking when replacing ItemsSource so grouped
collections collapsed to zero can grow again, even when UIKit defers
data-source callbacks.
- Restore the required iOS and Mac Catalyst public API entries for the
layout callback override.


### 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. -->

Fixes #38276

Related: #39847 — adds coverage to prevent reintroducing the
nested-scroll regression already addressed by the revert.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->
<!-- 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!


### Root cause: 

- `StrokeLineJoin` was correctly mapped to Core Graphics, but the border
stroke was clipped to the original shape path. Round and Bevel join
geometry extends beyond convex path corners, so the active clip removed
the visible join geometry and caused corners to appear sharp.

### Description of Change

- The iOS `MauiCALayer` renderer now uses `RequiresUnclippedStroke` to
identify Round, Bevel, and custom-MiterLimit configurations. For these
cases, it renders the stroke on an inset path without the outer shape
clip, preserving the complete join geometry inside the `CALayer` bounds.
- The background is clipped to the inset path so it does not appear in
bevelled corner cutouts.
- Default Miter rendering with the default miter limit retains the
existing clipped rendering path, preserving current border dimensions
and dash placement for unaffected Border scenarios.

### Issues Fixed

Fixes #29743

### Tested the behavior in the following platforms

- [ ] Windows
- [ ] Android
- [x] iOS
- [x] Mac

| Before Issue Fix | After Issue Fix |
|----------|----------|
| <img width="1125" height="2436" alt="BeforeFix29743"
src="https://github.com/user-attachments/assets/45ada062-5d57-491c-a863-2cbbb7b7d9f4"
/> | <img width="1125" height="2436" alt="AfterFix29743"
src="https://github.com/user-attachments/assets/98ed0c28-7a5d-480e-9066-b88330bb5032"
/> |
<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…imated push (#40135)

<!-- 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.
-->

### Issue details

Issue reports that immediately popping an Android modal after a
non-animated push removes the page from `Navigation.ModalStack`, but
leaves its native `ModalFragment` dialog on screen:

```csharp
await Navigation.PushModalAsync(new ContentPage { BackgroundColor = Colors.Yellow }, animated: false);
await Navigation.PopModalAsync(animated: false);
```

Expected: the modal closes and the previous page becomes visible.
Actual: the logical modal stack is empty, but a full-screen native
dialog remains, leaving logical and native navigation out of sync. The
author reports working behavior in **10.0.20**, failure in **10.0.30**,
and continued failure in 10.0.40, 10.0.110 and 10.0.130. Animated pushes
are not affected by the reported reproduction because the animation
gives the page time to load.

The immediate push/pop sequence was reproduced in the Sandbox sample on
**Android 15/API 35**: before the fix, `Loaded at pop: False; stack: 0;
dialogs: 1`.

### Root cause

`ModalFragment.OnResume` can run before the modal page's platform view
is attached and `Loaded` has fired. Previously, it unconditionally
raised `PresentationCompleted`, allowing `PushModalAsync(animated:
false)` to return before the modal was ready for an immediate native
pop.

The subsequent `PopModalAsync` checks `IsModalReady`. When the current
platform page is not loaded, it skips `PopModalPlatformAsync` and defers
stack synchronization, but still removes the modal's logical parent and
disconnects its handler. The native modal remains in
`_platformModalPages`. Deferred synchronization then waits for that same
modal to have a handler and loaded platform view, a condition that
cannot recover after disconnection. Consequently, the native dialog is
never dismissed.

### Regression reason

The **likely introducing change** is [PR
#32479](#32479), which fixed a
related hang involving `Task.Yield()` by making non-animated pushes
await a new `PresentationCompleted` event. That event was raised
synchronously from `OnResume`, which is not sufficient proof that the
modal page is loaded. An awaiting immediate pop can therefore continue
inside this lifecycle timing window.

Release-source tracing supports this attribution:

- The Android modal-manager source in **10.0.20** exactly matches the
parent of the [shipped change
`5214279`](5214279).
- The source in **10.0.30** exactly matches both the original PR merge
and that shipped change, integrated through
[#33363](#33363).
- The shared modal-manager source is identical between those releases,
locating the relevant behavioral difference in Android presentation
timing.

This is **likely**, not confirmed introduction: no same-environment
runtime comparison of the candidate and its parent was performed. The
release histories diverge, so the version comparison was not treated as
a linear bisect.

### Fix details

In `ModalNavigationManager.Android.cs`, complete presentation only when
**both** the page is loaded and the fragment is resumed:

- Subscribe to the modal page's `Loaded` event when constructing the
fragment.
- If `Loaded` happens first, `OnResume` completes presentation only when
`IsLoaded` is true.
- If resume happens first, the `Loaded` handler completes presentation
only when `IsResumed` is true.
- Unsubscribe `Loaded` when presentation completes or the dialog is
dismissed.
- Preserve the existing early-start/destroy completion safeguards.

This strengthens the presentation-readiness guarantee without adding
delays or changing shared modal-stack cleanup. No public API changes are
introduced, and other platform implementations are unchanged.


### 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. -->

Fixes #40134

<!--
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: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…ng (#39911)

<!-- 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!

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

### Description of Change

Custom font loading can pump STA messages. Performing that work
synchronously during a XAML layout tick can cause dispatcher reentrancy
and a native WinUI fail-fast crash.

Defer font-image rendering with Task.Yield() before entering the
existing Win2D rendering pipeline. This preserves UI-thread rendering
while allowing the current layout tick to finish. Also honor
cancellation before rendering and after the yield, avoid logging
expected cancellation as a warning, and dispose CanvasTextFormat.

### 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. -->

Fixes #39888

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

<!-- 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

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

Adds executable XAML regression coverage for `{Binding A.B.C.Text}` when
intermediate references are null despite non-nullable declarations. Each
test runs with Runtime, XamlC, and SourceGen inflation.

**Investigation:** The `11.0.0` release tag still bases null-conditional
access on nullable annotations and generates `source.A.B.C.Text`.
Current `net11` already includes the fix from #36444
(`803bc81a488007ce0647ab5693cf4811b8ce4844`), which uses runtime
nullability and generates `source.A?.B?.C?.Text`. No additional
production-code change is needed on this base; this PR adds behavioral
coverage rather than duplicating that fix.

**Important testing detail:** `TypedBinding` catches getter
`NullReferenceException`s. Checking only the resulting label text or
using `Assert.Throws` misses the issue. The new test captures
thread-local first-chance exceptions during binding evaluation, with the
AppDomain event handler removed in `finally`. This detects
debugger-visible exceptions even when the binding engine catches them.
It does not claim that every exception escapes the binding engine or
crashes the app.

The other tests verify recovery when A, B, or C becomes null and is
restored, leaf-property updates, detached-leaf changes not affecting the
target value, and two-way bindings writing null to a
non-nullable-declared reference property.

**Proposed resolution:** Retain the runtime-nullability fix already
present in `net11` and ensure it is included in the applicable servicing
release. This test-only PR protects that behavior. Existing #36444
coverage inspects generated source; these tests execute the inflated
bindings.

cc @simonrozsival - the fix from #36444 is present on `net11` but absent
from the `11.0.0` tag. The new executable test reproduces the
SourceGen-only first-chance exceptions with the shipped generator and
passes with the existing fix.

#### Validation

The A/B check replaced only `CompiledBindingMarkup.cs` with its contents
at `4b41c78edb15307a84caf5b4bfe89a6df0813dcb`, which are byte-identical
to that file in the `11.0.0` tag. All other code remained at current
`net11`; this is not a full released-package/device run.

| Generator implementation | Runtime | XamlC | SourceGen |
| --- | --- | --- | --- |
| Shipped `11.0.0` generator file | 3 passed | 3 passed | 2 passed,
first-chance exception test failed |
| Current `net11` / existing #36444 fix | 3 passed | 3 passed | 3 passed
|

Exact commands and results:

```powershell
$PSDefaultParameterValues["EstablishBrokenBaseline.ps1:BaseBranch"] = "4b41c78edb15307a84caf5b4bfe89a6df0813dcb"
& .github/skills/verify-tests-fail-without-fix/scripts/verify-tests-fail.ps1 -PRNumber 40139 -TestType XamlUnitTest -TestFilter "FullyQualifiedName~Maui40139" -FixFiles src/Controls/src/SourceGen/CompiledBindingMarkup.cs -BaseBranch 4b41c78 -RequireFullVerification
```

Result: **VERIFICATION PASSED** - 1 failed / 8 passed with the shipped
generator file; 9 passed with the current generator. `40139` is the
report-directory identifier for the issue investigation. The PowerShell
default also pins the shared baseline helper, which otherwise loses the
explicit base during dot-sourcing.

```shell
dotnet build Microsoft.Maui.BuildTasks.slnf -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -v q
```

Result: passed.

```shell
dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj -c Debug -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false --filter 'FullyQualifiedName~Maui40139' -v q
```

Result: passed, 9 tests. Executed locally on macOS using the installed
.NET 11 RC2 SDK; no native Android/iOS device validation was performed.

### 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. -->

Relates to #40139; adds regression coverage for the existing fix to
#36313. This PR does not introduce a new production fix or establish
that a serviced package has shipped.

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

---------
…40150)

### 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

On iOS and Mac Catalyst, `HtmlWebViewSource.BaseUrl` is not used as a
URL. `MauiWKWebView.LoadHtml` passes every value to `new NSUrl(baseUrl,
true)`, which is `initFileURLWithPath:isDirectory:`. A URL such as
`https://example.com/` is treated as a relative file path and becomes a
`file:` URL under the current directory. The loaded document therefore
never gets the origin the app asked for, so these break:

- relative URLs that should resolve against a remote base
- cookies and storage scoped to that origin
- services that identify the embedding app by its `Referer`. For
example, YouTube's embedded player requires one ([Required Minimum
Functionality](https://developers.google.com/youtube/terms/required-minimum-functionality)).
Google's documented way to provide it on iOS is
`loadHTMLString:baseURL:` with an https base URL, which is what
`HtmlWebViewSource.BaseUrl` maps to. With this bug the player shows
"Error 153".

Android already passes `BaseUrl` to `LoadDataWithBaseURL` as a URL, so
this makes iOS and Mac Catalyst behave like Android.

**Change:** `LoadHtml` resolves the base URL in a new `ResolveBaseUrl`:

| `BaseUrl` | Before | After |
| --- | --- | --- |
| `https://example.com/` | `file:///…/https:/example.com/` (a file URL
under the current directory) | `https://example.com/` |
| a file system path, e.g. `NSBundle.MainBundle.BundlePath` | directory
file URL | unchanged |
| `null` / empty | app bundle path | unchanged |

A value counts as a URL when `NSUrl.FromString` parses it with a scheme.
Anything else keeps the existing file-path behaviour, so apps that pass
a bundle path for local content are not affected.

No open PR addresses this issue.

### Tests

Device tests in `WebViewHandlerTests.iOS.cs` (it also compiles for Mac
Catalyst). Each loads HTML with a `BaseUrl` and reads `document.baseURI`
from the page:

- `HtmlSourceBaseUrlWithSchemeIsDocumentBaseUrl` for
`https://example.com/` and `https://example.com/content/`
- `HtmlSourceBaseUrlFilePathStaysFileUrl`, which pins the existing
file-path behaviour
- `HtmlWebViewSourceStub` gains a `BaseUrl` property for these tests

Run locally with xharness, `Category=WebView`, on this branch's base
`net11` (e7f7353):

| Run | Result |
| --- | --- |
| iOS simulator 26.5, without the fix | both scheme cases fail:
`Expected "https://example.com/"`, `Actual
"file:///Users/…/Library/Develop…"`. The file-path case passes. |
| iOS simulator 26.5, with the fix | 79 passed, 0 failed, 2 skipped |
| Mac Catalyst, with the fix | 74 passed, 0 failed, 7 skipped |

### Issues Fixed

Fixes #19792

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…ation (#40148)

<!-- 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!


### Issue

After upgrading from .NET MAUI 10 to 11, XAML source generation fails
when a `DynamicResource` key is supplied through a nested markup
extension:

```xml
<Label FontSize="{DynamicResource {x:Static local:FontSizes.Medium}}" />
```

Here, `FontSizes.Medium` is a public string constant containing a
resource dictionary key. Instead of resolving that key, compilation
reports:

```text
MAUIG1001: Unable to cast object of type
'Microsoft.Maui.Controls.Xaml.ElementNode' to type
'Microsoft.Maui.Controls.Xaml.ValueNode'.
```

The exact error was reproduced in the MacCatalyst Sandbox build before
applying this fix.

### Root cause

`KnownMarkups.ProvideValueForDynamicResourceExtension` optimizes
resource creation during the source generator's early value-creation
pass. It assumes the key node is a `ValueNode` containing a literal
string and casts it directly.

Nested markup extensions such as `x:Static` are represented by
`ElementNode` instances, so this assumption causes an invalid cast
before the nested extension can be evaluated.

### Fix

Restrict the early optimization to literal string keys. When the key is
not a literal string, decline the optimization and let the existing
markup-extension pipeline evaluate the nested value, assign
`DynamicResourceExtension.Key`, and invoke `ProvideValue` normally.

This preserves the existing literal-key fast path without adding
special-case handling for `x:Static` or changing the public API.

### Regression coverage

Add 10 parameterized cases covering literal keys and nested `x:Static`
keys backed by constants, static readonly fields, and static properties,
plus nested `x:String` values. Both positional and explicit `Key=` forms
are covered.

Each case compiles and executes the generated page, verifies the initial
font size, and confirms that replacing the resource updates the label's
font size. Before the fix, nine cases failed and the positional
literal-key control passed; afterward, all 10 pass.


### 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. -->

Fixes #40145

<!--
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: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
### Description of Change

With the .NET 11 implicit XAML namespaces feature, `{x:Static
Routes.LineItemsPage}` fails with `MAUIG1001: Type not found Routes`
when `Routes` is produced by another source generator (e.g.
epj.RouteGenerator in the repro project), while the same reference works
with an explicit `xmlns` prefix. Roslyn source generators cannot see
each other's output, so the XAML source generator has no symbol for such
types. For explicit `clr-namespace:` prefixes it already defers to the
C# compiler by emitting `global::{ns}.{Type}.{member}` as a guess (which
is why the prefix workaround works), but for the implicit/global xmlns —
where a set of candidate namespaces is registered rather than a single
one — no such fallback existed, and the generator reported a hard error.
Types that are part of the compilation already resolve correctly through
the implicit xmlns in all inflators, and XamlC/runtime inflation are
unaffected since they run against the compiled assembly.

**Fix**

When `x:Static` can't resolve its type symbol and the xmlns is an
aggregated one (such as the implicit
`http://schemas.microsoft.com/dotnet/maui/global`), resolution is
deferred to the C# compiler, exactly like the existing `clr-namespace:`
fallback. The deferral candidates are deliberately narrow: only CLR
namespaces (aggregated xmlns can also map to other xmlns URIs, which are
filtered out) that the **current assembly** registered on that xmlns —
metadata references are immutable, so a type the generator cannot see
can only materialize in the compilation's own assembly, as another
generator's output. In practice that leaves:

- one candidate (the common case): the member access is emitted fully
qualified, `global::Test.Routing.Routes.LineItemsPage` — no usings, no
name-collision surface;
- several candidates (the app registered 2+ of its own namespaces on one
xmlns): the member access is emitted unqualified and the candidates
become `using` directives in the generated file, so the compiler
resolves the name or reports CS0104 on a genuine ambiguity;
- no valid candidate: the existing `MAUIG1001` error is reported, as
before.

The usings travel as marker lines inside the generated body and are
lifted into `using` directives by the final code writers, so they reach
both `InitializeComponent` and the Hot Reload `UpdateComponent` output
(which previously discarded them and produced an uncompilable update for
this scenario).

**Tests**

`Issues/Maui39763.cs` reproduces the scenario with the source generator
driver: the x:Static type is absent from the compilation the generator
sees (like another generator's output) but registered in the global
xmlns, and the tests verify the generated code compiles once the type
exists in the final compilation.

| | Without fix | With fix |
| --- | --- | --- |
| `XStaticWithGeneratedTypeInImplicitXmlns` | Fails: `error MAUIG1001: …
Type not found Routes.` | Passes; asserts the exact
`global::Test.Routing.Routes.LineItemsPage` output |
| `XStaticWithGeneratedTypeInAggregatedXmlns` (urn: aggregation) |
Fails: emitted `using urn:test39763;` | Passes |
| `XStaticWithGeneratedTypeInImplicitXmlnsMultipleNamespaces` | — |
Passes; pins the multi-candidate usings path |
| `XStaticWithResolvableTypeInImplicitXmlns` (control) | Passes | Passes
|
| `Maui39763Tests.XStaticFallbackUsings_ReachUpdateComponent` (Hot
Reload) | Fails: no `using` in `UpdateComponentSource` | Passes; all
generated sources compile |
| Full Xaml.UnitTests | 2 pre-existing locale failures | Same 2, zero
new (2183 passed) |
| Full SourceGen.UnitTests | — | 629 passed / 0 failed |

Known residual, intrinsic to CSC deferral: in the multi-candidate case a
field (`x:Name`) or a type in the page's namespace with the same name as
the deferred type can still shadow it — the single-candidate path, which
covers the issue's scenario, is immune.

### Issues Fixed

Fixes #39763

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…request (#40124)

### Description of Change

On Android, pressing the system back button while an animated
`NavigationPage.PushAsync` is still running pops the page natively
without MAUI being notified: during an in-flight fragment transaction
the back press is consumed by an AndroidX callback registered later than
MAUI's (`OnBackPressedDispatcher` invokes the most recently added
enabled callback). After that:

- the `Task` returned by `PushAsync` never completes —
`StackNavigationManager` finishes a navigation when the outgoing
fragment's view is destroyed, and a cancelled transition never destroys
it,
- `NavigationStack`/`CurrentPage` still contain the pushed page while
the screen shows the previous one, and the next back press is delivered
to the invisible page,
- anything awaiting that `PushAsync` hangs, so the app looks frozen.

**Fix**

`StackNavigationManager` now reconciles when the platform back stack
pops without a MAUI request. On every `OnDestinationChanged` that was
not produced by `ApplyNavigationRequest` itself (guarded by a flag
around the request processing), it compares the platform back-stack
depth with the cross-platform stack; when the platform has fewer
entries, it trims the stack to what is actually on screen and completes
the pending navigation through the existing `NavigationFinished` path —
the same reconciliation `IStackNavigation.NavigationFinished` already
performs on the Controls side (stack sync, `CurrentPage`, toolbar, task
completion).

This is the outcome the issue asks for: the interrupted push is treated
as cancelled, the `PushAsync` task completes, and the cross-platform
stack matches what is displayed.

**Tests**


`NavigationPageTests.PushCompletesWhenThePlatformPopsDuringTheTransition`
(Android device test): starts an animated push and immediately pops the
platform back stack — what the stolen back press does — then checks the
push task completes, the stack has a single page and `CurrentPage` is
the root again.

| | Without fix | With fix |
|---|---|---|
| Android emulator (API 37) | Fails: `PushAsync never completed after
the platform popped the page` | Passes. NavigationPage category 25
passed / 1 failed / 1 skipped — the one failure (`BarBackgroundColor
respects Android system chrome opt-out`) fails identically on unmodified
`main` on the same emulator |

### Issues Fixed

Fixes #39456

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@kubaflo
kubaflo merged commit f641216 into candidate/11.0.1xx-sr2 Nov 17, 2026
2 of 12 checks passed
@kubaflo
kubaflo deleted the stephanedelcroix-xihr-throwaway-compilation-signal branch November 17, 2026 19:24
@kubaflo kubaflo mentioned this pull request Nov 17, 2026
1 task
kubaflo added a commit that referenced this pull request Nov 18, 2026
… different C# (#40330)

<!-- 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).

**Base note:** this is a follow-up to #40233, which was merged into
`candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This
change modifies code that only exists there, so the PR targets
`candidate/11.0.1xx-sr2`.

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 #40233, closing the gap it documented: if a **throwaway
compilation with different user C#** (speculative or design-time
snapshot) evaluates the edited XAML before the real compilation does,
the pending `UpdateComponent()` patch is lost. The generator couldn't
tell this apart from a genuine C#-only edit, which had to emit an
*empty* `UpdateComponent()` because the runtime classified a delta as a
XAML change by the emptiness of that body.

**Fix: move the classification to a companion signal type, as
@noiseonwires proposed on #36937.** The `MetadataUpdateHandler` is in
this repo, so no Roslyn or hot reload agent changes are needed.

- **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now
also nests a private `__XamlHotReloadSignal` type in each XIHR root,
with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's
no patch). It's emitted on every generation, like `UpdateComponent()`,
so there's no member churn. Its content only changes when the patch
changes, so Roslyn lists it in a delta exactly when there's a new patch
to apply.
- **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML
is unchanged and a patch is pending, the patch is always re-derived from
its baseline, whatever the C# sources are. The output becomes a function
of the inputs, not of evaluation order or of which compilation ran
first. The `UserSourcesFingerprint` gate from #40233 (and the extra
compilation input to the pipeline) is removed.
- **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the
companion type counts as a XAML change only if the delta lists the
companion **and** `UpdateComponent()` isn't empty. This keeps structural
changes, which reset the body to empty, out, as before. A companion
listed without its root is mapped back to the root. Roots without a
companion (older generated code) keep the existing empty-body check.
`UpdateRequested.HandledTypes` and the
`UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged.

With this, a C#-only edit re-emits the same patch. `UpdateComponent()`
and the companion are byte-identical, so they aren't in the delta and
the patch isn't re-applied. This matters because patches aren't always
idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML
edit whose delta was rejected (e.g. it was combined with a C# rude edit)
still carries its patch on the next generation instead of an empty body.

**Remaining limitation (not addressed here):** a throwaway run with
*different XAML* (e.g. an intermediate keystroke) still advances the
cached "previous" XAML. The next real patch is then diffed from that
intermediate state rather than from what the app last applied. Fixing
that would need knowledge of the last applied generation.

**Tests**
- `XamlIncrementalHotReloadPipelineTests`
- `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is
the gap from #40233. It fails without the fix.
- `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces
`CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose
expectation is intentionally changed.
  - `SignalFingerprint_ChangesWithThePatchOnly`.
- `XamlIncrementalHotReloadE2ETests` (real
`MetadataUpdater.ApplyUpdate`)
- `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live
label changed at runtime isn't overwritten by a C#-only delta.
- `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates
the existing classification test.
- The test harness now lists the companion type among the delta's
updated types only when its fingerprint changed, like Roslyn does.
- `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two
handler tests cover a root with a companion type and a companion listed
alone.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**855 passed, 0 failed, 0 skipped**.
- With only the generator/state change reverted, 3 new tests fail,
including the throwaway test. With only the handler change reverted, the
2 E2E runtime tests fail.
- `dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`:
**2250 passed, 2 failed, 8 skipped**. The 2 failures
(`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass
with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **12 passed**.
- `dotnet format whitespace --verify-no-changes` on the changed files:
clean.

### Issues Fixed

Fixes #36937

Follow-up to #40233.

---------
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
github-actions Bot pushed a commit that referenced this pull request Nov 18, 2026
…ted one

A throwaway generator run with different XAML advanced the cached previous
XAML, so the next real UpdateComponent was diffed from a generation that never
reached the app.

InitializeComponent now records each instance's generation key in
XamlComponentRegistry. UpdateComponent branches on that key: instances at a
retained generation (up to 4) get the patch diffed from that generation, others
get the default patch, and every patched instance records the new key, so
re-running the patch is a no-op.

Follow-up to #40330 for #36937.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Nov 18, 2026
…ns (#40378)

<!-- 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).

> [!IMPORTANT]
> **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on
#40233, #40235, #40329 and #40330, which exist only on
`candidate/11.0.1xx-sr2` (not on `net11`, `main` or
`inflight/11.0.1xx-sr3`). Against `net11` the diff would include about
527 unrelated files. As with #40329 and #40330, it targets
`candidate/11.0.1xx-sr2` directly so it ships together with its
prerequisites.

### Description of Change

#40330 left one limitation. A throwaway generator run with different
XAML, such as a design-time or speculative run whose output never
reaches the app, advanced the cached previous XAML. The next real
`UpdateComponent()` was then diffed from that intermediate generation
instead of the generation the running app actually has. The result was
missed edits: for example, an edit already present in the throwaway XAML
was never applied.

The generator cannot tell which of its runs reached the app, so this PR
has `UpdateComponent()` decide at runtime:

- **Generation key.** Each successful generation gets a key: a SHA-256
of the normalized XAML plus the node IDs
(`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the
current generation and the previously generated ones as baselines, up to
`MaxBaselines = 4`.
- **InitializeComponent** records `XamlComponentRegistry.Register(this,
"__xihr_generation:<type>", key)`.
- **UpdateComponent** reads the instance's recorded key:
- A retained generation whose diff produces exactly the current node IDs
gets its own branch: the patch diffed from that generation.
- Anything else gets the default patch, diffed from the last generated
XAML. This matches the previous behavior.
- Every patched instance then records the new key, so running the patch
again, or for a C#-only edit, changes nothing.
- When there is nothing to patch, the output is unchanged: an empty UC,
with no marker. Rude-edit rollback behavior is preserved, and the older
applied generation now also gets its own branch.

**Known edge, not a regression:** a retained generation whose diff would
assign different IDs from the current ones (e.g. some reverts) is not
given a branch. Instances at that generation fall back to the default
patch, which is the old behavior.

### Issues Fixed

Fixes #36937 (remaining limitation from #40330)

### Tests

-
`XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`:
real metadata update. Applied `Text="Hello"`, then a throwaway run with
`Text="World" FontSize="30"`, then the real edit to `Text="World"`. The
live label ends at `World` with its default `FontSize`, re-running UC is
a no-op, and new instances are already current. A new harness hook,
`GenerateWithThrowawayRuns`, runs and discards a forked driver run.
-
`XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`:
checks the branch structure and determinism (same snapshot and C#-only
edits give an identical UC).
- `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded`
- Existing rude-edit assertions now target the default patch
(`UpdateComponentText.DefaultPatch`), because the UC legitimately
contains a branch for the older applied generation.

### Validation

- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**passed**, 899/899.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **passed**, 12/12.
- `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274
passed, 12 failed. All 12 failures are `CultureNotFoundException` from
culture-specific tests under invariant-globalization mode; none involve
hot reload.
- `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes
--include <changed files>`: **passed**.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Nov 18, 2026
… different C# (#40330)

<!-- 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).

**Base note:** this is a follow-up to #40233, which was merged into
`candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This
change modifies code that only exists there, so the PR targets
`candidate/11.0.1xx-sr2`.

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 #40233, closing the gap it documented: if a **throwaway
compilation with different user C#** (speculative or design-time
snapshot) evaluates the edited XAML before the real compilation does,
the pending `UpdateComponent()` patch is lost. The generator couldn't
tell this apart from a genuine C#-only edit, which had to emit an
*empty* `UpdateComponent()` because the runtime classified a delta as a
XAML change by the emptiness of that body.

**Fix: move the classification to a companion signal type, as
@noiseonwires proposed on #36937.** The `MetadataUpdateHandler` is in
this repo, so no Roslyn or hot reload agent changes are needed.

- **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now
also nests a private `__XamlHotReloadSignal` type in each XIHR root,
with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's
no patch). It's emitted on every generation, like `UpdateComponent()`,
so there's no member churn. Its content only changes when the patch
changes, so Roslyn lists it in a delta exactly when there's a new patch
to apply.
- **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML
is unchanged and a patch is pending, the patch is always re-derived from
its baseline, whatever the C# sources are. The output becomes a function
of the inputs, not of evaluation order or of which compilation ran
first. The `UserSourcesFingerprint` gate from #40233 (and the extra
compilation input to the pipeline) is removed.
- **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the
companion type counts as a XAML change only if the delta lists the
companion **and** `UpdateComponent()` isn't empty. This keeps structural
changes, which reset the body to empty, out, as before. A companion
listed without its root is mapped back to the root. Roots without a
companion (older generated code) keep the existing empty-body check.
`UpdateRequested.HandledTypes` and the
`UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged.

With this, a C#-only edit re-emits the same patch. `UpdateComponent()`
and the companion are byte-identical, so they aren't in the delta and
the patch isn't re-applied. This matters because patches aren't always
idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML
edit whose delta was rejected (e.g. it was combined with a C# rude edit)
still carries its patch on the next generation instead of an empty body.

**Remaining limitation (not addressed here):** a throwaway run with
*different XAML* (e.g. an intermediate keystroke) still advances the
cached "previous" XAML. The next real patch is then diffed from that
intermediate state rather than from what the app last applied. Fixing
that would need knowledge of the last applied generation.

**Tests**
- `XamlIncrementalHotReloadPipelineTests`
- `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is
the gap from #40233. It fails without the fix.
- `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces
`CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose
expectation is intentionally changed.
  - `SignalFingerprint_ChangesWithThePatchOnly`.
- `XamlIncrementalHotReloadE2ETests` (real
`MetadataUpdater.ApplyUpdate`)
- `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live
label changed at runtime isn't overwritten by a C#-only delta.
- `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates
the existing classification test.
- The test harness now lists the companion type among the delta's
updated types only when its fingerprint changed, like Roslyn does.
- `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two
handler tests cover a root with a companion type and a companion listed
alone.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**855 passed, 0 failed, 0 skipped**.
- With only the generator/state change reverted, 3 new tests fail,
including the throwaway test. With only the handler change reverted, the
2 E2E runtime tests fail.
- `dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`:
**2250 passed, 2 failed, 8 skipped**. The 2 failures
(`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass
with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **12 passed**.
- `dotnet format whitespace --verify-no-changes` on the changed files:
clean.

### Issues Fixed

Fixes #36937

Follow-up to #40233.

---------
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Nov 18, 2026
…ns (#40378)

<!-- 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).

> [!IMPORTANT]
> **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on
#40233, #40235, #40329 and #40330, which exist only on
`candidate/11.0.1xx-sr2` (not on `net11`, `main` or
`inflight/11.0.1xx-sr3`). Against `net11` the diff would include about
527 unrelated files. As with #40329 and #40330, it targets
`candidate/11.0.1xx-sr2` directly so it ships together with its
prerequisites.

### Description of Change

#40330 left one limitation. A throwaway generator run with different
XAML, such as a design-time or speculative run whose output never
reaches the app, advanced the cached previous XAML. The next real
`UpdateComponent()` was then diffed from that intermediate generation
instead of the generation the running app actually has. The result was
missed edits: for example, an edit already present in the throwaway XAML
was never applied.

The generator cannot tell which of its runs reached the app, so this PR
has `UpdateComponent()` decide at runtime:

- **Generation key.** Each successful generation gets a key: a SHA-256
of the normalized XAML plus the node IDs
(`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the
current generation and the previously generated ones as baselines, up to
`MaxBaselines = 4`.
- **InitializeComponent** records `XamlComponentRegistry.Register(this,
"__xihr_generation:<type>", key)`.
- **UpdateComponent** reads the instance's recorded key:
- A retained generation whose diff produces exactly the current node IDs
gets its own branch: the patch diffed from that generation.
- Anything else gets the default patch, diffed from the last generated
XAML. This matches the previous behavior.
- Every patched instance then records the new key, so running the patch
again, or for a C#-only edit, changes nothing.
- When there is nothing to patch, the output is unchanged: an empty UC,
with no marker. Rude-edit rollback behavior is preserved, and the older
applied generation now also gets its own branch.

**Known edge, not a regression:** a retained generation whose diff would
assign different IDs from the current ones (e.g. some reverts) is not
given a branch. Instances at that generation fall back to the default
patch, which is the old behavior.

### Issues Fixed

Fixes #36937 (remaining limitation from #40330)

### Tests

-
`XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`:
real metadata update. Applied `Text="Hello"`, then a throwaway run with
`Text="World" FontSize="30"`, then the real edit to `Text="World"`. The
live label ends at `World` with its default `FontSize`, re-running UC is
a no-op, and new instances are already current. A new harness hook,
`GenerateWithThrowawayRuns`, runs and discards a forked driver run.
-
`XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`:
checks the branch structure and determinism (same snapshot and C#-only
edits give an identical UC).
- `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded`
- Existing rude-edit assertions now target the default patch
(`UpdateComponentText.DefaultPatch`), because the UC legitimately
contains a branch for the older applied generation.

### Validation

- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**passed**, 899/899.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **passed**, 12/12.
- `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274
passed, 12 failed. All 12 failures are `CultureNotFoundException` from
culture-specific tests under invariant-globalization mode; none involve
hot reload.
- `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes
--include <changed files>`: **passed**.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Nov 18, 2026
… different C# (#40330)

<!-- 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).

**Base note:** this is a follow-up to #40233, which was merged into
`candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This
change modifies code that only exists there, so the PR targets
`candidate/11.0.1xx-sr2`.

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 #40233, closing the gap it documented: if a **throwaway
compilation with different user C#** (speculative or design-time
snapshot) evaluates the edited XAML before the real compilation does,
the pending `UpdateComponent()` patch is lost. The generator couldn't
tell this apart from a genuine C#-only edit, which had to emit an
*empty* `UpdateComponent()` because the runtime classified a delta as a
XAML change by the emptiness of that body.

**Fix: move the classification to a companion signal type, as
@noiseonwires proposed on #36937.** The `MetadataUpdateHandler` is in
this repo, so no Roslyn or hot reload agent changes are needed.

- **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now
also nests a private `__XamlHotReloadSignal` type in each XIHR root,
with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's
no patch). It's emitted on every generation, like `UpdateComponent()`,
so there's no member churn. Its content only changes when the patch
changes, so Roslyn lists it in a delta exactly when there's a new patch
to apply.
- **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML
is unchanged and a patch is pending, the patch is always re-derived from
its baseline, whatever the C# sources are. The output becomes a function
of the inputs, not of evaluation order or of which compilation ran
first. The `UserSourcesFingerprint` gate from #40233 (and the extra
compilation input to the pipeline) is removed.
- **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the
companion type counts as a XAML change only if the delta lists the
companion **and** `UpdateComponent()` isn't empty. This keeps structural
changes, which reset the body to empty, out, as before. A companion
listed without its root is mapped back to the root. Roots without a
companion (older generated code) keep the existing empty-body check.
`UpdateRequested.HandledTypes` and the
`UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged.

With this, a C#-only edit re-emits the same patch. `UpdateComponent()`
and the companion are byte-identical, so they aren't in the delta and
the patch isn't re-applied. This matters because patches aren't always
idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML
edit whose delta was rejected (e.g. it was combined with a C# rude edit)
still carries its patch on the next generation instead of an empty body.

**Remaining limitation (not addressed here):** a throwaway run with
*different XAML* (e.g. an intermediate keystroke) still advances the
cached "previous" XAML. The next real patch is then diffed from that
intermediate state rather than from what the app last applied. Fixing
that would need knowledge of the last applied generation.

**Tests**
- `XamlIncrementalHotReloadPipelineTests`
- `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is
the gap from #40233. It fails without the fix.
- `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces
`CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose
expectation is intentionally changed.
  - `SignalFingerprint_ChangesWithThePatchOnly`.
- `XamlIncrementalHotReloadE2ETests` (real
`MetadataUpdater.ApplyUpdate`)
- `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live
label changed at runtime isn't overwritten by a C#-only delta.
- `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates
the existing classification test.
- The test harness now lists the companion type among the delta's
updated types only when its fingerprint changed, like Roslyn does.
- `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two
handler tests cover a root with a companion type and a companion listed
alone.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**855 passed, 0 failed, 0 skipped**.
- With only the generator/state change reverted, 3 new tests fail,
including the throwaway test. With only the handler change reverted, the
2 E2E runtime tests fail.
- `dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`:
**2250 passed, 2 failed, 8 skipped**. The 2 failures
(`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass
with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **12 passed**.
- `dotnet format whitespace --verify-no-changes` on the changed files:
clean.

### Issues Fixed

Fixes #36937

Follow-up to #40233.

---------
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Nov 18, 2026
…ns (#40378)

<!-- 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).

> [!IMPORTANT]
> **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on
#40233, #40235, #40329 and #40330, which exist only on
`candidate/11.0.1xx-sr2` (not on `net11`, `main` or
`inflight/11.0.1xx-sr3`). Against `net11` the diff would include about
527 unrelated files. As with #40329 and #40330, it targets
`candidate/11.0.1xx-sr2` directly so it ships together with its
prerequisites.

### Description of Change

#40330 left one limitation. A throwaway generator run with different
XAML, such as a design-time or speculative run whose output never
reaches the app, advanced the cached previous XAML. The next real
`UpdateComponent()` was then diffed from that intermediate generation
instead of the generation the running app actually has. The result was
missed edits: for example, an edit already present in the throwaway XAML
was never applied.

The generator cannot tell which of its runs reached the app, so this PR
has `UpdateComponent()` decide at runtime:

- **Generation key.** Each successful generation gets a key: a SHA-256
of the normalized XAML plus the node IDs
(`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the
current generation and the previously generated ones as baselines, up to
`MaxBaselines = 4`.
- **InitializeComponent** records `XamlComponentRegistry.Register(this,
"__xihr_generation:<type>", key)`.
- **UpdateComponent** reads the instance's recorded key:
- A retained generation whose diff produces exactly the current node IDs
gets its own branch: the patch diffed from that generation.
- Anything else gets the default patch, diffed from the last generated
XAML. This matches the previous behavior.
- Every patched instance then records the new key, so running the patch
again, or for a C#-only edit, changes nothing.
- When there is nothing to patch, the output is unchanged: an empty UC,
with no marker. Rude-edit rollback behavior is preserved, and the older
applied generation now also gets its own branch.

**Known edge, not a regression:** a retained generation whose diff would
assign different IDs from the current ones (e.g. some reverts) is not
given a branch. Instances at that generation fall back to the default
patch, which is the old behavior.

### Issues Fixed

Fixes #36937 (remaining limitation from #40330)

### Tests

-
`XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`:
real metadata update. Applied `Text="Hello"`, then a throwaway run with
`Text="World" FontSize="30"`, then the real edit to `Text="World"`. The
live label ends at `World` with its default `FontSize`, re-running UC is
a no-op, and new instances are already current. A new harness hook,
`GenerateWithThrowawayRuns`, runs and discards a forked driver run.
-
`XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`:
checks the branch structure and determinism (same snapshot and C#-only
edits give an identical UC).
- `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded`
- Existing rude-edit assertions now target the default patch
(`UpdateComponentText.DefaultPatch`), because the UC legitimately
contains a branch for the older applied generation.

### Validation

- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**passed**, 899/899.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **passed**, 12/12.
- `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274
passed, 12 failed. All 12 failures are `CultureNotFoundException` from
culture-specific tests under invariant-globalization mode; none involve
hot reload.
- `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes
--include <changed files>`: **passed**.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Nov 19, 2026
…40413) (#40417)

<!-- 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).

**Base is `candidate/11.0.1xx-sr2`, not `net11`.** The PR is test-only
and covers behavior that exists only on the candidate branch, from the
#36937 fix chain #40233, #40235, #40329, #40330, and #40378. Against
`net11` the test fails, because that fix has not flowed there yet. This
follows the precedent of #40329, #40330, and #40378, which targeted this
branch for the same reason. Maintainers: retarget if you prefer a
different lane.

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

#40413 reports that in VS on Windows (.NET 11, SourceGen inflator, XAML
Incremental Hot Reload on by default in Debug), editing a Label's `Text`
in the default template's `MainPage.xaml` is not applied.

**Root cause.** This is #36937. Roslyn/VS evaluate the same edited
generator-driver snapshot more than once, for example forked or
speculative runs, or a throwaway compilation before the applied one. On
`net11`, the first evaluation advances the cached previous XAML. The
evaluation that is actually applied then sees no diff and emits an empty
`UpdateComponent`, and the runtime silently skips it. The bug became
visible in .NET 11 because XIHR is now the default; 10.0.120 used legacy
XAML Hot Reload.

I reproduced this with the issue's own template `MainPage.xaml` through
the source generator:

| Sequence | `net11` (a25e629) | `candidate/11.0.1xx-sr2`
(cec6650) |
| --- | --- | --- |
| Edit evaluated once | patch | patch |
| Same edited snapshot evaluated twice: 2nd run | **empty UC** | patch |
| Throwaway compilation first, then real run: real run | **empty UC** |
patch |

On the candidate branch the existing fixes already handle this. This PR
adds
`DefaultTemplateMainPageTextEdit_SurvivesRepeatedAndThrowawayEvaluations`,
a theory with repeated and throwaway-first cases. It uses the template
page shape (`StaticResource` styles from a sibling `Styles.xaml`,
`x:Name`, a `Clicked` handler in code-behind) to lock in the reported
scenario. There are no product changes.

**Android .NET 10 (validation comment).** This is a separate scenario.
XIHR was not the default in .NET 10, so that report involves the legacy
XAML Hot Reload path and is not caused by this regression. It is not
addressed here.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj
--filter
"FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~CodeBehindFieldStabilityTests"`:
**passed**, 93/93, on this branch.
- `net11`: the same two sequences, run through an equivalent temporary
probe with the template XAML, produce an empty UC, as shown in the
table. I did not port the committed test itself to `net11`: its helpers
exist only on candidate, and reverting the fix commits in place
conflicts.
- Not verified in Visual Studio on Windows or on device; I worked on a
macOS host.

### Issues Fixed

Fixes #40413

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Nov 19, 2026
… different C# (#40330)

<!-- 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).

**Base note:** this is a follow-up to #40233, which was merged into
`candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This
change modifies code that only exists there, so the PR targets
`candidate/11.0.1xx-sr2`.

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 #40233, closing the gap it documented: if a **throwaway
compilation with different user C#** (speculative or design-time
snapshot) evaluates the edited XAML before the real compilation does,
the pending `UpdateComponent()` patch is lost. The generator couldn't
tell this apart from a genuine C#-only edit, which had to emit an
*empty* `UpdateComponent()` because the runtime classified a delta as a
XAML change by the emptiness of that body.

**Fix: move the classification to a companion signal type, as
@noiseonwires proposed on #36937.** The `MetadataUpdateHandler` is in
this repo, so no Roslyn or hot reload agent changes are needed.

- **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now
also nests a private `__XamlHotReloadSignal` type in each XIHR root,
with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's
no patch). It's emitted on every generation, like `UpdateComponent()`,
so there's no member churn. Its content only changes when the patch
changes, so Roslyn lists it in a delta exactly when there's a new patch
to apply.
- **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML
is unchanged and a patch is pending, the patch is always re-derived from
its baseline, whatever the C# sources are. The output becomes a function
of the inputs, not of evaluation order or of which compilation ran
first. The `UserSourcesFingerprint` gate from #40233 (and the extra
compilation input to the pipeline) is removed.
- **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the
companion type counts as a XAML change only if the delta lists the
companion **and** `UpdateComponent()` isn't empty. This keeps structural
changes, which reset the body to empty, out, as before. A companion
listed without its root is mapped back to the root. Roots without a
companion (older generated code) keep the existing empty-body check.
`UpdateRequested.HandledTypes` and the
`UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged.

With this, a C#-only edit re-emits the same patch. `UpdateComponent()`
and the companion are byte-identical, so they aren't in the delta and
the patch isn't re-applied. This matters because patches aren't always
idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML
edit whose delta was rejected (e.g. it was combined with a C# rude edit)
still carries its patch on the next generation instead of an empty body.

**Remaining limitation (not addressed here):** a throwaway run with
*different XAML* (e.g. an intermediate keystroke) still advances the
cached "previous" XAML. The next real patch is then diffed from that
intermediate state rather than from what the app last applied. Fixing
that would need knowledge of the last applied generation.

**Tests**
- `XamlIncrementalHotReloadPipelineTests`
- `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is
the gap from #40233. It fails without the fix.
- `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces
`CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose
expectation is intentionally changed.
  - `SignalFingerprint_ChangesWithThePatchOnly`.
- `XamlIncrementalHotReloadE2ETests` (real
`MetadataUpdater.ApplyUpdate`)
- `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live
label changed at runtime isn't overwritten by a C#-only delta.
- `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates
the existing classification test.
- The test harness now lists the companion type among the delta's
updated types only when its fingerprint changed, like Roslyn does.
- `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two
handler tests cover a root with a companion type and a companion listed
alone.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**855 passed, 0 failed, 0 skipped**.
- With only the generator/state change reverted, 3 new tests fail,
including the throwaway test. With only the handler change reverted, the
2 E2E runtime tests fail.
- `dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`:
**2250 passed, 2 failed, 8 skipped**. The 2 failures
(`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass
with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **12 passed**.
- `dotnet format whitespace --verify-no-changes` on the changed files:
clean.

### Issues Fixed

Fixes #36937

Follow-up to #40233.

---------
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Nov 19, 2026
…ns (#40378)

<!-- 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).

> [!IMPORTANT]
> **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on
#40233, #40235, #40329 and #40330, which exist only on
`candidate/11.0.1xx-sr2` (not on `net11`, `main` or
`inflight/11.0.1xx-sr3`). Against `net11` the diff would include about
527 unrelated files. As with #40329 and #40330, it targets
`candidate/11.0.1xx-sr2` directly so it ships together with its
prerequisites.

### Description of Change

#40330 left one limitation. A throwaway generator run with different
XAML, such as a design-time or speculative run whose output never
reaches the app, advanced the cached previous XAML. The next real
`UpdateComponent()` was then diffed from that intermediate generation
instead of the generation the running app actually has. The result was
missed edits: for example, an edit already present in the throwaway XAML
was never applied.

The generator cannot tell which of its runs reached the app, so this PR
has `UpdateComponent()` decide at runtime:

- **Generation key.** Each successful generation gets a key: a SHA-256
of the normalized XAML plus the node IDs
(`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the
current generation and the previously generated ones as baselines, up to
`MaxBaselines = 4`.
- **InitializeComponent** records `XamlComponentRegistry.Register(this,
"__xihr_generation:<type>", key)`.
- **UpdateComponent** reads the instance's recorded key:
- A retained generation whose diff produces exactly the current node IDs
gets its own branch: the patch diffed from that generation.
- Anything else gets the default patch, diffed from the last generated
XAML. This matches the previous behavior.
- Every patched instance then records the new key, so running the patch
again, or for a C#-only edit, changes nothing.
- When there is nothing to patch, the output is unchanged: an empty UC,
with no marker. Rude-edit rollback behavior is preserved, and the older
applied generation now also gets its own branch.

**Known edge, not a regression:** a retained generation whose diff would
assign different IDs from the current ones (e.g. some reverts) is not
given a branch. Instances at that generation fall back to the default
patch, which is the old behavior.

### Issues Fixed

Fixes #36937 (remaining limitation from #40330)

### Tests

-
`XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`:
real metadata update. Applied `Text="Hello"`, then a throwaway run with
`Text="World" FontSize="30"`, then the real edit to `Text="World"`. The
live label ends at `World` with its default `FontSize`, re-running UC is
a no-op, and new instances are already current. A new harness hook,
`GenerateWithThrowawayRuns`, runs and discards a forked driver run.
-
`XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`:
checks the branch structure and determinism (same snapshot and C#-only
edits give an identical UC).
- `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded`
- Existing rude-edit assertions now target the default patch
(`UpdateComponentText.DefaultPatch`), because the UC legitimately
contains a branch for the older applied generation.

### Validation

- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**passed**, 899/899.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **passed**, 12/12.
- `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274
passed, 12 failed. All 12 failures are `CultureNotFoundException` from
culture-specific tests under invariant-globalization mode; none involve
hot reload.
- `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes
--include <changed files>`: **passed**.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Nov 19, 2026
…40413) (#40417)

<!-- 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).

**Base is `candidate/11.0.1xx-sr2`, not `net11`.** The PR is test-only
and covers behavior that exists only on the candidate branch, from the
#36937 fix chain #40233, #40235, #40329, #40330, and #40378. Against
`net11` the test fails, because that fix has not flowed there yet. This
follows the precedent of #40329, #40330, and #40378, which targeted this
branch for the same reason. Maintainers: retarget if you prefer a
different lane.

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

#40413 reports that in VS on Windows (.NET 11, SourceGen inflator, XAML
Incremental Hot Reload on by default in Debug), editing a Label's `Text`
in the default template's `MainPage.xaml` is not applied.

**Root cause.** This is #36937. Roslyn/VS evaluate the same edited
generator-driver snapshot more than once, for example forked or
speculative runs, or a throwaway compilation before the applied one. On
`net11`, the first evaluation advances the cached previous XAML. The
evaluation that is actually applied then sees no diff and emits an empty
`UpdateComponent`, and the runtime silently skips it. The bug became
visible in .NET 11 because XIHR is now the default; 10.0.120 used legacy
XAML Hot Reload.

I reproduced this with the issue's own template `MainPage.xaml` through
the source generator:

| Sequence | `net11` (a25e629) | `candidate/11.0.1xx-sr2`
(cec6650) |
| --- | --- | --- |
| Edit evaluated once | patch | patch |
| Same edited snapshot evaluated twice: 2nd run | **empty UC** | patch |
| Throwaway compilation first, then real run: real run | **empty UC** |
patch |

On the candidate branch the existing fixes already handle this. This PR
adds
`DefaultTemplateMainPageTextEdit_SurvivesRepeatedAndThrowawayEvaluations`,
a theory with repeated and throwaway-first cases. It uses the template
page shape (`StaticResource` styles from a sibling `Styles.xaml`,
`x:Name`, a `Clicked` handler in code-behind) to lock in the reported
scenario. There are no product changes.

**Android .NET 10 (validation comment).** This is a separate scenario.
XIHR was not the default in .NET 10, so that report involves the legacy
XAML Hot Reload path and is not caused by this regression. It is not
addressed here.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj
--filter
"FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~CodeBehindFieldStabilityTests"`:
**passed**, 93/93, on this branch.
- `net11`: the same two sequences, run through an equivalent temporary
probe with the template XAML, produce an empty UC, as shown in the
table. I did not port the committed test itself to `net11`: its helpers
exist only on candidate, and reverting the fix commits in place
conflicts.
- Not verified in Visual Studio on Windows or on device; I worked on a
macOS host.

### Issues Fixed

Fixes #40413

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Nov 22, 2026
… different C# (#40330)

<!-- 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).

**Base note:** this is a follow-up to #40233, which was merged into
`candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This
change modifies code that only exists there, so the PR targets
`candidate/11.0.1xx-sr2`.

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 #40233, closing the gap it documented: if a **throwaway
compilation with different user C#** (speculative or design-time
snapshot) evaluates the edited XAML before the real compilation does,
the pending `UpdateComponent()` patch is lost. The generator couldn't
tell this apart from a genuine C#-only edit, which had to emit an
*empty* `UpdateComponent()` because the runtime classified a delta as a
XAML change by the emptiness of that body.

**Fix: move the classification to a companion signal type, as
@noiseonwires proposed on #36937.** The `MetadataUpdateHandler` is in
this repo, so no Roslyn or hot reload agent changes are needed.

- **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now
also nests a private `__XamlHotReloadSignal` type in each XIHR root,
with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's
no patch). It's emitted on every generation, like `UpdateComponent()`,
so there's no member churn. Its content only changes when the patch
changes, so Roslyn lists it in a delta exactly when there's a new patch
to apply.
- **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML
is unchanged and a patch is pending, the patch is always re-derived from
its baseline, whatever the C# sources are. The output becomes a function
of the inputs, not of evaluation order or of which compilation ran
first. The `UserSourcesFingerprint` gate from #40233 (and the extra
compilation input to the pipeline) is removed.
- **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the
companion type counts as a XAML change only if the delta lists the
companion **and** `UpdateComponent()` isn't empty. This keeps structural
changes, which reset the body to empty, out, as before. A companion
listed without its root is mapped back to the root. Roots without a
companion (older generated code) keep the existing empty-body check.
`UpdateRequested.HandledTypes` and the
`UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged.

With this, a C#-only edit re-emits the same patch. `UpdateComponent()`
and the companion are byte-identical, so they aren't in the delta and
the patch isn't re-applied. This matters because patches aren't always
idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML
edit whose delta was rejected (e.g. it was combined with a C# rude edit)
still carries its patch on the next generation instead of an empty body.

**Remaining limitation (not addressed here):** a throwaway run with
*different XAML* (e.g. an intermediate keystroke) still advances the
cached "previous" XAML. The next real patch is then diffed from that
intermediate state rather than from what the app last applied. Fixing
that would need knowledge of the last applied generation.

**Tests**
- `XamlIncrementalHotReloadPipelineTests`
- `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is
the gap from #40233. It fails without the fix.
- `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces
`CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose
expectation is intentionally changed.
  - `SignalFingerprint_ChangesWithThePatchOnly`.
- `XamlIncrementalHotReloadE2ETests` (real
`MetadataUpdater.ApplyUpdate`)
- `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live
label changed at runtime isn't overwritten by a C#-only delta.
- `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates
the existing classification test.
- The test harness now lists the companion type among the delta's
updated types only when its fingerprint changed, like Roslyn does.
- `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two
handler tests cover a root with a companion type and a companion listed
alone.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**855 passed, 0 failed, 0 skipped**.
- With only the generator/state change reverted, 3 new tests fail,
including the throwaway test. With only the handler change reverted, the
2 E2E runtime tests fail.
- `dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`:
**2250 passed, 2 failed, 8 skipped**. The 2 failures
(`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass
with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **12 passed**.
- `dotnet format whitespace --verify-no-changes` on the changed files:
clean.

### Issues Fixed

Fixes #36937

Follow-up to #40233.

---------
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Nov 22, 2026
…ns (#40378)

<!-- 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).

> [!IMPORTANT]
> **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on
#40233, #40235, #40329 and #40330, which exist only on
`candidate/11.0.1xx-sr2` (not on `net11`, `main` or
`inflight/11.0.1xx-sr3`). Against `net11` the diff would include about
527 unrelated files. As with #40329 and #40330, it targets
`candidate/11.0.1xx-sr2` directly so it ships together with its
prerequisites.

### Description of Change

#40330 left one limitation. A throwaway generator run with different
XAML, such as a design-time or speculative run whose output never
reaches the app, advanced the cached previous XAML. The next real
`UpdateComponent()` was then diffed from that intermediate generation
instead of the generation the running app actually has. The result was
missed edits: for example, an edit already present in the throwaway XAML
was never applied.

The generator cannot tell which of its runs reached the app, so this PR
has `UpdateComponent()` decide at runtime:

- **Generation key.** Each successful generation gets a key: a SHA-256
of the normalized XAML plus the node IDs
(`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the
current generation and the previously generated ones as baselines, up to
`MaxBaselines = 4`.
- **InitializeComponent** records `XamlComponentRegistry.Register(this,
"__xihr_generation:<type>", key)`.
- **UpdateComponent** reads the instance's recorded key:
- A retained generation whose diff produces exactly the current node IDs
gets its own branch: the patch diffed from that generation.
- Anything else gets the default patch, diffed from the last generated
XAML. This matches the previous behavior.
- Every patched instance then records the new key, so running the patch
again, or for a C#-only edit, changes nothing.
- When there is nothing to patch, the output is unchanged: an empty UC,
with no marker. Rude-edit rollback behavior is preserved, and the older
applied generation now also gets its own branch.

**Known edge, not a regression:** a retained generation whose diff would
assign different IDs from the current ones (e.g. some reverts) is not
given a branch. Instances at that generation fall back to the default
patch, which is the old behavior.

### Issues Fixed

Fixes #36937 (remaining limitation from #40330)

### Tests

-
`XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`:
real metadata update. Applied `Text="Hello"`, then a throwaway run with
`Text="World" FontSize="30"`, then the real edit to `Text="World"`. The
live label ends at `World` with its default `FontSize`, re-running UC is
a no-op, and new instances are already current. A new harness hook,
`GenerateWithThrowawayRuns`, runs and discards a forked driver run.
-
`XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`:
checks the branch structure and determinism (same snapshot and C#-only
edits give an identical UC).
- `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded`
- Existing rude-edit assertions now target the default patch
(`UpdateComponentText.DefaultPatch`), because the UC legitimately
contains a branch for the older applied generation.

### Validation

- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**passed**, 899/899.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **passed**, 12/12.
- `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274
passed, 12 failed. All 12 failures are `CultureNotFoundException` from
culture-specific tests under invariant-globalization mode; none involve
hot reload.
- `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes
--include <changed files>`: **passed**.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Nov 22, 2026
…40413) (#40417)

<!-- 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).

**Base is `candidate/11.0.1xx-sr2`, not `net11`.** The PR is test-only
and covers behavior that exists only on the candidate branch, from the
#36937 fix chain #40233, #40235, #40329, #40330, and #40378. Against
`net11` the test fails, because that fix has not flowed there yet. This
follows the precedent of #40329, #40330, and #40378, which targeted this
branch for the same reason. Maintainers: retarget if you prefer a
different lane.

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

#40413 reports that in VS on Windows (.NET 11, SourceGen inflator, XAML
Incremental Hot Reload on by default in Debug), editing a Label's `Text`
in the default template's `MainPage.xaml` is not applied.

**Root cause.** This is #36937. Roslyn/VS evaluate the same edited
generator-driver snapshot more than once, for example forked or
speculative runs, or a throwaway compilation before the applied one. On
`net11`, the first evaluation advances the cached previous XAML. The
evaluation that is actually applied then sees no diff and emits an empty
`UpdateComponent`, and the runtime silently skips it. The bug became
visible in .NET 11 because XIHR is now the default; 10.0.120 used legacy
XAML Hot Reload.

I reproduced this with the issue's own template `MainPage.xaml` through
the source generator:

| Sequence | `net11` (a25e629) | `candidate/11.0.1xx-sr2`
(cec6650) |
| --- | --- | --- |
| Edit evaluated once | patch | patch |
| Same edited snapshot evaluated twice: 2nd run | **empty UC** | patch |
| Throwaway compilation first, then real run: real run | **empty UC** |
patch |

On the candidate branch the existing fixes already handle this. This PR
adds
`DefaultTemplateMainPageTextEdit_SurvivesRepeatedAndThrowawayEvaluations`,
a theory with repeated and throwaway-first cases. It uses the template
page shape (`StaticResource` styles from a sibling `Styles.xaml`,
`x:Name`, a `Clicked` handler in code-behind) to lock in the reported
scenario. There are no product changes.

**Android .NET 10 (validation comment).** This is a separate scenario.
XIHR was not the default in .NET 10, so that report involves the legacy
XAML Hot Reload path and is not caused by this regression. It is not
addressed here.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj
--filter
"FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~CodeBehindFieldStabilityTests"`:
**passed**, 93/93, on this branch.
- `net11`: the same two sequences, run through an equivalent temporary
probe with the template XAML, produce an empty UC, as shown in the
table. I did not port the committed test itself to `net11`: its helpers
exist only on candidate, and reverting the fix commits in place
conflicts.
- Not verified in Visual Studio on Windows or on device; I worked on a
macOS host.

### Issues Fixed

Fixes #40413

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Nov 23, 2026
… different C# (#40330)

<!-- 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).

**Base note:** this is a follow-up to #40233, which was merged into
`candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This
change modifies code that only exists there, so the PR targets
`candidate/11.0.1xx-sr2`.

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 #40233, closing the gap it documented: if a **throwaway
compilation with different user C#** (speculative or design-time
snapshot) evaluates the edited XAML before the real compilation does,
the pending `UpdateComponent()` patch is lost. The generator couldn't
tell this apart from a genuine C#-only edit, which had to emit an
*empty* `UpdateComponent()` because the runtime classified a delta as a
XAML change by the emptiness of that body.

**Fix: move the classification to a companion signal type, as
@noiseonwires proposed on #36937.** The `MetadataUpdateHandler` is in
this repo, so no Roslyn or hot reload agent changes are needed.

- **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now
also nests a private `__XamlHotReloadSignal` type in each XIHR root,
with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's
no patch). It's emitted on every generation, like `UpdateComponent()`,
so there's no member churn. Its content only changes when the patch
changes, so Roslyn lists it in a delta exactly when there's a new patch
to apply.
- **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML
is unchanged and a patch is pending, the patch is always re-derived from
its baseline, whatever the C# sources are. The output becomes a function
of the inputs, not of evaluation order or of which compilation ran
first. The `UserSourcesFingerprint` gate from #40233 (and the extra
compilation input to the pipeline) is removed.
- **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the
companion type counts as a XAML change only if the delta lists the
companion **and** `UpdateComponent()` isn't empty. This keeps structural
changes, which reset the body to empty, out, as before. A companion
listed without its root is mapped back to the root. Roots without a
companion (older generated code) keep the existing empty-body check.
`UpdateRequested.HandledTypes` and the
`UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged.

With this, a C#-only edit re-emits the same patch. `UpdateComponent()`
and the companion are byte-identical, so they aren't in the delta and
the patch isn't re-applied. This matters because patches aren't always
idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML
edit whose delta was rejected (e.g. it was combined with a C# rude edit)
still carries its patch on the next generation instead of an empty body.

**Remaining limitation (not addressed here):** a throwaway run with
*different XAML* (e.g. an intermediate keystroke) still advances the
cached "previous" XAML. The next real patch is then diffed from that
intermediate state rather than from what the app last applied. Fixing
that would need knowledge of the last applied generation.

**Tests**
- `XamlIncrementalHotReloadPipelineTests`
- `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is
the gap from #40233. It fails without the fix.
- `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces
`CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose
expectation is intentionally changed.
  - `SignalFingerprint_ChangesWithThePatchOnly`.
- `XamlIncrementalHotReloadE2ETests` (real
`MetadataUpdater.ApplyUpdate`)
- `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live
label changed at runtime isn't overwritten by a C#-only delta.
- `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates
the existing classification test.
- The test harness now lists the companion type among the delta's
updated types only when its fingerprint changed, like Roslyn does.
- `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two
handler tests cover a root with a companion type and a companion listed
alone.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**855 passed, 0 failed, 0 skipped**.
- With only the generator/state change reverted, 3 new tests fail,
including the throwaway test. With only the handler change reverted, the
2 E2E runtime tests fail.
- `dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`:
**2250 passed, 2 failed, 8 skipped**. The 2 failures
(`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass
with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **12 passed**.
- `dotnet format whitespace --verify-no-changes` on the changed files:
clean.

### Issues Fixed

Fixes #36937

Follow-up to #40233.

---------
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Nov 23, 2026
…ns (#40378)

<!-- 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).

> [!IMPORTANT]
> **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on
#40233, #40235, #40329 and #40330, which exist only on
`candidate/11.0.1xx-sr2` (not on `net11`, `main` or
`inflight/11.0.1xx-sr3`). Against `net11` the diff would include about
527 unrelated files. As with #40329 and #40330, it targets
`candidate/11.0.1xx-sr2` directly so it ships together with its
prerequisites.

### Description of Change

#40330 left one limitation. A throwaway generator run with different
XAML, such as a design-time or speculative run whose output never
reaches the app, advanced the cached previous XAML. The next real
`UpdateComponent()` was then diffed from that intermediate generation
instead of the generation the running app actually has. The result was
missed edits: for example, an edit already present in the throwaway XAML
was never applied.

The generator cannot tell which of its runs reached the app, so this PR
has `UpdateComponent()` decide at runtime:

- **Generation key.** Each successful generation gets a key: a SHA-256
of the normalized XAML plus the node IDs
(`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the
current generation and the previously generated ones as baselines, up to
`MaxBaselines = 4`.
- **InitializeComponent** records `XamlComponentRegistry.Register(this,
"__xihr_generation:<type>", key)`.
- **UpdateComponent** reads the instance's recorded key:
- A retained generation whose diff produces exactly the current node IDs
gets its own branch: the patch diffed from that generation.
- Anything else gets the default patch, diffed from the last generated
XAML. This matches the previous behavior.
- Every patched instance then records the new key, so running the patch
again, or for a C#-only edit, changes nothing.
- When there is nothing to patch, the output is unchanged: an empty UC,
with no marker. Rude-edit rollback behavior is preserved, and the older
applied generation now also gets its own branch.

**Known edge, not a regression:** a retained generation whose diff would
assign different IDs from the current ones (e.g. some reverts) is not
given a branch. Instances at that generation fall back to the default
patch, which is the old behavior.

### Issues Fixed

Fixes #36937 (remaining limitation from #40330)

### Tests

-
`XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`:
real metadata update. Applied `Text="Hello"`, then a throwaway run with
`Text="World" FontSize="30"`, then the real edit to `Text="World"`. The
live label ends at `World` with its default `FontSize`, re-running UC is
a no-op, and new instances are already current. A new harness hook,
`GenerateWithThrowawayRuns`, runs and discards a forked driver run.
-
`XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`:
checks the branch structure and determinism (same snapshot and C#-only
edits give an identical UC).
- `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded`
- Existing rude-edit assertions now target the default patch
(`UpdateComponentText.DefaultPatch`), because the UC legitimately
contains a branch for the older applied generation.

### Validation

- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**passed**, 899/899.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **passed**, 12/12.
- `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274
passed, 12 failed. All 12 failures are `CultureNotFoundException` from
culture-specific tests under invariant-globalization mode; none involve
hot reload.
- `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes
--include <changed files>`: **passed**.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Nov 23, 2026
…40413) (#40417)

<!-- 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).

**Base is `candidate/11.0.1xx-sr2`, not `net11`.** The PR is test-only
and covers behavior that exists only on the candidate branch, from the
#36937 fix chain #40233, #40235, #40329, #40330, and #40378. Against
`net11` the test fails, because that fix has not flowed there yet. This
follows the precedent of #40329, #40330, and #40378, which targeted this
branch for the same reason. Maintainers: retarget if you prefer a
different lane.

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

#40413 reports that in VS on Windows (.NET 11, SourceGen inflator, XAML
Incremental Hot Reload on by default in Debug), editing a Label's `Text`
in the default template's `MainPage.xaml` is not applied.

**Root cause.** This is #36937. Roslyn/VS evaluate the same edited
generator-driver snapshot more than once, for example forked or
speculative runs, or a throwaway compilation before the applied one. On
`net11`, the first evaluation advances the cached previous XAML. The
evaluation that is actually applied then sees no diff and emits an empty
`UpdateComponent`, and the runtime silently skips it. The bug became
visible in .NET 11 because XIHR is now the default; 10.0.120 used legacy
XAML Hot Reload.

I reproduced this with the issue's own template `MainPage.xaml` through
the source generator:

| Sequence | `net11` (a25e629) | `candidate/11.0.1xx-sr2`
(cec6650) |
| --- | --- | --- |
| Edit evaluated once | patch | patch |
| Same edited snapshot evaluated twice: 2nd run | **empty UC** | patch |
| Throwaway compilation first, then real run: real run | **empty UC** |
patch |

On the candidate branch the existing fixes already handle this. This PR
adds
`DefaultTemplateMainPageTextEdit_SurvivesRepeatedAndThrowawayEvaluations`,
a theory with repeated and throwaway-first cases. It uses the template
page shape (`StaticResource` styles from a sibling `Styles.xaml`,
`x:Name`, a `Clicked` handler in code-behind) to lock in the reported
scenario. There are no product changes.

**Android .NET 10 (validation comment).** This is a separate scenario.
XIHR was not the default in .NET 10, so that report involves the legacy
XAML Hot Reload path and is not caused by this regression. It is not
addressed here.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj
--filter
"FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~CodeBehindFieldStabilityTests"`:
**passed**, 93/93, on this branch.
- `net11`: the same two sequences, run through an equivalent temporary
probe with the template XAML, produce an empty UC, as shown in the
table. I did not port the committed test itself to `net11`: its helpers
exist only on candidate, and reverting the fix commits in place
conflicts.
- Not verified in Visual Studio on Windows or on device; I worked on a
macOS host.

### Issues Fixed

Fixes #40413

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@kubaflo kubaflo added this to the .NET 11 SR2 milestone Nov 24, 2026
KarthikRajaKalaimani pushed a commit to KarthikRajaKalaimani/maui that referenced this pull request Nov 26, 2026
… different C# (dotnet#40330)

<!-- 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).

**Base note:** this is a follow-up to dotnet#40233, which was merged into
`candidate/11.0.1xx-sr2` and is not in `net11` (or `main`) yet. This
change modifies code that only exists there, so the PR targets
`candidate/11.0.1xx-sr2`.

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 dotnet#40233, closing the gap it documented: if a **throwaway
compilation with different user C#** (speculative or design-time
snapshot) evaluates the edited XAML before the real compilation does,
the pending `UpdateComponent()` patch is lost. The generator couldn't
tell this apart from a genuine C#-only edit, which had to emit an
*empty* `UpdateComponent()` because the runtime classified a delta as a
XAML change by the emptiness of that body.

**Fix: move the classification to a companion signal type, as
@noiseonwires proposed on dotnet#36937.** The `MetadataUpdateHandler` is in
this repo, so no Roslyn or hot reload agent changes are needed.

- **Generator (`UpdateComponentCodeWriter`)**: the `.uc.xsg.cs` file now
also nests a private `__XamlHotReloadSignal` type in each XIHR root,
with `Fingerprint() => "<sha256 of the patch body>"` (`""` when there's
no patch). It's emitted on every generation, like `UpdateComponent()`,
so there's no member churn. Its content only changes when the patch
changes, so Roslyn lists it in a delta exactly when there's a new patch
to apply.
- **Generator (`XamlGenerator` / `XamlHotReloadState`)**: when the XAML
is unchanged and a patch is pending, the patch is always re-derived from
its baseline, whatever the C# sources are. The output becomes a function
of the inputs, not of evaluation order or of which compilation ran
first. The `UserSourcesFingerprint` gate from dotnet#40233 (and the extra
compilation input to the pipeline) is removed.
- **Runtime (`XamlIncrementalHotReloadHandler`)**: a root that has the
companion type counts as a XAML change only if the delta lists the
companion **and** `UpdateComponent()` isn't empty. This keeps structural
changes, which reset the body to empty, out, as before. A companion
listed without its root is mapped back to the root. Roots without a
companion (older generated code) keep the existing empty-body check.
`UpdateRequested.HandledTypes` and the
`UpdateApplied`/`UpdateSkipped`/`UpdateFailed` contract are unchanged.

With this, a C#-only edit re-emits the same patch. `UpdateComponent()`
and the companion are byte-identical, so they aren't in the delta and
the patch isn't re-applied. This matters because patches aren't always
idempotent: reorders use `RemoveAt`/`Insert`. As a side benefit, a XAML
edit whose delta was rejected (e.g. it was combined with a C# rude edit)
still carries its patch on the next generation instead of an empty body.

**Remaining limitation (not addressed here):** a throwaway run with
*different XAML* (e.g. an intermediate keystroke) still advances the
cached "previous" XAML. The next real patch is then diffed from that
intermediate state rather than from what the app last applied. Fixing
that would need knowledge of the last applied generation.

**Tests**
- `XamlIncrementalHotReloadPipelineTests`
- `ThrowawayRunWithDifferentCSharpFirst_DoesNotConsumePendingPatch` is
the gap from dotnet#40233. It fails without the fix.
- `CSharpOnlyEditAfterXamlEdit_KeepsPatchAndSignalUnchanged` replaces
`CSharpOnlyEditAfterXamlEdit_EmitsEmptyUpdateComponent`, whose
expectation is intentionally changed.
  - `SignalFingerprint_ChangesWithThePatchOnly`.
- `XamlIncrementalHotReloadE2ETests` (real
`MetadataUpdater.ApplyUpdate`)
- `CSharpOnlyEditAfterXamlEdit_DoesNotReapplyPatch` checks that a live
label changed at runtime isn't overwritten by a C#-only delta.
- `UpdateRequested_ReportsXamlChange_WhenSignalTypeIsUpdated` updates
the existing classification test.
- The test harness now lists the companion type among the delta's
updated types only when its fingerprint changed, like Roslyn does.
- `Controls.Core.UnitTests/XamlIncrementalHotReloadHandlerTests`: two
handler tests cover a root with a companion type and a companion listed
alone.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**855 passed, 0 failed, 0 skipped**.
- With only the generator/state change reverted, 3 new tests fail,
including the throwaway test. With only the handler change reverted, the
2 E2E runtime tests fail.
- `dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`:
**2250 passed, 2 failed, 8 skipped**. The 2 failures
(`TwoWayDecimalBinding_*`) depend on the dev machine's locale and pass
with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **12 passed**.
- `dotnet format whitespace --verify-no-changes` on the changed files:
clean.

### Issues Fixed

Fixes dotnet#36937

Follow-up to dotnet#40233.

---------
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
KarthikRajaKalaimani pushed a commit to KarthikRajaKalaimani/maui that referenced this pull request Nov 26, 2026
…ns (dotnet#40378)

<!-- 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).

> [!IMPORTANT]
> **Base: `candidate/11.0.1xx-sr2` (decided).** This PR builds on
dotnet#40233, dotnet#40235, dotnet#40329 and dotnet#40330, which exist only on
`candidate/11.0.1xx-sr2` (not on `net11`, `main` or
`inflight/11.0.1xx-sr3`). Against `net11` the diff would include about
527 unrelated files. As with dotnet#40329 and dotnet#40330, it targets
`candidate/11.0.1xx-sr2` directly so it ships together with its
prerequisites.

### Description of Change

dotnet#40330 left one limitation. A throwaway generator run with different
XAML, such as a design-time or speculative run whose output never
reaches the app, advanced the cached previous XAML. The next real
`UpdateComponent()` was then diffed from that intermediate generation
instead of the generation the running app actually has. The result was
missed edits: for example, an edit already present in the throwaway XAML
was never applied.

The generator cannot tell which of its runs reached the app, so this PR
has `UpdateComponent()` decide at runtime:

- **Generation key.** Each successful generation gets a key: a SHA-256
of the normalized XAML plus the node IDs
(`NodeIdHelper.ComputeGenerationKey`). `XamlHotReloadState` keeps the
current generation and the previously generated ones as baselines, up to
`MaxBaselines = 4`.
- **InitializeComponent** records `XamlComponentRegistry.Register(this,
"__xihr_generation:<type>", key)`.
- **UpdateComponent** reads the instance's recorded key:
- A retained generation whose diff produces exactly the current node IDs
gets its own branch: the patch diffed from that generation.
- Anything else gets the default patch, diffed from the last generated
XAML. This matches the previous behavior.
- Every patched instance then records the new key, so running the patch
again, or for a C#-only edit, changes nothing.
- When there is nothing to patch, the output is unchanged: an empty UC,
with no marker. Rude-edit rollback behavior is preserved, and the older
applied generation now also gets its own branch.

**Known edge, not a regression:** a retained generation whose diff would
assign different IDs from the current ones (e.g. some reverts) is not
given a branch. Instances at that generation fall back to the default
patch, which is the old behavior.

### Issues Fixed

Fixes dotnet#36937 (remaining limitation from dotnet#40330)

### Tests

-
`XamlIncrementalHotReloadE2ETests.ThrowawayRunWithDifferentXaml_PatchStartsFromTheAppliedGeneration`:
real metadata update. Applied `Text="Hello"`, then a throwaway run with
`Text="World" FontSize="30"`, then the real edit to `Text="World"`. The
live label ends at `World` with its default `FontSize`, re-running UC is
a no-op, and new instances are already current. A new harness hook,
`GenerateWithThrowawayRuns`, runs and discards a forked driver run.
-
`XamlIncrementalHotReloadPipelineTests.ThrowawayRunWithDifferentXaml_PatchesFromEveryRetainedGeneration`:
checks the branch structure and determinism (same snapshot and C#-only
edits give an identical UC).
- `XamlIncrementalHotReloadPipelineTests.RetainedGenerations_AreBounded`
- Existing rude-edit assertions now target the default patch
(`UpdateComponentText.DefaultPatch`), because the UC legitimately
contains a branch for the older applied generation.

### Validation

- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
**passed**, 899/899.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~HotReload"`: **passed**, 12/12.
- `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj`: 2274
passed, 12 failed. All 12 failures are `CultureNotFoundException` from
culture-specific tests under invariant-globalization mode; none involve
hot reload.
- `dotnet format whitespace Microsoft.Maui.sln --verify-no-changes
--include <changed files>`: **passed**.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
KarthikRajaKalaimani pushed a commit to KarthikRajaKalaimani/maui that referenced this pull request Nov 26, 2026
…otnet#40413) (dotnet#40417)

<!-- 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).

**Base is `candidate/11.0.1xx-sr2`, not `net11`.** The PR is test-only
and covers behavior that exists only on the candidate branch, from the
dotnet#36937 fix chain dotnet#40233, dotnet#40235, dotnet#40329, dotnet#40330, and dotnet#40378. Against
`net11` the test fails, because that fix has not flowed there yet. This
follows the precedent of dotnet#40329, dotnet#40330, and dotnet#40378, which targeted this
branch for the same reason. Maintainers: retarget if you prefer a
different lane.

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

dotnet#40413 reports that in VS on Windows (.NET 11, SourceGen inflator, XAML
Incremental Hot Reload on by default in Debug), editing a Label's `Text`
in the default template's `MainPage.xaml` is not applied.

**Root cause.** This is dotnet#36937. Roslyn/VS evaluate the same edited
generator-driver snapshot more than once, for example forked or
speculative runs, or a throwaway compilation before the applied one. On
`net11`, the first evaluation advances the cached previous XAML. The
evaluation that is actually applied then sees no diff and emits an empty
`UpdateComponent`, and the runtime silently skips it. The bug became
visible in .NET 11 because XIHR is now the default; 10.0.120 used legacy
XAML Hot Reload.

I reproduced this with the issue's own template `MainPage.xaml` through
the source generator:

| Sequence | `net11` (a25e629) | `candidate/11.0.1xx-sr2`
(cec6650) |
| --- | --- | --- |
| Edit evaluated once | patch | patch |
| Same edited snapshot evaluated twice: 2nd run | **empty UC** | patch |
| Throwaway compilation first, then real run: real run | **empty UC** |
patch |

On the candidate branch the existing fixes already handle this. This PR
adds
`DefaultTemplateMainPageTextEdit_SurvivesRepeatedAndThrowawayEvaluations`,
a theory with repeated and throwaway-first cases. It uses the template
page shape (`StaticResource` styles from a sibling `Styles.xaml`,
`x:Name`, a `Clicked` handler in code-behind) to lock in the reported
scenario. There are no product changes.

**Android .NET 10 (validation comment).** This is a separate scenario.
XIHR was not the default in .NET 10, so that report involves the legacy
XAML Hot Reload path and is not caused by this regression. It is not
addressed here.

**Validation**
- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj
--filter
"FullyQualifiedName~XamlIncrementalHotReloadPipelineTests|FullyQualifiedName~CodeBehindFieldStabilityTests"`:
**passed**, 93/93, on this branch.
- `net11`: the same two sequences, run through an equivalent temporary
probe with the template XAML, produce an empty UC, as shown in the
table. I did not port the committed test itself to `net11`: its helpers
exist only on candidate, and reverting the fix commits in place
conflicts.
- Not verified in Visual Studio on Windows or on device; I worked on a
macOS host.

### Issues Fixed

Fixes dotnet#40413

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.