Skip to content

[trimming] Agent guidance for trimmable handlers and lazy mapper remaps - #40715

Merged
kubaflo merged 6 commits into
mainfrom
simonrozsival-handler-guidance-instructions
Nov 30, 2026
Merged

kubaflo merged 6 commits into
mainfrom
simonrozsival-handler-guidance-instructions

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 9fc89e163e09ad84e46d29176e995dc810548920

Dimension Assessment Rationale
Change confidence 8.5/10 ↑ Every rule was rechecked against the final restacked #29952 head (cdeafb7): the source, docs/design/HandlerResolution.md including its new Behavior changes section, and the resolved review threads.
↑ The committed Pester suite Review-Expert.Tests.ps1 passes 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 /review run, 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

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

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 is the top layer of the trimmable-handlers stack:

  1. [trimming] Context-aware handler activation #40721: context-aware handler activation
  2. [trimming] Customization-preserving mapper infrastructure #40725: customization-preserving mapper infrastructure
  3. [trimming] Remap Controls mappers lazily on first handler attachment #40728: lazy Controls mapper remaps
  4. [trimming] Trimmable element handlers #29952: trimmable [ElementHandler] resolution
  5. This PR: agent guidance

The 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:

  • New .github/instructions/handler-registration.instructions.md, path-scoped to Controls *.Mapper.cs partials, Core/Controls hosting, Handlers/Element, PropertyMapper*/CommandMapper*, ElementExtensions, Hot Reload, handler-resolution and mapper tests, and HandlerResolution.md. It covers:
    • Built-in defaults: built-in controls declare their default handler with the internal [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 existing SetupDefaults factory is an exception to keep, not a pattern to copy: a factory delegate only defers construction, so the handler stays rooted.
    • Construction: attribute-resolved handlers need a public parameterless constructor. Only ToHandler() injects constructor arguments; a handler that needs them should be registered with an AddHandler factory. The factory's provider resolves the current IMauiContext only on context-taking paths such as ToHandler(), not on public GetHandler(Type). There is no activation cache, and custom IMauiHandlersFactory implementations are unsupported.
    • Feature switches: handler selection that depends on a feature switch uses a nested ElementHandlerAttribute subclass that checks a [FeatureSwitchDefinition] switch (Material3, Windows CollectionView, Apple Shell). GetHandlerType() may return null.
    • Resolution:
      • It covers precedence, GetHandler/GetHandlerType consistency, interface ambiguity, Hot Reload replacement of attribute handlers, non-singleton injected handlers and TryAddHandler semantics.
      • To replace a built-in handler, use AddHandler; it wins regardless of registration order.
      • Mapper customization is documented as startup-only.
      • It links to HandlerResolution.md rather than duplicating it, and asks for observable changes to be recorded in that doc's Behavior changes section.
    • Lazy remaps: remaps run on first attach, base type first. Toolbar, which is not an element, triggers its remap from its own handler setter.
      • Remaps use the *ForControls helpers, not the public customization APIs. Label's Android IsTextSelectable and Apple FlowDirection public appends are the documented exception; they run from static Label(), not the remap.
      • Static factories are installed through InstallPlatformViewFactory() with ??=, and DependsOn stays in type initialization.
      • Remapped mappers call .WithFrameworkMappingsSealed(). SwitchHandler.Mapper and TextButtonMapper/ImageButtonMapper remain unsealed exceptions.
      • A framework remap of an inherited key builds on the parent's mapping as it is at first attachment.
      • For inherited keys, sealed mappers return child-bound mappings and unsealed ones return the chained mapping. Internals use PropertyMapper.GetPropertyDirect.
    • Testing:
      • Platform attribute branches need device tests. Tests that toggle a switch use DisableParallelization and restore it.
      • Mapper-preservation tests cover customizations both before and after the remap.
      • Tests that read global mappers must trigger the lazy remap first (new VisualElement().RemapForControls()).
      • Tests must not assume Type identity 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 "use ModifyMapping for Controls-layer overrides" check.
    • Dimension 3 gets checks for remaps, sealing, unsealed exceptions, child-key remaps, ??=, DependsOn and test-order independence.
    • Dimension 12 gets checks for resolution consistency, unsupported custom factories and the AddMauiControlsHandlers() no-op.
    • Dimension 18 gets checks for attributes, feature-switch selection and device coverage. The existing HybridWebView factory is exempt from the built-in-handler check.
    • Dimensions 12 and 18 activate for every .cs file, both in the rulebook's Conditional Dimensions table and in Review-Expert.ps1. Self-reviews that pick dimensions from the rulebook, such as try-fix Step 6, therefore also reach the [ElementHandler] checks.
    • Dimension Routing now routes Controls *.Mapper.cs partials, Core mapper infrastructure (PropertyMapper*, CommandMapper*, MappingCustomizationSequence.cs) and *Mapper*Tests.cs to dimension 3, so mapper-only changes get the remap and test-order checks.
  • .github/scripts/Review-Expert.ps1: mirrors those three routing rules in Get-ExpertExpectedDimensions and updates the pinned routing SHA-256. This changes only routing data; it adds no tokens, checkouts or PR-code execution.
  • New .github/scripts/Review-Expert.Tests.ps1: Pester regression tests for the routing, run by the existing powershell-script-tests.yml gate. 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 focused applyTo cannot match control class files (Label.cs, Button.cs, ...).
  • README-AI.md: indexes the handler instruction files.

No skills changed: code-review delegates handler checks to maui-expert-reviewer, and no other skill describes handler registration.

Validation: No automated tests exist for instruction or agent markdown, and skill-validation.yml runs only for .github/skills/**.

  • pwsh -c 'Import-Module Pester -RequiredVersion 5.9.0; Invoke-Pester .github/scripts/Review-Expert.Tests.ps1': passed, 13/13.
  • With the three mapper routing rules temporarily removed from Review-Expert.ps1, the same run failed 6 of 13 tests, so the suite catches the original gap.

git diff --check is clean.

Issues Fixed

Follow-up to #29952; no separate issue.

@azure-pipelines

Copy link
Copy Markdown
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.

@kubaflo

This comment has been minimized.

@kubaflo

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Expert Review — No findings

Reviewed commit 077990f.

@github-actions

This comment has been minimized.

@simonrozsival simonrozsival changed the title [net12.0] Agent guidance for trimmable handlers and lazy mapper remaps [net12.0] Agent guidance for trimmable handlers and lazy mapper remaps (handlers stack 5/5) Nov 27, 2026
@simonrozsival
simonrozsival removed this pull request from stack #40716 November 27, 2026 14:49
@simonrozsival simonrozsival changed the title [net12.0] Agent guidance for trimmable handlers and lazy mapper remaps (handlers stack 5/5) [trimming] Agent guidance for trimmable handlers and lazy mapper remaps Nov 27, 2026
@simonrozsival
simonrozsival marked this pull request as ready for review November 27, 2026 14:54
Copilot AI balanced review requested due to automatic review settings November 27, 2026 14:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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

Comment thread .github/agents/maui-expert-reviewer.md Resolved
@kubaflo

This comment has been minimized.

@kubaflo

This comment has been minimized.

Copilot AI balanced review requested due to automatic review settings November 29, 2026 23:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

There are no active review issues requiring resolution.

1 open issue

Review effort: Balanced

@github-actions

This comment has been minimized.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Expert Review — 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@kubaflo

This comment has been minimized.

@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Selected Tests

@kubaflo — AI-selected UI tests and device tests (GPT-6.2 Sol + MAI Code 2) for commit 6fce69c8.

Result NOTHING TO RUN Platforms none Tests 0 UI, 0 device Commit 6fce69c8


🧪 Test selection — click to expand
Suite Result Selected Build
UI tests ➖ nothing to run none —
Device tests ➖ nothing to run none —
🧪 UI tests — nothing to run

ℹ️ The AI found no changes relevant to UI tests, so no maui-pr-uitests run was queued.

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.

🧪 Running — nothing

No UI tests run for this PR.

🧪 Device tests — nothing to run

ℹ️ The AI found no changes relevant to device tests, so no maui-pr-devicetests run was queued.

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.

🧪 Running — nothing

No device tests run for this PR.

⏭️ Skipped — what neither suite runs

UI tests — 77 categories, 4 platforms

Platforms not run: Android, iOS, MacCatalyst, Windows

Each skipped platform and category is listed as a maui-pr-uitests (skipped) … status on this commit. Use /azp run maui-pr-uitests for the full suite.

Device tests — 105 categories, 4 platforms

Platforms not run: Android, iOS, MacCatalyst, Windows

Each skipped platform and project is listed as a maui-pr-devicetests (skipped) … status on this commit. Use /azp run maui-pr-devicetests for the full suite.

🤖 Why these tests — AI rationale (GPT-6.2 Sol + MAI Code 2)

UI tests

Each model chose independently; every test that runs was selected by at least one of them.

Platform GPT-6.2 Sol MAI Code 2
Android — —
iOS — —
MacCatalyst — —
Windows — —

GPT-6.2 Sol — No MAUI UI tests selected because the PR changes only reviewer guidance and PowerShell reviewer checks.

  • The .github Markdown changes document handler registration and mapper remaps; they do not change MAUI runtime code.
  • Review-Expert scripts and their PowerShell workflow do not build or run the UI test apps.

MAI Code 2 — Agent-guidance and PowerShell review-routing-only changes; no UI or device tests can be affected.

  • All changed files are under .github/ and update AI guidance, expert-review routing, or PowerShell tests/workflows.
  • No product, UI test host, shared test infrastructure, device test, SDK, or build behavior is changed.
  • UI tests are deliberately omitted because these files cannot alter app runtime behavior.
  • Device tests are deliberately omitted because these files cannot alter device-tested products or build output.

Device tests

Each model chose independently; every test that runs was selected by at least one of them.

Platform GPT-6.2 Sol MAI Code 2
Android — —
iOS — —
MacCatalyst — —
Windows — —

GPT-6.2 Sol — No MAUI device tests selected because the PR does not change product code or device test infrastructure.

  • Handler and mapper guidance does not change the implementations.
  • Reviewer routing and its script tests are confined to the separate PowerShell workflow, not the Helix device test pipeline.

MAI Code 2 — Agent-guidance and review-script-only changes; no device tests are affected.

  • Changes are confined to .github/ instruction, routing, test, and workflow files.
  • No MAUI runtime, handler, graphics, Essentials, BlazorWebView, or device test code changed.
  • Device tests are therefore omitted.

Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Expert Review — 2 findings

Reviewed commit 6fce69c.

Previously reported findings were not duplicated.

@kubaflo
kubaflo force-pushed the simonrozsival-handler-guidance-instructions branch from 6fce69c to 6c21f80 Compare November 30, 2026 11:29
Copilot AI balanced review requested due to automatic review settings November 30, 2026 11:29
Base automatically changed from dev/simonrozsival/net10.0-use-element-handler-attributes to main November 30, 2026 11:35
simonrozsival and others added 6 commits November 30, 2026 12:35
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>
kubaflo added a commit that referenced this pull request Nov 30, 2026
<!-- 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>
@kubaflo
kubaflo force-pushed the simonrozsival-handler-guidance-instructions branch from 6c21f80 to 7bc422a Compare November 30, 2026 11:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues remain for the handler-guidance and review-tooling changes.

1 open issue

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 30, 2026 11:35
@kubaflo
kubaflo merged commit 1d05957 into main Nov 30, 2026
5 of 7 checks passed
@kubaflo
kubaflo deleted the simonrozsival-handler-guidance-instructions branch November 30, 2026 11:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues are identified for the tooling and documentation updates supporting .NET MAUI’s trimmable-handler guidance.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

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.

3 participants