Repository navigation
[XSG] Hot reload: refresh keyed and Class style consumers on setter edits - #40418
Conversation
…dits Incremental XAML Hot Reload patched a keyed or Class style's setter by assigning the raw string to the live Setter.Value, which skipped type conversion and never reapplied the style. Consumers kept stale values. The generator now rebuilds the style through the normal visitor pipeline and calls the new XamlComponentRegistry.TryUpdateStyle helper. When the live style is materialized and shared, its setters are replaced in place and reapplied to every element using it (StaticResource, DynamicResource, StyleClass and derived styles). Otherwise the dictionary entry is replaced so future lookups get the new style. Fixes #39984 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 40418Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 40418" |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
🟡 Changes recommended
Style edits can leave consumers with stale values, break precedence across multiple style classes, and prematurely initialize unused lazy styles and their resource dependencies.
4 open issues
What changed in this PR
Extends source-generated XAML Hot Reload to refresh keyed and class-style consumers after scalar setter edits in root resource dictionaries. This addresses #39984 and builds on the implicit-style support in #39928.
Changes:
- Rebuilds edited styles and updates compatible live instances rather than replacing references held by consumers.
- Adds setter reapplication and non-materializing resource lookup helpers.
- Adds lazy/eager regression tests, test-harness options, and public API declarations.
| File | Description |
|---|---|
src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs |
Adds the lazy-resource generation option. |
src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs |
Passes lazy-resource settings into generation. |
src/Controls/tests/SourceGen.UnitTests/HotReload/Maui39984Tests.cs |
Tests generated patches and live style updates. |
src/Controls/src/Xaml/XamlComponentRegistry.cs |
Locates compatible live styles and updates their setters. |
src/Controls/src/Xaml/PublicAPI/netstandard/PublicAPI.Unshipped.txt |
Declares the helper for .NET Standard. |
src/Controls/src/Xaml/PublicAPI/net/PublicAPI.Unshipped.txt |
Declares the helper for .NET. |
src/Controls/src/Xaml/PublicAPI/net-windows/PublicAPI.Unshipped.txt |
Declares the helper for Windows. |
src/Controls/src/Xaml/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt |
Declares the helper for Mac Catalyst. |
src/Controls/src/Xaml/PublicAPI/net-ios/PublicAPI.Unshipped.txt |
Declares the helper for iOS. |
src/Controls/src/Xaml/PublicAPI/net-android/PublicAPI.Unshipped.txt |
Declares the helper for Android. |
src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs |
Generates keyed and class-style update patches. |
src/Controls/src/SourceGen/SetPropertyHelpers.cs |
Generates live-update calls with lazy-factory fallback. |
src/Controls/src/Core/Style.cs |
Replaces setters and reapplies them to tracked targets. |
src/Controls/src/Core/ResourceDictionary.cs |
Adds lookup of already-materialized local resources. |
Review effort: Balanced
|
|
||
| foreach (var (target, specificity) in targets) | ||
| foreach (Setter setter in Setters) | ||
| setter.Apply(target, specificity); |
There was a problem hiding this comment.
[major] Logic and Correctness Verification - Reapplying only the edited style breaks precedence between styles sharing a specificity. For a Label with StyleClass="A,B", let A set TextColor=Red and FontSize=12, and B set TextColor=Blue. Editing only A's FontSize turns the retained Label red: MergedStyle applies both classes at the same specificity, so unapplying A clears B's winning TextColor entry and these lines reapply A without B. A newly created Label remains blue. The same issue affects an implicit style BasedOn an edited keyed base when both set TextColor, because AsBaseStyle() preserves implicit specificity. Reconcile the affected style layers in their original order, and cover overlapping setters in the regression tests; the current tests use only one class and nonoverlapping base/derived properties.
| && live.Class == replacement.Class | ||
| && live.ApplyToDerivedTypes == replacement.ApplyToDerivedTypes | ||
| && live.CanCascade == replacement.CanCascade | ||
| && ReferenceEquals(live.BasedOn, replacement.BasedOn) |
There was a problem hiding this comment.
[moderate] Logic and Correctness Verification - An unchanged inline Style.BasedOn is rebuilt as a fresh object, so this identity comparison rejects a scalar setter-only edit. For a root Class="Warning" style with an inline base and TextColor=Red, editing only TextColor to Blue makes TryUpdateStyle return false; the generated Class-style caller ignores false, leaving both retained and subsequently created StyleClass consumers red with either resource setting. A keyed style with the same inline base leaves retained StaticResource consumers stale after its dictionary-entry fallback. A shared keyed style based on a lazy x:Shared="False" base has the same failure, even though the edited style itself is shared and tracked. Preserve or reconcile an unchanged base rather than requiring the freshly generated base to have the old identity, and add a retained-consumer regression case for this guard.
This comment has been minimized.
This comment has been minimized.
kubaflo
left a comment
There was a problem hiding this comment.
Could you check the ai's suggestions?
|
/review run-tests |
Selected UI Tests
🧪 Test selection — click to expand❌ maui-pr-uitests #1691859 failed. See the failing checks below or the run for details. GPT-6.1 Sol: Shared style and resource infrastructure changes require a full UI test run on Android, iOS, MacCatalyst, and Windows. 🧪 Ran — 77 categories on Android, iOS, MacCatalyst, WindowsThe complete 📊 Results — failed: 124 passed, 9 failed of 133 jobs
Failed tests (17)
🤖 Why these tests — AI rationale (GPT-6.1 Sol + Claude Opus 5.5)Each model chose independently; every test that runs was selected by at least one of them.
GPT-6.1 Sol — Shared style and resource infrastructure changes require a full UI test run on Android, iOS, MacCatalyst, and Windows.
Claude Opus 5.5 — XAML source-gen hot reload fix for keyed/Class style setter edits; adds only new hot-reload-only code paths, so no UI tests are needed.
Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification. |
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
An unrelated setter edit currently reattaches all merged-style triggers and behaviors, rerunning active trigger actions and restarting behavior state; setter-only refreshes and regression coverage are needed.
1 open issue
4 resolved since last review
Review effort: Balanced
| if (mergedStyle != null && mergedStyle.ContainsStyle(this)) | ||
| mergedStyle.Reapply(); |
|
/review run-tests |
Selected UI Tests
🧪 Test selection — click to expand❌ maui-pr-uitests #1692548 failed. See the failing checks below or the run for details. GPT-6.1 Sol: Shared style/resource infrastructure changes select a full UI run on all four platforms, including Android Material3. 🧪 Ran — 77 categories on Android, iOS, MacCatalyst, WindowsThe complete 📊 Results — failed: 125 passed, 8 failed of 133 jobs
Failed tests (14)
🤖 Why these tests — AI rationale (GPT-6.1 Sol + Claude Opus 5.5)Each model chose independently; every test that runs was selected by at least one of them.
GPT-6.1 Sol — Shared style/resource infrastructure changes select a full UI run on all four platforms, including Android Material3.
Claude Opus 5.5 — XAML hot-reload (UpdateComponent) fix for keyed/Class style setter edits; no UI test behavior changes, so no UI tests are run.
Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification. |
This comment has been minimized.
This comment has been minimized.
PR Test Gate
🧪 Gate analysis — click to expand✅ Passed. The selected verification satisfied the gate's passing conditions. Unmatched, skipped, or inconclusive groups are not passing evidence. 🧪 Unit tests
Execution log excerptsWithout fix With fix PR head: 135b0f91. Without-fix baseline: f79bb5b3. |
| _ => null | ||
| }; | ||
| if (mergedStyle != null && mergedStyle.ContainsStyle(this)) | ||
| mergedStyle.Reapply(); |
There was a problem hiding this comment.
[major] Logic and Correctness Verification - Editing only FontSize on a retained Label's keyed or class style restarts active trigger actions and behavior state. MergedStyle.Reapply calls Style.UnApplyCore/ApplyCore for every style layer; an active IsEnabled=True trigger's PropertyCondition.TearDown clears its true state and SetUp restores it, invoking ExitActions and EnterActions even though IsEnabled never changed. AttachedCollection also invokes behavior detach/attach callbacks again, including attachments on unedited layers. Refresh setter layers in precedence order without tearing down existing triggers and behaviors. Add lazy/eager repeated-edit coverage asserting unchanged action and lifecycle counts; the new tests contain no such attachments.
| return false; | ||
| key = keyString; | ||
| } | ||
| bool isImplicitStyle = key is null && !style.Properties.ContainsKey(new XmlName("", "Class")); |
There was a problem hiding this comment.
[major] Input and Path Correctness - A root XAML Style with Class="" and no x:Key reaches the class-style update path because this predicate checks attribute presence rather than its value. ResourceDictionary.Add(Style) treats an empty Class as implicit and stores it under TargetType.FullName. Editing TextColor from Red to Blue therefore emits TryUpdateClassStyle, whose StyleClass-prefix lookup finds no class list; the generated caller throws InvalidOperationException and leaves the retained Label red. This fails with either LazyRD setting because Class-bearing declarations are generated eagerly. Classify the supplied Class value consistently with ResourceDictionary.Add and cover the empty-Class setter edit.
| else | ||
| { | ||
| if (!isImplicitStyle) | ||
| replacement = CreateReplacement(includeBase: false); |
There was a problem hiding this comment.
[moderate] XAML & Bindings - Rebuilding these setters leaves descendant component IDs pointing at the old instances. With eager resources, use a keyed ContentView style containing a scalar BackgroundColor setter and a Content setter whose value is a Label with Text="Before". Editing BackgroundColor recreates and installs the Label, but the conversion context has no NodeIds and this path emits no XamlComponentRegistry.Register calls for the replacement subtree. A subsequent edit to Text="After" is emitted against the original Label's ID, updating the detached object or skipping it after collection instead of changing the displayed replacement. Re-register replacement setter descendants under their stable IDs and cover this two-edit sequence.
… commit (#40483) <!-- 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 - [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). CI workflow infrastructure, so it targets `main`. ### Description of Change Follow-up to #40468, found while testing `/review run-tests` on open PRs after it merged. `maui-pr-uitests` builds GitHub's test-merge commit (`refs/pull/N/merge`). GitHub does not refresh it when `main` moves; it waits for activity on the PR. Right after #40468 merged, every open PR's merge ref still merged an older `main` (21 merged #40305's `main`, 20 merged an even older one). Some had been stale for hours. The pipeline in those commits does not declare the new `uitest_*` parameters, so the dispatcher stopped straight away with "merges an older main". Changes: - **Wait instead of failing.** `Get-VerifiedPullRequest` now treats a merge ref whose pipeline cannot take the selection as "not ready yet". It keeps polling for up to 10 minutes, which covers a refresh GitHub is already computing. A missing merge of a new head still gives up after about 3 minutes, as before. The dispatcher job timeout goes from 15 to 25 minutes to fit. - **Check every parameter that will be sent.** `Test-RunTestsPipelineSupportsSelection` also requires each `uitest_<Category>` / `uitestPlatform*` name in the queue request. Otherwise a category added to `main` later would reach Azure as an "Unexpected parameter" 400 on PRs whose merge ref predates it. - If GitHub still hasn't refreshed after 10 minutes, the comment says so and suggests commenting again later or updating the branch. ### Validation - `RunTests.Tests.ps1` and `CopilotPipeline.Tests.ps1`: 66 passed. A new test covers parameters that are missing from the built pipeline, including regex metacharacters. - Real `/review run-tests` comments after #40468 merged, using the current `main` dispatcher (without this PR): | PR | Merge ref merges | Selection | Result | | --- | --- | --- | --- | | #40437 | new `main` (head pushed after the merge) | 9 categories, all platforms | **Queued targeted build 1692555** as the trigger identity (no 403). Azure shows `selectedRun=true`, the four platform booleans and only the 9 `uitest_*` values; only the CollectionView, CV1 and per-platform stages started | | #40418 | new `main` | full suite (both models) | Full build 1692548 | | #40369, #40344, #40288 | #40305's `main` | 5 / 4 / 2 categories | Stopped: stale merge ref | | #40420 | older `main` | 4 categories, Android | Stopped: stale merge ref | A `/review run-tests` comment, an API read and a no-op base edit did not refresh a stale merge ref within 10+ minutes; a push to the PR head refreshes it at once. Until GitHub refreshes the older PRs, they need an update or push. This PR waits for any refresh GitHub is already computing, explains the situation in the comment, and keeps a later category addition from becoming an Azure 400. Co-authored-by: Copilot CI <copilot-ci@microsoft.com>
Preserve live-style updates alongside metadata-safe local resource factories and combine lazy dictionary options with existing test driver controls. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
Resolved the conflicts with Combined live-style updates with the target’s metadata-safe local resource factories and explicit delegate construction, preserving resource additions and replacement behavior. Retained the lazy-resource dictionary option alongside the existing diagnostics, preview-feature, line-info and inflator controls in the shared test drivers and Hot Reload harness. |

Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Target Branch
mainnet11, for reviewTargets
main: this is XAML incremental hot reload work, like #39928, and it adds a generator-only public API.Description of Change
When a
Setter.Valuechanged on a keyedStyleor aClassstyle in a rootResourceDictionary,UpdateComponent()emitted something like((Setter)node!).Value = "Blue";. That assigns an unconverted string and never reapplies the style, so existing consumers kept stale values. With lazy resources, even new consumers kept them. #39928 fixed implicit styles by replacing the dictionary entry. That doesn't help keyed or Class styles, becauseStaticResource,StyleClassandBasedOnconsumers hold theStyleinstance directly.Changes:
Generator (
UpdateComponentCodeWriter,SetPropertyHelpers): setter-value edits on keyed and Class styles in a root RD now rebuild the style through the normal IC visitor pipeline, as for implicit styles, and callXamlComponentRegistry.TryUpdateStyle. Fallback when that returns false:The implicit-style path is unchanged.
XamlComponentRegistry.TryUpdateStyle(new public,EditorBrowsable(Never)): finds the live style without forcing lazy factories. That means a shared, already-materialized lazy entry, an eager entry, or the single matching entry in a class list. If only the setters changed, it replaces them in place; otherwise it returns false. "Only the setters" means the same TargetType, Class, BasedOn, BaseResourceKey, ApplyToDerivedTypes and CanCascade.Style.ReplaceSetters(internal): unapplies the old setters from all tracked targets, swaps them, and reapplies the new ones with each target's specificity. Derived-style consumers are covered because a base style tracks them withAsBaseStylespecificity. Local values still win.ResourceDictionary.TryGetLocalMaterializedValue/LazyResource.TryGetCachedValue(internal): let the helper peek at an entry without resolving it.Known limitations:
x:Shared="False"styles can't be refreshed, because the instances aren't tracked. New consumers get the new value.Resourcesare out of scope; this matches [XAML] Refresh implicit styles after incremental Hot Reload setter edits #39928, which also covers only root resource dictionaries.Issues Fixed
Fixes #39984
Validation
New tests are in
src/Controls/tests/SourceGen.UnitTests/HotReload/Maui39984Tests.cs, run with both lazy and eager RD. I added aLazyRDoption to the test harness for them. They cover:BasedOnpropagationx:Shared="False"stylesThe new tests failed (8 of 8) before the fix. Commands run:
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test Microsoft.Maui.Controls.SourceGen.UnitTests.dll --filter "FullyQualifiedName~Maui39984|FullyQualifiedName~Maui39780": Passed, 14/14. I ran it from a copy of the build output outside the~-containing worktree path.dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj: 6733 passed, 1 failed. The failure isTwoWayBindingToNullableDoublePropertyWithEmptyStringBecomesNull, which also fails without this change: it's locale-dependent ("3,14" vs "3.14").dotnet build src/Controls/src/Xaml/Controls.Xaml.csproj -f netstandard2.0: succeeded with no PublicAPI errors.I did not test this on a device or in Visual Studio.