Repository navigation
[trimming] Agent guidance for trimmable handlers and lazy mapper remaps - #40715
Conversation
|
Azure Pipelines: 1 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
This comment has been minimized.
This comment has been minimized.
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.
Expert Review — No findings
Reviewed commit 077990f.
077990f to
7af2539
Compare
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
🟡 Changes recommended
Routing omissions skip the new mapper checks for mapper-only changes, and the factory-provider guidance incorrectly guarantees context availability on direct GetHandler(Type) calls.
2 open issues
What changed in this PR
This documentation-only PR completes the trimmable-handlers stack with agent guidance for attribute-based handler defaults and lazy Controls mapper remaps. It builds on #29952 and its supporting layers without changing product code.
Changes:
- Adds focused rules for handler declaration, resolution, activation, remapping, and testing.
- Updates reviewer checks for mapper customization preservation, compatibility, and trimming.
- Links the new guidance from existing handler instructions and repository-wide entry points.
| File | Description |
|---|---|
.github/README-AI.md |
Indexes both handler instruction files. |
.github/instructions/handler-registration.instructions.md |
Defines handler registration, resolution, lazy-remap, and testing guidance. |
.github/instructions/handler-patterns.instructions.md |
Adds sealing and remap-helper rules and links detailed guidance. |
.github/copilot-instructions.md |
Adds repository-wide handler and mapper guidance pointers. |
.github/agents/maui-expert-reviewer.md |
Updates mapper, compatibility, and trimming review checks. |
Review effort: Balanced
This comment has been minimized.
This comment has been minimized.
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.
Expert Review — 2 findings
Reviewed commit 6fce69c.
See inline comments for details.
Previously reported findings were not duplicated.
| - CHECK: Don't null handler references eagerly in `DisconnectHandler` — the view might be removed and re-added (e.g., Shell tab switching); clear subscriptions while keeping weak references alive | ||
| - CHECK: On Android, assign per-view state in `AttachedToWindow`/`DetachedFromWindow` rather than constructor to avoid leaks when views are recycled | ||
| - CHECK: Use `ModifyMapping` for Controls-layer overrides that override Core behavior, so user-registered mappings aren't silently replaced | ||
| - CHECK: Controls-layer overrides of Core handler mappers live in the control's lazy `RemapForControls()` (call `base.RemapForControls()`, then a static `OneTimeInitializationAction.InvokeOnce()`) and use the internal `ReplaceMappingForControls`/`AppendToMappingForControls`/`PrependToMappingForControls`/`ModifyMappingForControls` helpers. Flag the public `AppendToMapping`/`ModifyMapping`/`ReplaceMapping`/indexer inside a remap: those are the app customization layer, and a lazy framework call through them reorders or overrides app customizations made at startup. Label's Android `IsTextSelectable` and Apple `FlowDirection` public appends are the only deliberate exception. They live in `static Label()`, not the lazy remap, to keep main's type-initialization timing; flag moving them into the remap or copying the pattern |
There was a problem hiding this comment.
[minor] Logic and Correctness Verification - The unconditional base.RemapForControls() requirement rejects the valid root remaps in src/Controls/src/Core/Element/Element.Mapper.cs:15-18 and Toolbar/Toolbar.Mapper.cs:19-22. Element's base BindableObject has no such hook, and Toolbar has no remappable base, so following the prescribed fix produces uncompilable code. Require base-first ordering only when overriding an inherited remap, and make the same qualification in handler-registration.instructions.md:52.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Selected Tests
🧪 Test selection — click to expand
🧪 UI tests — nothing to runℹ️ The AI found no changes relevant to UI tests, so no GPT-6.2 Sol: No MAUI UI tests selected because the PR changes only reviewer guidance and PowerShell reviewer checks. 🧪 Running — nothingNo UI tests run for this PR. 🧪 Device tests — nothing to runℹ️ The AI found no changes relevant to device tests, so no GPT-6.2 Sol: No MAUI device tests selected because the PR does not change product code or device test infrastructure. 🧪 Running — nothingNo device tests run for this PR. ⏭️ Skipped — what neither suite runsUI tests — 77 categories, 4 platforms Platforms not run: Android, iOS, MacCatalyst, Windows Each skipped platform and category is listed as a Device tests — 105 categories, 4 platforms Platforms not run: Android, iOS, MacCatalyst, Windows Each skipped platform and project is listed as a 🤖 Why these tests — AI rationale (GPT-6.2 Sol + MAI Code 2)UI testsEach model chose independently; every test that runs was selected by at least one of them.
GPT-6.2 Sol — No MAUI UI tests selected because the PR changes only reviewer guidance and PowerShell reviewer checks.
MAI Code 2 — Agent-guidance and PowerShell review-routing-only changes; no UI or device tests can be affected.
Device testsEach model chose independently; every test that runs was selected by at least one of them.
GPT-6.2 Sol — No MAUI device tests selected because the PR does not change product code or device test infrastructure.
MAI Code 2 — Agent-guidance and review-script-only changes; no device tests are affected.
Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification. |
There was a problem hiding this comment.
Expert Review — 2 findings
Reviewed commit 6fce69c.
Previously reported findings were not duplicated.
6fce69c to
6c21f80
Compare
Add path-scoped handler-registration instructions covering [ElementHandler] defaults, feature-switch handler attributes, resolution precedence, lazy Controls remaps with the *ForControls helpers, sealed framework mappings, and testing. Point handler-patterns and copilot-instructions at it, index it in README-AI, and replace the reviewer agent's outdated ModifyMapping check with the new remap, registration and resolution checks. The hash-pinned Dimension Routing section is unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Describe when lazy remaps run and their base-first order, the unsealed SwitchHandler and TextButton/ImageButton mappers, Label's timing-dependent public appends, and that a child framework remap stops observing parent app customizations. Tell test authors to trigger the lazy remap before reading global mappers, and mention factory registrations for handlers that need constructor arguments. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Controls *.Mapper.cs partials, Core mapper infrastructure (PropertyMapper*, CommandMapper*, MappingCustomizationSequence) and mapper tests now activate dimension 3 in both the reviewer rulebook and Review-Expert.ps1, with the pinned routing hash updated together. Also qualify the handler-factory guidance: the provider resolves the current IMauiContext only on context-taking activation paths such as ToHandler(), not on public GetHandler(Type). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Label's public Android IsTextSelectable and Apple FlowDirection appends now run from static Label(), not the lazy remap. Platform view factories are installed through InstallPlatformViewFactory() with ??=. A framework remap of an inherited key builds on the parent's mapping at first attachment. Sealed mappers return child-bound mappings for inherited keys while unsealed ones return the chained mapping, and internals use GetPropertyDirect. Also cover interface ambiguity, Hot Reload replacement of attribute handlers, non-singleton injected handlers and the HandlerResolution.md behavior changes section. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… exception The rulebook's Trimming/AOT and Backward Compatibility triggers now include any .cs change, matching Get-ExpertExpectedDimensions, so inline self-reviews that select dimensions from the rulebook also reach the [ElementHandler] checks. The pinned routing hash is updated with it. Add Review-Expert.Tests.ps1, which loads the routing functions from the script's AST and checks the pinned hash, the 32 headings, mapper routing to dimension 3, and its negative cases. The PowerShell test workflow now also runs when the rulebook changes. Treat HybridWebView's deferred DI factory as an existing exception to keep, and note that a factory defers construction but still roots the handler. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Toolbar calls RemapForControls() from its own handler setter. Mapper customization is a startup-only operation. Built-in handlers are replaced with AddHandler regardless of registration order, not RemoveAll followed by TryAddHandler, and AddMauiControlsHandlers() does not restore them. Hot Reload default-handler replacement is scoped to the RegisterHandlers collection and reinstalled after removal. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
<!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `cdeafb72937dc746d00866464afe6553904c7d9f` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 7/10 | ↑ Two review rounds addressed: most-specific interface resolution, plus Hot Reload replacement of attribute and default handlers (scoped per app, reinstalled after removal). Each fix has tests that fail without it.<br>↑ Rebased onto the reviewed lower layers. Core 1,279 tests pass under dotnet test and xunit.console, and Controls 7,532 pass. Controls compiles for Android, iOS and MacCatalyst.<br>↑ The new Android compatibility-renderer default activation device test passes 3/3 on an emulator.<br>↓ CI and the full device suites on this head are not yet assessed.<br>↓ Windows paths are compile-only; no Windows device coverage is added. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it 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 --> Follow-up to #28357 targeting **main / .NET 12**. Rebased onto the trimmable-styles merge (#33561), `04d36966ed9d334c056872d83741e973d61f6c55`. #### Stack This PR is **layer 4 of 5** in a stack split from the original single PR for easier review. It is based on #40728, and its own diff covers only the attribute-based resolution: 1. #40721: context-aware handler activation and Hot Reload type matching. 2. #40725: mapper infrastructure that preserves app customizations, the `*ForControls` remap helpers and sealed framework mappings. 3. #40728: lazy Controls mapper remapping on first handler attachment. 4. **This PR**: `[ElementHandler]` attributes on Controls types, removal of the eager default DI registrations, resolution precedence and caches, Hot Reload cache invalidation, Material3 and Apple Shell attribute selection, Windows `PreventGestureBubbling` overrides and the constructor-argument diagnostic. 5. #40715: Copilot guidance for working with handlers and mappers. The sections below describe the combined feature; the activation, mapper and lazy-remap sections are reviewed in layers 1–3. The combined tree is unchanged from the reviewed `5db8263312bf8ea352e8f5a40b04e148c235f4cc` except for the follow-up below. Built-in Controls primarily declare `[ElementHandler]` instead of being rooted by an eager default DI registration table. Controls-specific mapper changes run lazily when handlers attach, while preserving recorded application customizations. Open review items are listed below; this description is not a merge-readiness approval. #### Attribute-based handler resolution `ElementHandlerAttribute` remains internal. The concrete handler type is statically referenced for trimming/AOT. Although the attribute has `Inherited = false`, the factory explicitly walks the base-type hierarchy for fallback. Nested control-specific attributes preserve conditional Android Material3 selection and Windows CollectionView handler selection without unconditionally referencing both alternatives on the active path. `GetHandler(Type)` and `GetHandlerType(Type)` share the resolution order: 1. Exact DI registration. 2. Attribute declared directly on the requested type. 3. The more specific of the nearest registered base class and the nearest inherited attribute. An inherited attribute ranks like the built-in registration its declaring class used to have; a registration on that class or a subclass wins. 4. The most specific registered interface. With Controls defaults on, the `IContentButton`/`IContentView` defaults compete here as interface registrations. 5. Content interface fallbacks: `IContentButton` → `ContentButtonHandler`, then `IContentView` → `ContentViewHandler`. A conditional attribute can declare no handler, for example Apple `ShellItem` when `UseiOSShellHandler` is off; resolution then continues as if it were absent. An exact `AddHandler` still overrides defaults. A registration for `Button` applies to an unannotated `FancyButton : Button`, but registering `IButton` or `View` does not divert it from `ButtonHandler`. Factory registrations remain authoritative even when `GetHandlerType` cannot report an `ImplementationType` and therefore returns `null`. Controls enables an `ElementHandlerDefaultsEnabled` policy per app's handler collection: `TryAddHandler` does not replace a directly declared default or the `IContentButton`/`IContentView` defaults, but still registers custom derived types that only inherit an attribute fallback. Apps without Controls defaults retain normal `TryAddHandler` behavior; `AddHandler` always remains an override. `UseMauiApp` enables the policy before registration callbacks execute regardless of builder-chain order. `AddMauiControlsHandlers` remains a non-obsolete compatibility no-op returning the original collection, without enabling defaults or eagerly remapping controls. #### Cache ownership and invalidation Only attribute and assignable-registration lookups are cached. The complete resolution result and constructor-activation strategy are **not** cached; current registrations and delegates are consulted on every request, and transient requests create fresh handlers. Each factory owns its resolution caches and builds its assignable index from current descriptors, including raw DI registrations. Built-in collection mutations (`Add`, `Insert`, indexer replacement, `Remove`, `RemoveAt`, `Clear`) advance a version. Hot Reload metadata updates, cache clearing, replaced-view callbacks and reset advance a checked generation before views are recreated. Hot Reload registration replacement also changes the collection version. A new cache generation replaces the old dictionaries, preventing concurrent old-generation readers from repopulating new state. Custom collections without mutation tracking do not retain resolution caches. Descriptor lookup stays consistent with indexer/list changes; removing the last registration restores the preceding descriptor for that service type. Cache lookup supports concurrent readers, but collection mutation retains the standard `IServiceCollection` contract and must not run concurrently with resolution. #### Context-aware activation without an activation cache `ElementExtensions.ToHandler` delegates reflection-based construction to the factory. A public parameterless constructor is preferred when present; otherwise `ActivatorUtilities.CreateInstance` resolves dependencies from the current context (including its Android context). Value-type handlers keep default construction. The constructor-presence check avoids using `MissingMethodException` as ordinary control flow, including first activation, without additional cache ownership/invalidation complexity. Direct public `GetHandler` callers retain parameterless-constructor behavior. Custom factories retain their existing exception-based injection fallback. Dependency failures propagate without retrying the entire injection. Factory activation still uses the current service provider/`IMauiContext`, and activated factory types participate in Hot Reload replacement. Historical matched **.NET 11** managed Release microbenchmarks measured warm injected activation at roughly 9 µs with exception-first construction versus 0.10–0.16 µs when missing-constructor exceptions were avoided. Constructor checks were comparable to a factory-owned activation cache; shared-host noise prevents claiming a small difference between those alternatives. These are **not .NET 12 measurements, Android startup claims, or APK-size results**. #### Lazy mapper remapping and main integration Controls `Element.SetHandler` invokes the remap hook before attaching any handler, including compatibility renderers. `ElementHandler.SetVirtualView` also invokes it for direct attachment outside Controls. Each remappable type calls its base hook and owns a blocking one-time initialization action; unrelated controls do not share a global initialization lock. Built-in mapper declarations seal their initial framework mappings. Controls property/command remaps update those mappings underneath recorded app customizations, preserving direct indexer overrides and `AppendToMapping`, `PrependToMapping`, `ModifyMapping`, and `ReplaceMapping` in registration order, including keys that are absent until a lazy remap and keys inherited from chained mappers. See `docs/design/HandlerResolution.md` for the ordering rules. Command-property dependency setup remains in control initialization, independent of handler attachment. The main rebase preserves newer upstream functionality: - `ContentButton` has its own handler attribute, `IContentButton` fallback, sealed mapper and lazy Android ripple remapping. - Switch OnColor remapping uses the lazy hook and customization-preserving prepend behavior on Apple platforms. - Android toolbar drawer-toggle remapping and the current Android/Windows common-mapping scope are retained. - RoundRectangle retains `IShapeWithStroke`; Shell retains the reentrant-navigation unsubscribe fix; handler instrumentation is preserved. - Android ListView/TableView/Frame compatibility attributes retain context-accepting activation through the factory's current-context injection path. - HybridWebView remains a deferred factory registration. Cell attributes retain their platform scopes, and Windows CollectionView feature-switch selection remains conditional. - Controls navigation-transition hooks are installed independently of the removed eager remapping helper. Obsolete eager registration/remapping helpers and Android-context-specific handler interfaces/attributes are removed. Detailed resolution and activation contracts are documented in `docs/design/HandlerResolution.md`. #### Updated Android APK measurements (.NET 12) **Trimmable styles + handlers reduce the plain template's signed NativeAOT APK by 756 KiB (4.64%) compared with neither optimization.** Since styles are already merged into main, this PR's incremental saving over styles alone is **712 KiB**. The 4.64% figure is the combined effect, not a handlers-only measurement. | Framework state | NativeAOT APK (bytes) | Release/CoreCLR APK (bytes) | | --- | ---: | ---: | | Neither styles nor handlers | 16,686,161 | 18,591,480 | | Trimmable styles only | 16,641,105 | 18,591,480 | | Trimmable styles + handlers | 15,912,017 | 18,398,968 | Styles alone save 44 KiB with NativeAOT. Ordinary Release/CoreCLR saves **188 KiB (1.04%)** with handlers; styles alone do not change that APK's size under its default settings. Measured the same unmodified `dotnet new maui -n Template --framework net12.0` source, **without `--sample-content`**, as signed ARM64 APKs. Framework revisions were `f38825f543a18fdcf5ac672b73835e50edd159f6` (neither), `04d36966ed9d334c056872d83741e973d61f6c55` (styles), and `9d2e9cf9b649b647777ec885cd31d1e303e3d49e` (both). The matched local builds use SDK `12.0.100-alpha.1.26523.103`, Android workload `37.99.0-preview.1.358`, and the same MAUI package version `12.0.0-pr29952.local`, with separate feeds/caches. Non-MAUI dependencies, runtime native libraries, signing key, app source and relevant build settings were matched and package hashes checked. NativeAOT uses full trimming and default trimmable styles; ordinary Release uses CoreCLR, partial trimming and default composite R2R. Both retain the SDK's default trimmable typemap and shipped/default profile policy: **no app-trained or custom MIBC**. These are APK file-size measurements, **not startup/JIT/runtime measurements**. No handlers-only arm was measured; the incremental handler saving includes its interaction with merged styles. Local artifact build commands (all **passed**): `bash artifacts/apk-styles-handlers-20261126/build-app.sh baseline aot`, `bash artifacts/apk-styles-handlers-20261126/build-app.sh none aot`, `bash artifacts/apk-styles-handlers-20261126/build-app.sh both aot`, and the same three commands with `release` instead of `aot`. The historical directory name `none` contains the styles-only revision; provenance is checked against `source.sha`, not inferred from directory labels. `python3 artifacts/apk-styles-handlers-20261126/measure.py` — **passed**; verifies all six APKs and records exact source/settings/package/profile identities in `results.json` alongside retained commands, logs and binlogs. These scripts and outputs are local investigation artifacts, not files added by this PR. #### Local validation after the styles rebase (9d2e9cf) The latest English-locale `net12.0` runs passed: - `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj -c Release -p:MauiPlatforms= -m:1 -v:q` — **1,198 passed**. - `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Release -p:MauiPlatforms= -m:1 -v:q` — **7,522 passed, 30 skipped**. - `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -c Release -p:MauiPlatforms= -m:1 -v:q` — **910 passed, 71 skipped**. The previously reported comma-decimal failures were independently reproduced on clean main and pass with the English locale; they are not this PR's regressions. Existing coverage includes collection mutation/raw registrations, custom unversioned collections, metadata and handler replacement, context/app isolation, dependency errors without retry, constructor preference/value types, first-use exception elimination, recorded mapper customization and ContentButton activation/type lookup. Local Android framework packaging and the six trimmed/NativeAOT template builds above passed. This does **not** establish device/UI behavior or iOS/MacCatalyst/Windows validation for this head; CI attribution and remaining review findings are still being assessed. #### Review follow-up in 714715d - **Handler precedence:** An inherited attribute ranks like the built-in registration its declaring class used to have. The most specific concrete candidate wins, and registered concrete types outrank interfaces. With Controls defaults on, `IContentButton`/`IContentView` defaults compete as interface registrations, and `TryAddHandler` no longer replaces them. - **Mapper customizations:** Lazy Controls remaps now compose underneath app customizations, as if they had run at startup. This covers post-seal assignments to absent keys, child customizations of parent keys that only appear in a later lazy remap, and delegates read before a remap. App-created mapper chains keep capture-at-customization semantics, and wrapping a mapping read from a mapper no longer recurses. - **Apple Shell:** `UseiOSShellHandler` again selects `ShellHandler` or `ShellRenderer`, along with the item, section and content handlers. Conditional attributes may declare no handler, so inactive handlers remain trimmable. - **CI fixes:** Hot Reload handler replacement matches by type name; xunit.console loads the test assembly twice. The Material3 Picker expectation is corrected, there is a blocking `OneTimeInitializationAction` test, and the constructor-argument diagnostic is clearer. Validation: Core unit tests passed 1,223/1,223 under `dotnet test` and xunit.console with `DOTNET_MODIFIABLE_ASSEMBLIES=debug`. Controls unit tests passed 7,530, with 30 skipped. `Controls.Core` compiles for `net12.0-ios27.1` and `net12.0-maccatalyst27.0`. The new Shell resolution device tests passed 2/2 on MacCatalyst via `.github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform maccatalyst -TestFilter "Category=Shell" -IncludeClasses "Microsoft.Maui.DeviceTests.ShellHandlerResolutionTests"`. Android and iOS device runs and CI are not yet assessed on this head, and the APK measurements above predate it. Follow-up in 5db8263: lazy RadioButton (Android) and TabbedPage remaps keep a `PlatformViewFactory` the app sets during startup. Resolution fetches its cache once per request, and the typed `*ForControls` mapper helpers check view and handler types before casting. Follow-up when splitting the stack: - Restores the iOS/MacCatalyst `UpdateCollectionViewAccessibilityTraits` refresh on semantics changes. A rebase in 7fba985 had accidentally dropped it. - `VisualElementMapperTests` trigger the lazy remap before reading global mapper keys. They previously passed only when another test had attached a handler first. - `HandlerResolution.md` gains the lower layers' more precise activation and remapping text. Validation on `c1de79de46`: - Core unit tests: 1,225 passed under `dotnet test` and xunit.console. - Controls unit tests: 7,530 passed, 30 skipped. - The three mapper key-order tests pass when run on their own. - `Controls.Core` compiles for `net12.0-android37.0`, `net12.0-ios27.1` and `net12.0-maccatalyst27.0`. Review follow-up (rebased; now in cdeafb7): - **Interface resolution:** resolution now picks the most specific matching interface before reporting an ambiguity. A concrete `IContentButton` with `IButton` and `IContentView` registered resolves to `ContentButtonHandler`, or to a registered `IContentButton` handler. Unrelated registrations remain ambiguous. - **Hot Reload:** pending handler replacements also apply to handlers resolved from `[ElementHandler]` or the content interface defaults. These have no collection descriptor, so the replacement is registered for the requested view type the next time it is resolved. - **Lower layers:** this PR was rebased onto #40728. That carries the lower layers' review fixes: injected handlers are never retained as singletons, the mapper fixes, and Label's public appends are back at type initialization. HandlerResolution.md now has a combined "Behavior changes" section with migration guidance. Second review round: - **Hot Reload:** replacements of attribute and default handlers apply only to the collection passed to `RegisterHandlers`. A newly registered collection receives replacements that were already applied to the previous one, and a replacement whose registration was removed is installed again. - **Registration order:** HandlerResolution.md documents the changes. `AddHandler` before `UseMauiApp()` now wins, `AddMauiControlsHandlers()` no longer restores a replaced handler, and `RemoveAll` followed by `TryAddHandler` no longer replaces an attributed default (use `AddHandler`). - **Android device test:** `CompatibilityRendererDefaultActivationTests` covers default activation of the `ListView`, `TableView` and `Frame` renderers with the current Android `Context`. Validation on `cdeafb7293`: - Core unit tests: 1,279 passed under `dotnet test` and xunit.console. - Controls unit tests: 7,532 passed, 30 skipped. - `Controls.Core` compiles for Android, iOS and MacCatalyst. - The Android device test above passed 3/3. Earlier validation on `a0f29fdbde`: - Core unit tests: 1,271 passed under `dotnet test` and xunit.console. - Controls unit tests: 7,531 passed, 30 skipped. - `Controls.Core` compiles for `net12.0-android37.0`, `net12.0-ios27.1` and `net12.0-maccatalyst27.0`. #### Behavior changes - **`AddMauiControlsHandlers()`:** Remains a compatibility no-op. Calling it after registering a custom handler, for example `AddHandler(typeof(Button), typeof(CustomButtonHandler))`, no longer restores `ButtonHandler`. Remove the custom registration instead. - **Custom `IMauiHandlersFactory` implementations:** Not supported. Built-in defaults are resolved from attributes by the built-in factory, not exposed as descriptors in `IMauiHandlersCollection`, so a replacement factory can no longer resolve Controls views. A follow-up will discourage and eventually remove this extension point. `IMauiContext.Handlers` exposes the interface, so this needs a replacement design rather than just `[Obsolete]`. - **Lazy remaps:** Controls mapper remaps run on each control type's first attachment instead of at `UseMauiApp`. App customizations made during startup are preserved as described above. Label keeps its pre-PR timing: its remaps already ran lazily from its static constructor. Windows CollectionView, ListView and TableView device coverage is left to the Windows controls maintainers. ### 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. --> Supports the trimmable handler work started in #28357. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
6c21f80 to
7bc422a
Compare


Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
9fc89e163e09ad84e46d29176e995dc810548920cdeafb7): the source,docs/design/HandlerResolution.mdincluding its new Behavior changes section, and the resolved review threads.↑ The committed Pester suite
Review-Expert.Tests.ps1passes 13/13 locally with Pester 5.9.0. It checks the pinned hash, the 32 headings, mapper routing to dimension 3 with negative cases, and C# routing to dimensions 12 and 18. Its positive cases fail when the mapper rules are removed.↓ The routing change has not been exercised in a live
/reviewrun, and I have not inspected the PowerShell Script Tests CI result for this head.↓ No automated validation exists for instruction or agent files. The skill-validation workflow covers only
.github/skills/**, which this PR does not change.↓ The guidance follows the stack's design, so it must be revisited if a lower layer changes before merge.
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 reviewFor .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 is the top layer of the trimmable-handlers stack:
[ElementHandler]resolutionThe base is the #29952 branch,
dev/simonrozsival/net10.0-use-element-handler-attributes. Merge this PR after #29952 and the layers below it. It changes only agent guidance, expert-review routing and its tests, not product code.It records the stack's handler and mapper practices so future agents follow them:
.github/instructions/handler-registration.instructions.md, path-scoped to Controls*.Mapper.cspartials, Core/Controls hosting,Handlers/Element,PropertyMapper*/CommandMapper*,ElementExtensions, Hot Reload, handler-resolution and mapper tests, andHandlerResolution.md. It covers:[ElementHandler]attribute on the control class (platform-scoped), not with DI.AddMauiControlsHandlers()is a no-op. DI is for app/library overrides and interfaces. HybridWebView's existingSetupDefaultsfactory is an exception to keep, not a pattern to copy: a factory delegate only defers construction, so the handler stays rooted.ToHandler()injects constructor arguments; a handler that needs them should be registered with anAddHandlerfactory. The factory's provider resolves the currentIMauiContextonly on context-taking paths such asToHandler(), not on publicGetHandler(Type). There is no activation cache, and customIMauiHandlersFactoryimplementations are unsupported.ElementHandlerAttributesubclass that checks a[FeatureSwitchDefinition]switch (Material3, Windows CollectionView, Apple Shell).GetHandlerType()may returnnull.GetHandler/GetHandlerTypeconsistency, interface ambiguity, Hot Reload replacement of attribute handlers, non-singleton injected handlers andTryAddHandlersemantics.AddHandler; it wins regardless of registration order.HandlerResolution.mdrather than duplicating it, and asks for observable changes to be recorded in that doc's Behavior changes section.Toolbar, which is not an element, triggers its remap from its own handler setter.*ForControlshelpers, not the public customization APIs. Label's AndroidIsTextSelectableand AppleFlowDirectionpublic appends are the documented exception; they run fromstatic Label(), not the remap.InstallPlatformViewFactory()with??=, andDependsOnstays in type initialization..WithFrameworkMappingsSealed().SwitchHandler.MapperandTextButtonMapper/ImageButtonMapperremain unsealed exceptions.PropertyMapper.GetPropertyDirect.DisableParallelizationand restore it.new VisualElement().RemapForControls()).Typeidentity across assembly loads.handler-patterns.instructions.md: adds bullets on sealing (with the unsealed exceptions) and the remap helpers, plus a short "Registering Built-in Handlers" section that links to the new file.maui-expert-reviewer.md: replaces the outdated "useModifyMappingfor Controls-layer overrides" check.??=,DependsOnand test-order independence.AddMauiControlsHandlers()no-op..csfile, both in the rulebook's Conditional Dimensions table and inReview-Expert.ps1. Self-reviews that pick dimensions from the rulebook, such as try-fix Step 6, therefore also reach the[ElementHandler]checks.*.Mapper.cspartials, Core mapper infrastructure (PropertyMapper*,CommandMapper*,MappingCustomizationSequence.cs) and*Mapper*Tests.csto dimension 3, so mapper-only changes get the remap and test-order checks..github/scripts/Review-Expert.ps1: mirrors those three routing rules inGet-ExpertExpectedDimensionsand updates the pinned routing SHA-256. This changes only routing data; it adds no tokens, checkouts or PR-code execution..github/scripts/Review-Expert.Tests.ps1: Pester regression tests for the routing, run by the existingpowershell-script-tests.ymlgate. That workflow now also triggers on.github/agents/maui-expert-reviewer.md, so a rulebook routing edit without a matching hash update fails CI.copilot-instructions.md: adds a short "Handlers and Mappers" pointer, because a focusedapplyTocannot match control class files (Label.cs,Button.cs, ...).README-AI.md: indexes the handler instruction files.No skills changed:
code-reviewdelegates handler checks tomaui-expert-reviewer, and no other skill describes handler registration.Validation: No automated tests exist for instruction or agent markdown, and
skill-validation.ymlruns only for.github/skills/**.pwsh -c 'Import-Module Pester -RequiredVersion 5.9.0; Invoke-Pester .github/scripts/Review-Expert.Tests.ps1': passed, 13/13.Review-Expert.ps1, the same run failed 6 of 13 tests, so the suite catches the original gap.git diff --checkis clean.Issues Fixed
Follow-up to #29952; no separate issue.