Repository navigation
Document and test the edge-triggered contract for native-mutated declared bools (R7) - #940
Conversation
There was a problem hiding this comment.
Pull request overview
This PR clarifies Reactor’s intended contract for “native-mutated declared bool” properties (notably InfoBar.IsOpen): these are edge-triggered (writes occur only on declared value transitions), and callers must wire the native change callback back into state for recoverability. It adds documentation and test coverage to lock that behavior in, without changing runtime behavior.
Changes:
- Added XML documentation on affected element properties (
InfoBar.IsOpen,TeachingTip.IsOpen,SplitView.IsPaneOpen,NavigationView.IsPaneOpen) describing the edge-triggered contract and the required callback wiring. - Added a new “Values the native control mutates on its own” section to the extending-controls guide (template + regenerated guide output).
- Added new selftest fixtures (InfoBar + TeachingTip) and a new headless unit test to pin descriptor wiring assumptions.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
src/Reactor/Core/Element.cs |
Adds XML docs describing the edge-triggered contract and state-sync guidance for self-mutating bool props. |
docs/_pipeline/templates/extending-reactor-controls.md.dt |
Adds the new guide section explaining edge-triggered vs re-asserting behavior and when each is appropriate. |
docs/guide/extending-reactor-controls.md |
Regenerated guide output reflecting the new template section. |
tests/Reactor.AppTests.Host/SelfTest/Fixtures/IsOpenEdgeTriggeredFixtures.cs |
Adds live-control selftests asserting both halves of the edge-triggered contract for InfoBar/TeachingTip. |
tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs |
Registers the new selftest fixtures in both the list and the factory switch. |
tests/Reactor.Tests/InfoBarIsOpenEdgeTriggeredTests.cs |
Adds headless tests that verify InfoBar.IsOpen remains bound via a plain one-way descriptor entry and retains its default. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
📦 Build metricsArtifact sizes for Packages (compressed .nupkg)
Assemblies in Microsoft.UI.Reactor
Assemblies in Microsoft.UI.Reactor.Advanced
Assemblies in Microsoft.UI.Reactor.Devtools
No size change beyond the noise floor. ✅ ✅ smaller / |
🧪 Merged coverageCoverage for
No coverage change beyond the noise floor. ✅ ✅ higher / |
…ared bools R7 reported that InfoBar.IsOpen `can never be shown again` after the user dismisses the bar with its built-in close button. Empirically that is not true: a declared false -> true transition re-opens it. What is missing is a stated rule and a test that pins it. Adds: - XML doc on InfoBarElement.IsOpen, TeachingTipElement.IsOpen, SplitViewElement.IsPaneOpen and NavigationViewElement.IsPaneOpen recording that these are edge-triggered and that the change callback is the sync channel. - A `values the native control mutates on its own` section in the extending-reactor-controls guide template (+ recompiled page). - IsOpenEdgeTriggeredFixtures selftests pinning both halves of the contract. - InfoBarIsOpenEdgeTriggeredTests headless guards on the descriptor wiring. No behaviour change. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 3a974fbd-1bad-4634-860f-3261f28a9ff9
…xture honestly Two findings from the pr-review skill: - alternative-solution (low): the guide told custom-control authors to always keep a self-mutating property on .OneWay, which contradicts Expander.IsExpanded and Popup.IsOpen (both re-assert against the live control). Narrowed the advice and spelled out the two conditions that make re-asserting safe: opt-in authority via Optional<T>, or an element default equal to the control's resting value. - test-coverage (medium): TeachingTipEdgeTriggered had no OnClosed oracle. While adding one I found WinUI raises no Closed event for a Reactor-mounted TeachingTip at all, because it never actually presents (an identically parented raw WinUI.TeachingTip does). A callback count there would assert the absence of that presentation defect rather than the edge contract, so the fixture stays at the IsOpen property level and its doc comment records why. The presentation defect is reported separately. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 3a974fbd-1bad-4634-860f-3261f28a9ff9
The multi-model cross-check flagged that TeachingTipEdgeTriggered unmounted while the tip was still declared open. Harmless today because a Reactor-mounted TeachingTip never actually presents, but it would leave a live overlay for the next fixture in the shared selftest host once that defect is fixed. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 3a974fbd-1bad-4634-860f-3261f28a9ff9
Post-#930 the repo prefers fluent modifiers, so the guide now names .Closed(...) alongside the with-expression form, and names the equivalent hook on the other three props (OnPaneOpenChanged / OnClosed). Co-authored-by: Copilot App <[email protected]> Copilot-Session: 3a974fbd-1bad-4634-860f-3261f28a9ff9
160df5f to
4f1eee8
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (1)
tests/Reactor.Tests/InfoBarIsOpenEdgeTriggeredTests.cs:117
InstanceFieldNames()only inspects fields declared on the concrete entry type. If a future refactor moves_readBack/_dpinto a non-public base type (or an intermediate helper), this test can start passing while the entry can still observe live control state, defeating the intended guard. Consider walking the base-type chain and collectingDeclaredOnlyinstance fields at each level.
private static IReadOnlyCollection<string> InstanceFieldNames(Type type)
=> type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
.Select(f => f.Name)
.ToList();
Copilot flagged this as a low-confidence comment and it was right. BindingFlags.NonPublic does not return private fields declared on BASE types, so InstanceFieldNames only saw the concrete entry. If a refactor moved _readBack into a base class, IsOpenEntry_CannotObserveTheLiveControl would have started passing while the entry could still observe live control state — the guard would have gone quiet exactly when it mattered. Now walks Type.BaseType collecting DeclaredOnly fields at each level. Needed a second UnconditionalSuppressMessage (IL2075) because the trim analyzer cannot annotate Type.BaseType; same test-only pattern as RichTextBlockDescriptorTests. Re-verified the guard still bites: with InfoBarElement.IsOpen flipped to false all 3 facts fail; restored, all 3 pass. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 3a974fbd-1bad-4634-860f-3261f28a9ff9
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (1)
tests/Reactor.Tests/InfoBarIsOpenEdgeTriggeredTests.cs:142
- GetPrivateField() only searches the concrete runtime type. If the descriptor entry implementation later moves a private field (like
_get) into a base type, this helper returns null and the “locates by behaviour” test will start failing for a refactor that doesn’t change the contract. Walking the type hierarchy here would make the guard more resilient (and consistent with InstanceFieldNames()).
[global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "Test-only: reflects a known non-public field on a concrete descriptor entry. JIT-only (this host is never trimmed) and behaviour-neutral.")]
private static object? GetPrivateField(object owner, string name)
=> owner.GetType()
.GetField(name, BindingFlags.Instance | BindingFlags.NonPublic)
?.GetValue(owner);
Second suppressed low-confidence comment from Copilot's review body, and it is right for the same reason the first one was — but pointing the other way. GetPrivateField used a single-level GetField(Instance | NonPublic), which does not walk the hierarchy (and BindingFlags.FlattenHierarchy does not help: it is documented not to apply to private fields). Moving _get into a base type would have made FindIsOpenEntry match nothing and turned the test red for a refactor that changed no contract. A guard that cries wolf on a behaviour-preserving refactor is how guards get weakened, which is the opposite of this PR's point. Now walks Type.BaseType with DeclaredOnly, consistent with InstanceFieldNames. The widening cannot mask a real regression: the entry is still identified by BEHAVIOUR (reads IsOpen, not IsClosable), a miss returns null and the Assert.Single still fails loudly. Adds ReflectionHelpers_FindPrivateFieldsDeclaredOnABaseType so the hierarchy walk cannot be silently reverted. Mutation-checked: reverting GetPrivateField to the single-level form fails exactly that test and nothing else; flipping InfoBarElement.IsOpen to false still fails the 3 contract guards. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 3a974fbd-1bad-4634-860f-3261f28a9ff9
Addressing the suppressed low-confidence review comment (
|
| Mutation | Result |
|---|---|
GetPrivateField reverted to single-level |
only ReflectionHelpers_FindPrivateFieldsDeclaredOnABaseType fails |
InfoBarElement.IsOpen default flipped to false |
the 3 contract guards still fail; the helper test correctly still passes |
Full unit suite green: Failed: 0, Passed: 12528.
…icrosoft#949) A `TeachingTip` whose first render declared `IsOpen: true` never presented. The mount-time write *was* issued — `OneWayPropEntry.Mount` writes unconditionally — and then silently lost. Root cause: Reactor configures a control fully before its parent takes it. On an UNPARENTED `TeachingTip`, WinUI discards a pending open as soon as anything else is written to the control; parented, it is harmless. So the declared open was always thrown away by a later write: DescriptorHandler.Mount prop loop (IsOpen), EnsureSubscribed, ApplySetters V1HandlerAdapter.Mount Content/HeroContent slots, AfterChildrenMount Reconciler.Mount ApplyModifiers (Margin, ...) ...caller adds the control to its parent <-- parenting is LAST Ordering the entry last inside the descriptor is not enough: setters, the content slots and common modifiers all run outside the descriptor's reach. Measurement pinned `PreferredPlacement` as the write that discards it, matching the descriptor bisect in the issue. The fix takes `IsOpen` off the generator's auto-map (`[WrapManual]`) and routes it through a bespoke `.Imperative` entry backed by a new `MountOpenDeferral` helper. A declared `true` is deferred to the control's `Loaded` event — the first moment the tip is parented into a live tree and an open is guaranteed to stick. A declared `false` still writes directly and disarms any pending open, so the app's latest word always wins. Post-mount behaviour is unchanged: updates stay edge-triggered, so a re-render carrying the same declared `true` still does not re-assert against a natively dismissed tip (the contract locked in by microsoft#940). Descriptor unmount hook ----------------------- An arm could otherwise outlive the mount that created it: unmount before `Loaded`, then re-parent, and the tip popped open on behalf of a mount that no longer existed (proven — the new selftest fails without the hook). The engine already dispatched unmount to hand-coded handlers, but `DescriptorHandler` never forwarded it, so descriptors had no teardown seam at all. Adds `ControlDescriptor.OnUnmount` / `.WithUnmount(...)` and the forwarding implementation, and uses it to cancel a pending open. Testing ------- New `IsOpenEdge_TeachingTipMountOpen` selftest, registered in both required places. Every assertion was mutation-checked so none can pass vacuously: A bypass the deferral -> DeclaredOpenOnFirstRenderOpens, PresentedTipRaisesClosedOnTeardown, RisingEdgeBeforeLoadOpensOnLoad B Cancel becomes a no-op -> FallingEdgeBeforeLoadCancelsPendingOpen C mount always arms open -> DeclaredClosedStaysClosed D unmount hook disabled -> UnmountBeforeLoadCancelsPendingOpen `PresentedTipRaisesClosedOnTeardown` is the presentation oracle: WinUI raises `Closed` only for a tip that genuinely presented, so a "set the DP and hope" fix would not satisfy it. Also refreshes the now-stale scope notes on `TeachingTipEdgeTriggered`, which documented the mount path as broken, and adds a shared `CloseAndSettle` teardown guard — these fixtures now really do present overlays, and `WaitFor(() => !tip.IsOpen)` would have pumped the dispatcher zero times because `IsOpen` flips synchronously. Also fixed ---------- The gallery's "TeachingTip (Title Only)" card declared a tip with no `IsOpen` and no trigger, so it could never appear. The issue warns that the obvious one-line `IsOpen = true` fix lands straight on this bug; now that mount-open works it would present once and, being edge-triggered with nothing wired to `OnClosed`, never come back. Switched to the state-driven shape the sibling "Basic TeachingTip" card already uses, and made it actually title-only. 12,933 unit tests pass; the full selftest suite matches the `main` baseline. Co-authored-by: Copilot App <[email protected]> Copilot-Session: ca0dab3f-2cff-4f78-a3b0-cb546975b515
TL;DR
R7 as written is overstated — I could not reproduce it, so this PR ships no behaviour change.
A natively-dismissed
InfoBardoes recover: a declaredfalse → truetransition re-opens it. Whatwas actually missing is a stated rule and a test that pins it. This PR adds both, plus an
audit of a real inconsistency the investigation uncovered.
Rebased onto
mainafter #930 merged. The diff is purely additive — 512 insertions, 0 deletions.No existing assertion, allowlist or guard was touched, weakened, or relaxed.
Symptom as reported
The ask was to treat
InfoBar.IsOpenas a controlled property: when the declared value istrueand the live control has drifted to
false, re-assert it on the next render.Root cause — accurate version
InfoBarElement.IsOpenis a generator-auto-mappedOneWayprop.OneWayPropEntry.Updatediffs old element vs new element, never the live control:
That much is true. But the conclusion drawn from it is not — with declared
false → truethecomparison is unequal, so it does write. I confirmed the code path is unobstructed:
InfoBarElementhas no arm inElement.ShallowEquals's switch (falls to_ => false), soReconciler.Update's shallow-skip arm never fires for it.DescriptorHandler.Updatehas no entry-level skip;props[i].Update(...)always runs.Evidence — I ran this, against a real WinUI
InfoBarThrowaway selftest fixture, since deleted. Stable across 4 runs:
OnClosedcounttrueTruebar.IsOpen = false)trueFalsetrueFalsetrue → falsefalseFalsefalse → truetrueTrueRow E is the recovery R7 says is impossible. Row C — the only non-recovering case — is the
defined behaviour of an edge-triggered value, not a bug.
The rule this PR writes down
Why I did not implement the requested fix
I planned it (a
ReassertingOneWayPropEntry+ a publicControlDescriptor.ReassertingOneWay(...)),then withdrew it.
InfoBarElement.IsOpen,SplitViewElement.IsPaneOpenandNavigationViewElement.IsPaneOpenall default totrue. Live re-assert would make every one ofthem written without a change callback undismissable — the user dismisses, and the next unrelated
setStateanywhere in that component brings it back. That is a worse, more visible regression thanthe reported bug, and it would land on every existing caller.
"It's the React controlled-input contract" is a fair principle, but it does not survive a default of
true.What changed
src/Reactor/Core/Element.csInfoBarElement.IsOpen,TeachingTipElement.IsOpen,SplitViewElement.IsPaneOpen,NavigationViewElement.IsPaneOpen(+InfoBarElement.IsClosable). Doc comments only.docs/_pipeline/templates/extending-reactor-controls.md.dtdocs/guide/extending-reactor-controls.mdmur docs compile --pages extending-reactor-controlstests/Reactor.AppTests.Host/SelfTest/Fixtures/IsOpenEdgeTriggeredFixtures.csInfoBar/TeachingTiptests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.csAllFixturesand theCreate()switch)tests/Reactor.Tests/InfoBarIsOpenEdgeTriggeredTests.csmur --regen-apireportsreactor.api.txt unchangedfor bothskills/reactor.api.txtand itsplugins/reactor/...mirror — no public API surface change.Tests
The two failure modes point in opposite directions, so both halves are pinned:
RisingEdgeReopensfails if the rising-edge write is ever lost — the recovery path.SameDeclaredValueDoesNotReopenfails if the engine is ever changed to re-assert against thelive control — a standing guard against exactly the regression described above.
Proof they are not vacuous — verbatim output
There is no product change here, so the usual "revert the fix, watch the test fail" does not apply.
I mutation-tested instead. All three mutations re-run after the rebase; all reverted afterwards
(
git diff HEAD -- src/is empty).Baseline (unmutated):
# Total failures: 0— 9 InfoBar + 5 TeachingTip assertions pass.MUTATION-1 —
OneWayPropEntry.Updatenever writes:MUTATION-2 —
OneWayPropEntry.Updatealways writes (i.e. the re-assert "fix" R7 asked for):MUTATION-3 —
InfoBarElement.IsOpendefault flipped tofalse:The two mutations fail disjoint assertion sets, which is the point: neither direction of
regression can slip through.
Audit — Reactor has three different rules here, not one
Found while verifying the above. Reported, not fixed.
Expander.IsExpandedOptional<bool>unsetExpanderHandler.cs:50Popup.IsOpenfalseOverlayLifecycle.cs:401InfoBar.IsOpentrueOneWayTeachingTip.IsOpenfalseOneWaySplitView.IsPaneOpentrueOneWayNavigationView.IsPaneOpentrueOneWayContentDialog.IsOpenfalseOverlayLifecycle.cs:48Flyout.IsOpenfalseOverlayLifecycle.cs:215The two re-asserting rows are defensible and the docs now say why:
ExpanderisOptional<bool>soauthority is opt-in, and
Popupdefaults tofalse, which is also where a light-dismissed popuprests — so its re-assert is a no-op in the direction that would fight the user.
Two genuine defects fall out of this table, both left for separate PRs:
ContentDialog.IsOpen/Flyout.IsOpenhave no falling edge. DeclaringIsOpen = falsedoes not close them — the update only handles
n.IsOpen && !o.IsOpen.TeachingTipnever actually presents. DeclaringIsOpen: trueon thefirst render leaves it closed, and even after a rising edge that flips the property, WinUI raises
no
Closedevent on the way back down — while an identically-parented rawWinUI.TeachingTipdoes present and does raiseClosed. This likely affects the gallery'sTeachingTip page. This is also why
TeachingTipEdgeTriggeredhas noOnClosedoracle: a callbackcount there would assert the absence of that presentation defect rather than the edge contract.
The fixture's doc comment records this.
Note for the gallery fix (sibling session)
The gallery's Reset button needs the
OnClosedwiring and something more:setShowClosable(true)when the value is alreadytruenever re-renders at all —RenderContext.MakeStateSetterbails on an equal value. The framework change alone would not havefixed that button.
Validation
Re-run after rebasing onto
main(post-#930):dotnet build Reactor.slnx— 0 errorsdotnet test tests/Reactor.Tests—Failed: 0, Passed: 12527, Skipped: 64, Total: 12591# Total failures: 0dotnet test tests/Reactor.SelfTests— 2 failures, identical to theorigin/mainbaselinemeasured on the same machine by reverting to a clean tree (
BackdropTransparent_Apply+ a fixturetimeout);
BackdropTransparent_Applypasses in isolation, so it is order/timing dependent andpre-existing, not from this branch
mur docs compile --validate-only— validation passed; unrelated drifted snippet churn indocs/guide/architecture-overview.md(regenerated from PR [Bug] Got error message when click expand item in Reactor.TestApp #919's source) was reverted so it isnot in this diff
.github/skills/pr-reviewacross all 8 dimensions on the final commit: 2 findings, both fixed(commits 2 and 3). Multi-model cross-check (GPT-5.4, high reasoning) returned 0 findings and
independently confirmed the core judgement.
One red
Selftestsrun in this PR's history — proven flakeCommit
273864e3initially failedSelftestsonIssue717_PinReleaseDoesNotClobberAuthorMinHeight.That is not one of this PR's fixtures. Four independent pieces of evidence, rather than an assertion:
Selftestswas green on the immediately preceding head4f1eee88.tests/Reactor.Tests/InfoBarIsOpenEdgeTriggeredTests.cs— a headless xUnit file thatReactor.AppTests.Host.csprojdoes not reference, so the selftest host never compiles it.Merge-ordering
No constraint. This PR adds no analyzer rule and changes no behaviour, so it cannot trip the
Release
TreatWarningsAsErrorsgate that #932 introduces.Open question for the reviewer
If you'd rather have the behaviour change anyway, the safe version is not live re-assert — it is
migrating these four props to
Optional<bool>so authority is opt-in, which is a breaking change totheir defaults and deserves its own spec.