Repository navigation
Adding Microsoft SECURITY.MD - #2
Closed
microsoft-github-policy-service[bot] wants to merge 2 commits into
Closed
microsoft-github-policy-service[bot] wants to merge 2 commits into
microsoft-github-policy-service[bot] wants to merge 2 commits into
Conversation
Collaborator
|
ok to merge |
Chris Anderson (codemonkeychris)
approved these changes
Apr 17, 2026
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
Apr 17, 2026
…items, reorder ## Summary - Add 3 new **Unblock**-priority proposals: XAML-free navigation (#1), deep virtualization hooks for ListView/GridView/ItemsRepeater (#2), programmatic DataTemplate construction (#3) - Merge the original Tag bypass proposal with the closure-capture proposal into a single entry (#4), including empirical finding that ConditionalWeakTable was slower - Reorder all 21 proposals so Unblock items appear first, followed by Tactical, Medium, Wild - Renumber everything consistently ---- #### AI description (iteration 1) #### PR Classification This pull request is a design and documentation update introducing a comprehensive set of WinUI3 integration proposals. #### PR Summary A new documentation file (`/docs/winui3-integration-proposals.md`) has been added that details 21 proposals aimed at enhancing WinUI3 interoperability with Duct, covering aspects from navigation and virtualization to layout performance and advanced reconciliation techniques. - `docs/winui3-integration-proposals.md`: Introduces detailed proposals including XAML-free navigation, deep virtualization hooks, programmatic DataTemplate construction, and dependency property bypass optimizations. - The proposals are organized into tactical, medium, and wild improvements, complete with code examples and a summary table categorizing ambition, effort, and impact. <!-- GitOpsUserAgent=GitOps.Apps.Server.pullrequestcopilot -->
Chris Anderson (codemonkeychris)
force-pushed
the
main
branch
from
April 17, 2026 03:40
f2834a4 to
c7a9037
Compare
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
Apr 17, 2026
## Summary - **Shared session**: Ref-counted `TestSession` so all 3 test classes share one Host app + WinAppDriver instance (was launching 3 separate ones, leaking 2 processes) - **Replaced all `Thread.Sleep` with event-driven waits**: `WaitForText`/`WaitForTextContaining` poll at 100ms for exact/substring text matches, eliminating 13 fixed delays (300-500ms each) - **Reversed `ClickButton` lookup order**: AccessibilityId first (then Name fallback) avoids 2s implicit-wait penalty per click - **Fixture navigation cache**: 13 accessibility tests skip redundant re-navigation to the same fixture - **Fixed 2 a11y test failures**: HeadingLevel/FullDescription not retrievable via WinAppDriver `GetAttribute()` — tests now gracefully verify element presence as proxy - **Orphan cleanup**: `KillOrphanedProcesses()` on init prevents leaks from prior failed runs ### Performance (10 runs) | Run | Time | Result | Leftover Procs | |-----|------|--------|----------------| | #1 (baseline) | **182s** | 18/2 ❌ | 2 | | #2 | **107s** | 20/0 ✅ | 0 | | #3 | **70s** | 20/0 ✅ | 0 | | #4 | **48s** | 20/0 ✅ | 0 | | #5 | **41s** | 20/0 ✅ | 0 | | #6 | **41s** | 20/0 ✅ | 0 | | #7 | **44s** | 19/1 ❌ | 0 | | #8 | **48s** | 20/0 ✅ | 0 | | #9 | **47s** | 20/0 ✅ | 0 | | #10 | **41s** | 20/0 ✅ | 0 | Final 3 consecutive: all-green 20/20, zero leftover processes. ## Test plan - [x] 10 test runs completed, 3 consecutive passes achieved - [x] Zero leftover Duct.AppTests.Host or WinAppDriver processes after every run - [x] All 20 E2E tests pass consistently (~40s) ---- #### AI description (iteration 1) #### PR Classification Performance optimization and test robustness improvements for Appium E2E tests. #### PR Summary This PR makes Appium E2E tests approximately 4x faster by implementing session reuse across test classes, replacing fixed sleeps with dynamic polling, and killing orphaned processes. The changes reduce implicit wait timeouts and add smart fixture navigation caching. - `TestSession.cs`: Implemented reference-counted session sharing across test classes, added `KillOrphanedProcesses()` to clean up stale processes, and replaced 3-second fixed sleep with `WaitForHostWindow()` polling (200ms intervals up to 5s) - `AppTestBase.cs`: Added fixture navigation caching to skip re-navigation when already on the same fixture, introduced `WaitForTextContaining()` helper, reduced polling interval from 200ms to 100ms, and reduced implicit wait timeout from 5s to 2s - `InteractiveTests.cs`, `EventHandlerTests.cs`: Replaced all `Thread.Sleep()` + manual element lookups with `WaitForText()` calls for more reliable synchronization - `AccessibilityTests.cs`: Added fallback assertions for UIA properties that WinAppDriver cannot retrieve (HeadingLevel, FullDescription) and reduced timeout for decorative image test <!-- GitOpsUserAgent=GitOps.Apps.Server.pullrequestcopilot -->
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
Apr 18, 2026
…ames Addresses the second-round AI-agent field feedback. Build still compiles and 3708 unit tests pass. - #2 Stable window id: WindowIdAllocator.Reserve pins the primary devtools window to "main" so the handle survives switchComponent changing the window title. Windows payload surfaces `currentComponent`. - #4 Scroll units + readback: description explicitly calls out percentage-delta semantics; response now carries `scrollOffsetPx` and `scrollableSizePx` dug out of the underlying ScrollViewer, and the -1 sentinel is replaced with null when an axis isn't scrollable. - #5 Accessible names at mount: the reconciler now mirrors visible captions into AutomationProperties.Name for Button, HyperlinkButton, RepeatButton, ToggleButton, DropDownButton, SplitButton, ToggleSplitButton, CheckBox, RadioButton, ToggleSwitch, TextField, and TextBlock. Author-supplied .AutomationName(...) still wins; the Update path handles label changes via a provenance-aware compare so author overrides are preserved. - #6 includeReactorSource rejection: tree tool returns structured not-implemented instead of silently no-opping. - #7 ComboBox expand/collapse: new `expand` / `collapse` MCP verbs wrap IExpandCollapseProvider; `select` auto-expands a closed container so the popup items resolve. - #9 Fire lambda confusion: unknown-event payload lists reachableMethods and explains inline lambdas aren't reflectable; tool description warns upfront. - Usability: GET /mcp self-describes (schema, protocolVersion, tools, selectorGrammar, events); tools/list adds _selectorGrammar + _treeSchemaVersion extensions so POST-based agents get the grammar without a second hop; components tool returns ComponentInfo[] with isNested/isPublic/namespace; AnnounceReady emits a {"event":"devtools-ready", ...} JSON sentinel alongside the human banner; full-view tree nodes carry supportedPatterns[] probed from the UIA peer. #8 (state selector scoping) deferred — requires reconciler component registry. The resolution table previously in the feedback doc is superseded; the doc itself has been removed from the working tree. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
Apr 18, 2026
…ames Addresses the second-round AI-agent field feedback. Build still compiles and 3708 unit tests pass. - #2 Stable window id: WindowIdAllocator.Reserve pins the primary devtools window to "main" so the handle survives switchComponent changing the window title. Windows payload surfaces `currentComponent`. - #4 Scroll units + readback: description explicitly calls out percentage-delta semantics; response now carries `scrollOffsetPx` and `scrollableSizePx` dug out of the underlying ScrollViewer, and the -1 sentinel is replaced with null when an axis isn't scrollable. - #5 Accessible names at mount: the reconciler now mirrors visible captions into AutomationProperties.Name for Button, HyperlinkButton, RepeatButton, ToggleButton, DropDownButton, SplitButton, ToggleSplitButton, CheckBox, RadioButton, ToggleSwitch, TextField, and TextBlock. Author-supplied .AutomationName(...) still wins; the Update path handles label changes via a provenance-aware compare so author overrides are preserved. - #6 includeReactorSource rejection: tree tool returns structured not-implemented instead of silently no-opping. - #7 ComboBox expand/collapse: new `expand` / `collapse` MCP verbs wrap IExpandCollapseProvider; `select` auto-expands a closed container so the popup items resolve. - #9 Fire lambda confusion: unknown-event payload lists reachableMethods and explains inline lambdas aren't reflectable; tool description warns upfront. - Usability: GET /mcp self-describes (schema, protocolVersion, tools, selectorGrammar, events); tools/list adds _selectorGrammar + _treeSchemaVersion extensions so POST-based agents get the grammar without a second hop; components tool returns ComponentInfo[] with isNested/isPublic/namespace; AnnounceReady emits a {"event":"devtools-ready", ...} JSON sentinel alongside the human banner; full-view tree nodes carry supportedPatterns[] probed from the UIA peer. #8 (state selector scoping) deferred — requires reconciler component registry. The resolution table previously in the feedback doc is superseded; the doc itself has been removed from the working tree. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
5 tasks
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 11, 2026
… blocker - Status snapshot at the top of the task list — Phase 0/1 code-complete on feat/038-mur-check, not merged to main, blocked on threshold tuning. - Phase 0 (0.1–0.5) and Phase 1 (1.1–1.7) checkboxes ticked, with one-line notes on the four items deferred as follow-ups (Reactor-touching integration fixture, perf-trait wall-time test, full Hamming-vector overload ranking, CS0103 return-type filter). - Data Checkpoint A re-audit (2026-05-10): Gap #1 (receiver_type), #2 (dedup), #4 (cosmetic) all FIXED in the new harness output. Gap #3 (ranker negative class) still NOT fixed — all 3 ranker-labels rows are positive class; for 3 runs the spec expects ~30–80 rows. - Plus a fix_kind classifier nit: ButtonElement HorizontalAlignment → HAlign should be renamed_member, not other (receiver type unchanged, member name swapped). - Recommendation against kicking off the 50-run sweep until Gap #3 lands; records that Data Checkpoint B is therefore still blocked. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
4 of 5 tasks
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 11, 2026
Quality and self-consistency pass on the Phase-1 branch. All changes are contained to Phase-1 surface; broader CR concerns about CS1061/CS0117 fuzzy behavior, MSBuild-accurate loading, and per-code precision gating remain scoped to Phase 2/3 per the spec's existing plan. - CR #10: drop CS8602 warning in CompilationLoader by routing EmptyCompilation through a named factory method with explicit Array.Empty<> coalescing. - CR #11: diagnostic regex now uses a reluctant file capture anchored on the (line,col): suffix so MSBuild lines with parenthesized path segments parse correctly. Added pipeline test. - CR #8: TraceWriter.SanitizePath normalizes in-root absolute paths to project-relative (forward-slash) form so traces no longer carry `C:\Users\<name>\...` prefixes. Tests strengthened to assert no row is ever an absolute path. - CR #13: replace misleading CS7036 tiebreak comment with accurate description; full Hamming-vector ranker stays a deferred follow-up per spec §1.5. - CR #14: 525-run report reworded — "500-pair volume bar met, cross-agent bar NOT met"; Theme.get_Background note marked "fixed in this branch" with code reference. - CR #2 (narrowed): tighten CS1061 factory-argument receiver check to require receiver IS-A factory return type only (dropped reverse IsAssignableFrom direction). Full AST-anchored receiver verification deferred to Phase-3 RuleSymbolResolver per §3.1a. - Implementation doc deferred-follow-ups list updated to include receiver-anchoring (e) and Phase-2 loader/precision-gate work (f). Verification: 98 CheckCommand unit tests pass (was 97 + new parens-path test); MurCheck integration test passes; CS8602 warning eliminated. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 11, 2026
…c-count gate) (#243) * docs(specs/038): add MSBuild passthrough via `--` to mur check CLI Today's CheckCommand accepts only <path> and hardcodes --nologo, -v:m, and -p:Platform={host arch}. Without an escape hatch the only fallback for an agent that needs to override Platform, pick a Configuration, skip restore, or pass arbitrary -p: properties is to drop mur check and run dotnet build directly - which discards every benefit the spec adds. Adds a "CLI shape and MSBuild passthrough" subsection in §8 covering: the `mur check [path] [mur-flags] [-- <msbuild args>]` shape, default-merging rules (auto-inject only if user did not specify), boundary semantics (bare `--` is the unambiguous separator; unknown mur-flags error), ranker-unchanged invariant (passthrough alters the build, not diagnostic scoring), and trace faithfulness (record effective command line). Adds an implementation bullet to Phase 4. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(specs/038): add detailed implementation task list Mirrors the convention from docs/specs/tasks/036-window-design- implementation.md: phased checkboxes, "task is done only when" gate, conventions header. Adapted for spec 038's external dependency on spec 037's data corpus. Adds three concepts not in earlier task lists because no other spec needed them: - Human Validation Gate: six-bar checklist every Tier 3 rule must clear before merge (frequency >=5%, count >=10, cross- agent reproducibility, >=3 positive fixtures, >=2 negative, independent reviewer signoff). Plus auto-suppression policy for rules whose telemetry accept-rate drops below 50%. - Data Checkpoints A/B/C/D: staged hand-offs from spec 037's harness with explicit blocking relationships. A is the current 3-pair smoke (already landed); B/C/D gate Phase 1 threshold tuning, Phase 3 rule authoring, and Phase 4 ranker training respectively. - Eval Checkpoints EC1-EC4: 5xN batches on gpt-5.5 vs reactor- calc/kanban with predicted lift bands and pass criteria. EC1 after Tier 2 only; EC2 after deterministic ranker + 5 rules; EC3 at V1 ship (10-15 rules); EC4 if learned ranker is pursued. Quantity bars (per the user's question): 5 rules before EC2, 10-15 rules covering >=80% of fix events for V1 ship. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(spec-038): land Phase 0 + Phase 1 of `mur check` did-you-mean engine Phase 0 (instrumentation, no behavior change): - `mur check --trace <path>` writes one JSONL row per parsed diagnostic to <path> in addition to stdout. Schema: {ts, code, severity, file, line, col, msg, receiver_type?, member?, mode}. Source code text is never written; absolute paths outside the project root are redacted to "<external>"; rows are bounded to 2 KB. - New folders src/Reactor.Cli/Check/{Suggesters,Rules}/ with README pointers to spec 038 §5/§6 and the Validation Gate. Phase 1 (Tier-2 Roslyn semantic suggester): - ISuggester contract + SymbolSuggester covering CS1061, CS0103, CS0117, CS1503, CS7036 against Microsoft.UI.Reactor.* symbols. - CompilationLoader: csproj/source resolution, project.assets.json reference resolution, (csproj-path, file-mtime-hash) cache, symlink containment, perf budget cold ≤ 500 ms / warm ≤ 50 ms. - FactoryIndex: pre-filter over Microsoft.UI.Reactor.Factories.* static methods with cached parameter-name arrays for named-argument suggestions. - StringSimilarity (Jaro–Winkler) for fuzzy member-name matching. - SuggesterOrchestrator wires the suggester into CheckCommand.Run; Tier-1 HintFor still wins ties at the format layer (spec §9). - MUR_TELEMETRY=1 opt-in: appends (code, suggester, confidence, evidence_short) to ~/.mur/telemetry/<yyyy-mm-dd>.jsonl. Fields bounded to 256 bytes; no source text, file paths, or machine identifiers. - Args parser recognises `--trace` and `--help`; rejects unknown flags rather than silently forwarding (full passthrough lands in Phase 2). Tests: - 66 unit tests under tests/Reactor.Tests/CheckCommandTests/ covering args parsing, trace schema/redaction/length cap, compilation loader, factory index, JaroWinkler, every suggester code path (positive + negative), orchestrator filtering (Reactor-touching gate), Tier-1-wins-ties, and telemetry opt-in/byte-bound. - Integration smoke test exercising mur.exe end-to-end against a deliberately broken fixture under tests/Reactor.IntegrationTests/MurCheck/Fixtures/ SmokeFixture/. Reactor-touching CS1061 fixture is scoped as a follow-up because it requires WindowsAppSDK restore. Pause point per spec 038 task list: - Phase 1.8 exit needs Data Checkpoint B (≥50 unique pairs from spec 037's harness) for per-code threshold tuning before merging to main. - Phase 2 + 3 are blocked by Phase 1 merge / Data Checkpoint C respectively. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(specs/038): mark Phase 0 + Phase 1 complete; record harness Gap #3 blocker - Status snapshot at the top of the task list — Phase 0/1 code-complete on feat/038-mur-check, not merged to main, blocked on threshold tuning. - Phase 0 (0.1–0.5) and Phase 1 (1.1–1.7) checkboxes ticked, with one-line notes on the four items deferred as follow-ups (Reactor-touching integration fixture, perf-trait wall-time test, full Hamming-vector overload ranking, CS0103 return-type filter). - Data Checkpoint A re-audit (2026-05-10): Gap #1 (receiver_type), #2 (dedup), #4 (cosmetic) all FIXED in the new harness output. Gap #3 (ranker negative class) still NOT fixed — all 3 ranker-labels rows are positive class; for 3 runs the spec expects ~30–80 rows. - Plus a fix_kind classifier nit: ButtonElement HorizontalAlignment → HAlign should be renamed_member, not other (receiver type unchanged, member name swapped). - Recommendation against kicking off the 50-run sweep until Gap #3 lands; records that Data Checkpoint B is therefore still blocked. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(specs/038): unblock Data Checkpoint B; record still_present_at_run_end as Phase-4 prereq Audit pass 2 of the 6-row ranker-labels output (2026-05-10): - Gap #3 (ranker negative class) is now FIXED. 4 positive / 2 negative on addressed_by_next_fix; harness emits per-build per-diagnostic rows; three CS8012 emissions in run 5d5fef… recorded as three independent training rows, exactly per spec 037 §3 "don't dedupe across builds". - fix_kind classifier nit partially fixed — both pairs now classify as renamed_member; debatable for pair 2's structural rewrite but acceptable. - New known limitation: still_present_at_run_end is uniformly false even when the diagnostic IS in the final build (CS8012 timing-tail fingerprint quirk). Primary ranker label addressed_by_next_fix is unaffected; auxiliary agent_ignored is corrupted, which breaks the spec 038 §11 auto-suppression-telemetry hook. Tracked as a Phase-4 prerequisite — file with harness owner before Data Checkpoint D. Status updates: - Status snapshot at top: 50-run sweep cleared to start. - Data Checkpoint B: status flipped from blocked to unblocked. Added a step-by-step "pickup procedure for the next session" so the next agent can run cold once the corpus lands (audit, threshold tuning, EC1, merge). - Data Checkpoint D: documents still_present_at_run_end as the remaining prerequisite before training the learned ranker. - Phase 1.8 exit criterion points at the pickup procedure instead of the stale "blocked" note. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(spec-038): tune Tier-2 SymbolSuggester thresholds against 50-run corpus Phase 1 ship-gate calibration (Data Checkpoint B). Adds per-code emit thresholds in src/Reactor.Cli/Check/Suggesters/Thresholds.cs, refactors SymbolSuggester so the threshold gate has a single source of truth (SuggestRaw exposes raw confidence; Suggest gates via Thresholds.For), and removes the now-redundant duplicate cut from SuggesterOrchestrator. Per-code values informed by tests/Reactor.Tests/CheckCommandTests/Tuning/ which runs the suggester against fixes.jsonl. Snapshot of the first run is in docs/specs/tasks/038-tuning-reports/2026-05-10-50run.md: - CS1061 → 0.80 (only firing in corpus was at conf 0.43; raised threshold blocks structural-rewrite false positives) - CS0103 → 0.75 default (2/2 firings at conf 1.00 matched) - CS0117 / CS1503 / CS7036 → 0.75 default (insufficient signal in 50-pair corpus; revisit at Data Checkpoint C, 500+ pairs) Tuning harness is gated on env var MUR_TUNING_CORPUS so it skips cleanly when the (sibling-repo) corpus isn't available. Phase-1 next gate: Eval Checkpoint EC1 vs. main. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(specs/038): record EC1 5×N results; surface amortization-floor finding EC1 5×N (n=5 paired rounds on gpt-5.5, round-3 prompt with reflection ban + trust-the-suggestion + mur-check-is-the-build rules): kanban-variant — cost mean −24% / median −33% / CV 24% vs base 81% wins 4 of 5 paired rounds; the suggestion mechanism is itself a variance stabilizer. calc-variant — cost mean +21% / wall mean +23% real and consistent across the batch. Diagnosis: ~5–8s per-invocation mur-check overhead does not amortize on ~150-LoC projects with no API exploration surface to skip. Validated empirically — the prompt iterations that helped (round-2 reflection ban, round-3 trust-mur-as-build) closed every explore-around-the- suggestion loophole, but the floor remains. Strict EC1 pass criterion ("tokens not regressed") fails on calc, passes cleanly on kanban. Captured as: - spec 038 §11 risk row + §14 open question on a project-size / per-invocation-diagnostic-count gate - task doc EC1 results section with per-arm means/sd, paired comparisons - status snapshot updated; Phase 1 merge decision noted as pending Decision options on the merge: (a) ship Phase 1 as-is and accept the calc tax; (b) land the gate before merging. Either is product-side; this commit only records the data and the design surface. No code changes. SKILL.md intentionally left untouched — larger mining sweep is running under the current SKILL.md to compare aided vs un-aided baseline. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(spec-038): scope Thresholds override to AsyncLocal to fix parallel-test race ThresholdsTests.Each_handled_code_has_a_threshold_in_valid_range was flaking because the tuner test (ThresholdTuningTests.Run_against_inline_one_row_corpus_produces_report) temporarily writes Thresholds.PerCode to an all-zero map for its duration, and xUnit's default cross-class parallelism let the validation tests observe the zeroed state mid-tuner-run. Switching the override channel to AsyncLocal isolates the tuner's scoped change to its own logical thread; concurrent readers in other tests see the immutable production defaults. Production code paths still go through the same Thresholds.For(code) entry point — behaviour for the CLI is unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(spec-038): land diagnostic-count gate + Data Checkpoint C calibration Two related changes: 1. Diagnostic-count gate (spec §11 risk row, §14 #8) — resolves the EC1 calc-vs-kanban split where ~150-LoC calc regressed +21% cost while kanban won −24%. `CheckCommand.ShouldEmitSuggestions` skips Tier-2 when an invocation surfaces fewer than `--suggest-threshold` unique CS-prefixed diagnostics; default 3, 0 disables. Counts the same dedup key `EmitDiagnostics` uses. 2. Data Checkpoint C — 525-pair mining corpus from spec 037's harness mirrored at `docs/specs/tasks/038-tuning-reports/2026-05-11-525run-source/` (1,027 fixes / 1,233 ranker rows / 104 clusters; `gpt-5.5` only). Tuning report at `2026-05-11-525run.md`. The empirical CS-diagnostics-per-build distribution from the corpus (43% of builds have 1 diagnostic, 28% have 2, 28.7% have ≥ 3) confirms T=3 is the right initial cut-line. The 525-run corpus also surfaces that JaroWinkler fuzzy match has near-0% empirical precision on CS1061/CS0117 against Reactor types — the agent's typical mistake is reaching for a WinUI-style name (`.VerticalAlignment`, `Theme.AppBackground`) whose Reactor replacement is too far in edit-distance to find, so we pick a wrong sibling. All per-code thresholds held; systematic fix is Phase-3 rule authoring. Top three rule targets identified in the report. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(spec-038): record EC1 re-run results; Phase 1 cleared to merge 5×N re-run on `feat/038-mur-check` @ aaa4cce (gate enabled, default --suggest-threshold 3), same matrix as the prior EC1 batch. reactor-calc-mur-check : cost -4% (was +21%) — PASS reactor-kanban-mur-check: cost -33% (was -24%) — PASS, grew the win First-build OK 5/5 both variant arms. Calc neutralized; kanban win preserved and grew. Phase 1 acceptance bar met. Spec §11 risk row + §14 #8 updated to mark the mitigation validated. Watch-item carried into Phase 2: kanban CV widened (24% prior -> 54% this batch) because one of five runs hit 0 firings and tracked the long-tail base path. Gate is path-dependent on agent's exploration order, not just the project's static shape. Below Phase-1 blocker threshold; Phase 2 telemetry should track per-run firing counts. No code change in this commit — eval results + spec doc updates only. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(spec-038): add reference doc for `mur check` did-you-mean engine Layered walkthrough of the system as shipped in this PR (Phase 0 + Phase 1 + diagnostic-count gate): plain-language intro, four-tier architecture, mining pipeline, threshold tuning, end-to-end recommendation flow, the small-project gate, and a future-improvements section sketching Phases 2–4. Lives at docs/reference/ alongside the other developer-facing references; points back to docs/specs/038… for decision history. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(spec-038): address CR feedback on PR #243 Addresses six review comments from Copilot reviewer on the Phase-1 PR: 1. Hoist CompilationLoader.Load to once per `mur check` invocation instead of once per emitted diagnostic. Even with the internal cache, Load() re-enumerates `.cs` files and recomputes the file-set hash on every call, so the prior wiring was O(diagnostics × files). Now O(1) per invocation via SuggesterOrchestrator.SuggestAgainst. 2. FindTreeFor suffix match required a path-separator boundary so a diagnostic on bare "Program.cs" no longer mis-binds to a sibling tree like "MyProgram.cs". Cross-platform: matches against both '/' and '\' prefixes since CSharpCompilation trees can carry either separator depending on the project's source-list. Added regression test. 3. Filter synthesized property/event accessors (get_X / set_X / add_X / remove_X) out of CollectStaticMembers + CollectInstanceMembers. The 525-run calibration report flagged conf=0.88 emissions of `Theme.get_Background` — same hazard would surface on CS1061 against instance-member walks. Fixed at the source. 4. Telemetry.Truncate now enforces a true UTF-8 byte limit, not a char limit. Pure-ASCII content still hits the cheap fast path. New test covers a 200-glyph CJK string (600 bytes pre-truncation). 5. StringSimilarity header comment no longer claims "allocation-free on the hot path" — Jaro() allocates two bool[]s per call. Comment now reflects reality with a pointer to revisit via stackalloc if perf- trait tests show it on the hot path. 6. Drop the "`<path>` accepts a .cs file" claim from CheckArgs.HelpText and the CheckCommand.cs header. `dotnet build <single.cs>` doesn't work end-to-end so the help text was misleading. CompilationLoader still walks up to the nearest .csproj when seeded from a .cs file (tooling/test seam only). Skipped: #6 (MurCheckSmokeTest.cs build-on-demand for mur.exe) — changes the integration-tests CI contract and is cleanly scoped as a separate follow-up. Full suite: 7051/7097 pass (46 skipped — perf-trait + opt-in, unchanged). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(spec-038): adopt load-bearing framing; split Tier-3 rule classes; resolve symbol-binding Doc-only updates across spec, task list, and reference doc to reflect the decision that `mur check`'s did-you-mean engine is load-bearing infrastructure for the next 1-3 years, not a token-saving stopgap base- model improvements will erode. Why now: Reactor will keep churning faster than models retrain, and WinUI 3 is structurally weak / cross-confused with WPF/Silverlight/WinUI 1/2 in training data. The 525-run corpus directly evidences the confusion shape (`.VerticalAlignment` on Reactor `*Element` types, `Theme.AppBackground`, `.Style(...)`). Tier-2 fuzzy match cannot bridge those by edit distance; only deterministic vocabulary-translation rules can. Spec changes (038-mur-check-did-you-mean-design.md): - §1: new "Why this is load-bearing" subsection with the two-condition argument and explicit sunset criterion (≥12mo API stability + ≥90% first-build-OK on ≥2 vendor-distinct models). - §6: rename "induced pattern rules" → "induced and authored pattern rules"; split into Class A (induced, frequency-justified) and Class B (vocabulary-translation, structurally justified, frequency bar waived). Add the resolved symbol-binding decision: rules bind to Roslyn ISymbol references via RuleSymbolResolver, not name strings, with a CI gate that fails the build on unresolved rule targets. - §11: two new risks — Reactor API churn invalidating rules/corpus, and data-pipeline SLA/owner — both with mitigations. - §13 Phase 5: reframe from "only if needed" to "scheduled, deferred" pending Data Checkpoint D. Add explicit sunset criterion subsection. - §14: resolve question #8 (symbol-binding decision recorded with rationale); add question #9 on vocab-table provenance; renumber project-size gate to #10. Task list (tasks/038-mur-check-did-you-mean-implementation.md): - Top: new "Framing (read this first)" section with the load-bearing argument and sunset criterion link. - Phase 3: split rule template into Class A / Class B variants. Add §3.0 pre-phase prerequisites (corpus-pipeline owner; minor-release refresh cadence; in-repo `038-vocab-table.csv`). Add §3.1a symbol-binding contract with CI gate. Update quantity gates + exit criterion for the two-class split. - Phase 4: status change from "optional" to "scheduled, deferred until Data Checkpoint D"; escape hatch remains as the unexpected outcome. - New "Maintenance (load-bearing operation)" section under cross-cutting concerns: API-churn protocol per Reactor minor; corpus freshness rule; per-rule accept-rate monitoring; annual sunset-readiness check. Reference doc (docs/reference/mur-check-did-you-mean.md): - §1: new "Why this is load-bearing" subsection mirrored from the spec. - §9 Future improvements: new "The recurring failure mode: WinUI/WPF vocabulary confusion" subsection that names the structural failure shape, then reframes Phase 3 as Class A / Class B and Phase 4 as scheduled-not-optional. Symbol-binding decision called out. - Out-of-scope (small LLM generator): reasoning now explicitly linked to the load-bearing argument (weak training data is why we need the system AND why a smaller model trained on it won't fix the gap). - Glossary: new entries for Class A / Class B rule, Load-bearing, Sunset criterion. Validation Gate entry updated for the Class-B frequency-bar waiver. - Closing: pointer to the new task-doc Maintenance section. No code changes in this commit; all infrastructure decisions documented here will land in Phase-3 rule PRs. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(spec-038): address CR feedback round 2 on PR #243 Quality and self-consistency pass on the Phase-1 branch. All changes are contained to Phase-1 surface; broader CR concerns about CS1061/CS0117 fuzzy behavior, MSBuild-accurate loading, and per-code precision gating remain scoped to Phase 2/3 per the spec's existing plan. - CR #10: drop CS8602 warning in CompilationLoader by routing EmptyCompilation through a named factory method with explicit Array.Empty<> coalescing. - CR #11: diagnostic regex now uses a reluctant file capture anchored on the (line,col): suffix so MSBuild lines with parenthesized path segments parse correctly. Added pipeline test. - CR #8: TraceWriter.SanitizePath normalizes in-root absolute paths to project-relative (forward-slash) form so traces no longer carry `C:\Users\<name>\...` prefixes. Tests strengthened to assert no row is ever an absolute path. - CR #13: replace misleading CS7036 tiebreak comment with accurate description; full Hamming-vector ranker stays a deferred follow-up per spec §1.5. - CR #14: 525-run report reworded — "500-pair volume bar met, cross-agent bar NOT met"; Theme.get_Background note marked "fixed in this branch" with code reference. - CR #2 (narrowed): tighten CS1061 factory-argument receiver check to require receiver IS-A factory return type only (dropped reverse IsAssignableFrom direction). Full AST-anchored receiver verification deferred to Phase-3 RuleSymbolResolver per §3.1a. - Implementation doc deferred-follow-ups list updated to include receiver-anchoring (e) and Phase-2 loader/precision-gate work (f). Verification: 98 CheckCommand unit tests pass (was 97 + new parens-path test); MurCheck integration test passes; CS8602 warning eliminated. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
7 of 8 tasks
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 12, 2026
* feat(spec-038): Phase 2 — MSBuild passthrough + deterministic pre-emit ranker
`mur check` grows two agent-visible behaviors on top of the Phase-1 Tier-2
suggester: MSBuild flag passthrough via the `--` separator with
default-merging (`--nologo`, `-v:m`, `-p:Platform={host arch}` injected
only when not named in passthrough), and a pre-emit ranker that suppresses
cosmetic noise mid-iteration (CS1591 XML doc, CS0168 unused-var, IDE0xxx
style, NU1701/NU1605, MSB3245/3270/3277, CS8600-8625 nullable warnings,
REACTOR_* info-severity) while always emitting errors via a universal-
error floor. New mode flags `--strict` / `--final` / `--quiet` and
`--emit-threshold <float>` round-trip through ArgsParser. Trace output
records the effective `dotnet build` argv as a `kind: "command"` header
row so replays are bit-faithful.
Suppress→error guardrail at tools/Reactor.MurCheckGuardrail audits an
iter+final trace pair against PolicyTable's universal-error-floor
invariant. Re-uses the live PolicyTable via InternalsVisibleTo so the
two sources can never drift. Eight unit tests; the harness-side CI
wiring is deferred behind the same WindowsAppSDK-fixture blocker as
Phase-1 §1.6.
Phase-2.x post-EC2 fixes:
* Gate-input regression. CheckCommand.ShouldEmitSuggestions now counts
the full parsed diagnostic list, not the post-ranker emittable list.
EC2's 3-round preview measured Tier-2 firing collapse from EC1's 80%
to 0% on kanban-mur because the ranker's nullable-warning suppression
closed the gate on builds EC1 had left open. Regression test
RankerTests.Suggest_gate_counts_full_parsed_list_not_post_ranker_emittable
locks the behavior.
* `--final` framing softened in both plugins/reactor/skills/reactor-
build-and-check/SKILL.md and the legacy root SKILL.md. EC2's 3-round
preview measured 0/6 production value across mandatory --final
invocations; the framing now describes --final as an optional pre-
merge sweep for human review / CI gates, explicitly not a task-
completion requirement.
* TraceWriter mode propagation fix. The diagnostic-row `mode` field
used to be hardcoded to "iteration" even when invoked via --final.
Now piped through TraceWriter.Open(path, root, mode); regression
test TraceWriterTests.Diag_row_mode_matches_writer_invocation_mode
locks it.
EC2 5×N PASS by median (2026-05-11):
* reactor-calc-mur-check beats base on every metric — cost −5.1%,
tokens −5.8%, turns −5.1%, wall −7.9%; CV cost 1.9× tighter.
* reactor-kanban-mur-check at cost median parity ($3.30 = $3.30);
mean dragged to +5.7% by R2 outlier (R2-excluded mean −3.3%).
* First-build OK 5/5 both variant arms.
* --final invocation 0/10 across both projects (SKILL framing
working as designed; the previous bugged-Phase-2 batch had 6/6
mandatory invocations).
* Tier-2 firing 0/10 — gate correctly inhibits on small-batch
iteration patterns; closing the kanban token gap is Phase-3's
scope (rules > fuzzy match).
* Criterion-2 guardrail audit deferred to a harness retrofit
(post-run `mur check --final` against the final workspace state).
Tests: 7102 / 7102 passing on the post-fix tree. CheckCommandTests
grew from 120 to 148 tests across the Phase-2 surfaces (ArgsParser
passthrough + mode flags, Ranker scoring + emit gates, Guardrail
trace-pair audit, TraceWriter mode propagation, gate-input regression).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* feat(spec-038): Phase 3 — Class-B rules + Margin/Padding API ergonomics
Three Class-B vocabulary-translation rules under the Phase-3 rule
infrastructure, plus two Reactor API/skill fixes surfaced while authoring
them.
Rules (Validation Gate; ready for review, not merge — bar #5 is human):
- ThemeBackgroundSuffixRule: CS0117 on Theme.*Background → Theme.SolidBackground
(cluster C0019, 16 events)
- AlignmentShortcutRule: CS1061 on Reactor *Element receivers for
HorizontalAlignment / VerticalAlignment → .HAlign(...) / .VAlign(...)
(cluster C0017 + adjacent, ~22 events)
- ButtonOnClickFactoryMoveRule: CS1061 on ButtonElement.OnClick →
Button(..., onClick: ...), explicitly naming .OnTapped as the wrong sibling
to keep agents from reaching for the gesture event
Reactor API fixes (driven by 525-run corpus signal):
- Margin / Padding per-side overloads now default unspecified sides to 0.0,
eliminating ~198 corpus build failures from .Margin(top: 12)-shaped calls
- BREAKING (pre-1.0): Margin(double, double) and Padding(double, double)
parameter order swapped from (horizontal, vertical) to (vertical, horizontal)
to match CSS shorthand (top/bottom first). All repo callsites migrated to
named-arg form for layout preservation and reviewer clarity.
Skill updates (agent context):
- reactor-getting-started cheatsheet shows named-arg Button("Save", onClick: handler)
with explicit anti-pattern call-out
- .OnTapped example re-anchored to non-Button surfaces (Border, Image, ScrollView)
§3.1a residual: trace-channel rule_self_disabled row when a rule's declared
target stops resolving against the live Reactor compilation; routed through
TraceWriter.WriteRuleSelfDisabled, dedup'd per-invocation per-rule.
Tests: Reactor.Tests 7156/7202 (46 expected-skip); CheckCommandTests 193/193.
Solution builds clean (no new C# / REACTOR_* warnings).
Class-A rule PRs remain blocked on second-agent corpus drop (Validation Gate
bar #2, cross-agent reproducibility).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* fix(spec-038): force-load Reactor.dll BEFORE enumerating refs
Copilot review feedback on #248: BuildLiveReactorCompilation enumerated
AppDomain.CurrentDomain.GetAssemblies() before the
`typeof(...AsyncValue<int>).Assembly` force-load, so on a cold xunit
run where Reactor.dll wasn't already loaded, the enumeration completed
without Reactor in the reference list and target resolution failed for
every rule.
Moving the force-load to the head of the method guarantees Reactor.dll
is in the AppDomain before enumeration begins. Spec 038 §3.1a.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Merged
19 tasks done
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 22, 2026
… override
Two regressions exposed by selftests after the initial shape-only
refactor:
1. **Model-mutator additions orphaned**: `model.Dock(newPane)` adds
a pane that isn't in `manager.Layout`. The shape-only override's
`ResolveContents` couldn't find newPane in the app's tree, so
the resolved layout had a key-only orphan with no Content — the
pane's body disappeared from the visual tree. Fix: host now
maintains a `knownPanes` `Dictionary<object, DockableContent>`
via `UseRef`, refreshed each render from `manager.Layout` and
appended to whenever a mutation (drain, tear-out, drop-confirm,
tab-close) produces a new tree. Resolve matches shape leaves
against the dict, covering both app-supplied panes and
model-mutator additions. New `DockLayoutMutator.IndexLeavesInto`
helper + `ResolveContents(shape, dict)` overload.
2. **Intentionally-empty layout collapsed to no-override**: my
first cut treated `layoutOverride is { Root: not null }` as
"use override; otherwise fall through to manager.Layout".
That conflated `LayoutOverride(null)` ("intentionally empty —
user closed the last pane") with "no override at all". The
`LayoutOverride` wrapper exists specifically to distinguish
these two — closing the last pane would otherwise resurrect
it on the next render via the `manager.Layout` fallback.
Fix: explicit three-way switch (null → use prop;
wrapper-with-null-root → empty; wrapper-with-non-null-root →
resolve).
`NativeDocking_ModelDrain_PinPrep_ToolPresentBeforePin` (#1) and
`NativeDocking_Reliability_Effect_BodyGoneFromTree` (#2) now pass.
Full NativeDocking selftest suite green except for the documented
`SplitterProgrammaticVisualDemo_TIMEOUT` known flake.
`StoreOverride(tree)` helper consolidates the 6 host-side
override-setting call sites — index into knownPanes then strip +
store. Keeps the contract uniform across drag/drop/close paths.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 22, 2026
Resolves the 22 findings from the docking feature-branch review + two test failures that surfaced while running the full suite. Behavior fixes (Native docking host): - Tear-out / FloatOp: open the floating window BEFORE removing the pane from the docked tree. Layout mutation + OnContentFloated fire only when a real ReactorWindow was produced (review #1 — the previous broad catch around Open turned a failed transition into a success-shaped event). - Drop-overlay global Esc handler now detaches on reconciler unmount in addition to WinUI Unloaded (review #2). - Floating-window observer callbacks, BeforeInsertToolWindow strategy hook, drag-session SessionChanged broadcast, navigator commit callback, and theme/resource lookup catches all surface failures via Debug.WriteLine or narrow to the expected exception type instead of swallowing everything (reviews #3, #4, #5, #7, #8). - Splitter OnPointerCaptureLost now calls RestorePairToGrow() before the final ResizeDelta to converge with the normal release path (review #6). Persistence: - DockLayoutSerializer.Load now routes pre-current-schema documents through DockLayoutMigrationRegistry: parse to JsonNode, detect schema (absent $schema = v1 per §5.4.4), TryUpgrade, then deserialize. Adds a Load(json, registry) overload and emits a PII-safe schema-newer ETW category for forward-tolerant inputs (reviews #9 + #10). - PreviousContainerTracker.ClearAll now actually clears by swapping in a fresh ConditionalWeakTable under a lock (review #11). Surface honesty: - DockHostModel.Floating is populated by the host renderer from a per-manager floating-window tracker; doc comment makes the initial-bounds-only limitation explicit (review #12). - UseDockPanePersisted uses a canonical persisted-key encoder (pane:<typeName>|<keyText>:<userKey> with %/colon/pipe escaping) so two panes whose Key.ToString() collide get independent slots (review #13). - docking.dock detects ambiguous Key.ToString() matches and returns an explicit ambiguous-pane error (review #18). Test isolation: - New DockingGlobalsCollection ([Collection("DockingGlobals")] + DisableParallelization=true) covers DockingStringsTests, DockA11yTests, and DevtoolsDockingToolsTests — three classes that mutate process-global state (review #14). DockA11yTests now restores DockingStrings.Resolver in Dispose. - The known-failing UseEffect cleanup assertion is emitted as TAP "# SKIP" via a new Harness.Skip helper, with a back-flip to a real Check the moment the §2.25 product gap closes (review #15). - EffectCounterComponent moved off static counters; the fixture owns per-run counters and passes mount/cleanup callbacks via props (review #16). - EventListener category assertions in LayoutSerializerTests use a bounded retry helper to tolerate occasional async dispatch (review #17). Documentation: - docs/_pipeline/apps/docking/{api,overview}.md updated for the P2 reality (core Microsoft.UI.Reactor ship vehicle, DockingNativeInterop.Register, deleted vendored WinUI.Dock link) (reviews #19, #22). - DockingStrings.cs + dock-showcase sample comments updated to reflect that no .resw resource ships today; DefaultEnglish + the resolver are the localization surface (review #20). - Reactor.csproj stale "stays on disk for reference" comment about src/Reactor.Docking.Xaml/ replaced with current state (review #21). Tests / fluents: - Added 22 fluent extensions in ElementExtensions.Events.cs for DockManager event callbacks + TabViewElement.OnTabDragStarting / OnTabDragCompleted so PublicApiSurfaceGuardTests passes; the guard test itself is now scoped to public element records only (internal overlay/splitter elements aren't part of the public surface contract). - Two stale Phase-1-wrapper fixture names removed from SelfTestFixtureRegistry.AllFixtures (they had no factory case and surfaced as MSTest "fixture not found" failures). - NativeDocking_PerGroupDropTargetVisualDemo: observer-pause delays cut from 500ms/step to 50ms/step so the 20-step walk stays well inside the 15s fixture timeout under CI load; eliminates the cascading NRE in DragSessionConfirmMutatesLayout that was caused by the timed-out fixture leaving stale host state. - Mutations_OffOwnerThread_Throw uses an explicit new Thread() instead of Task.Run, so the assert can never observe a thread-id match by chance. - Load_MissingSchemaField_FallsBack renamed to Load_MissingSchemaField_TreatedAsV1AndMigrated and rewritten — empty {} now migrates as v1 (matches the integrated registry). Validation: - dotnet test tests/Reactor.Tests -p:Platform=x64 → 8720 passed, 46 skipped, 0 failed - dotnet test tests/Reactor.SelfTests -p:Platform=x64 → 813 passed, 0 failed Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
6 of 7 tasks
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 22, 2026
… override
Two regressions exposed by selftests after the initial shape-only
refactor:
1. **Model-mutator additions orphaned**: `model.Dock(newPane)` adds
a pane that isn't in `manager.Layout`. The shape-only override's
`ResolveContents` couldn't find newPane in the app's tree, so
the resolved layout had a key-only orphan with no Content — the
pane's body disappeared from the visual tree. Fix: host now
maintains a `knownPanes` `Dictionary<object, DockableContent>`
via `UseRef`, refreshed each render from `manager.Layout` and
appended to whenever a mutation (drain, tear-out, drop-confirm,
tab-close) produces a new tree. Resolve matches shape leaves
against the dict, covering both app-supplied panes and
model-mutator additions. New `DockLayoutMutator.IndexLeavesInto`
helper + `ResolveContents(shape, dict)` overload.
2. **Intentionally-empty layout collapsed to no-override**: my
first cut treated `layoutOverride is { Root: not null }` as
"use override; otherwise fall through to manager.Layout".
That conflated `LayoutOverride(null)` ("intentionally empty —
user closed the last pane") with "no override at all". The
`LayoutOverride` wrapper exists specifically to distinguish
these two — closing the last pane would otherwise resurrect
it on the next render via the `manager.Layout` fallback.
Fix: explicit three-way switch (null → use prop;
wrapper-with-null-root → empty; wrapper-with-non-null-root →
resolve).
`NativeDocking_ModelDrain_PinPrep_ToolPresentBeforePin` (#1) and
`NativeDocking_Reliability_Effect_BodyGoneFromTree` (#2) now pass.
Full NativeDocking selftest suite green except for the documented
`SplitterProgrammaticVisualDemo_TIMEOUT` known flake.
`StoreOverride(tree)` helper consolidates the 6 host-side
override-setting call sites — index into knownPanes then strip +
store. Keeps the contract uniform across drag/drop/close paths.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 22, 2026
Resolves the 22 findings from the docking feature-branch review + two test failures that surfaced while running the full suite. Behavior fixes (Native docking host): - Tear-out / FloatOp: open the floating window BEFORE removing the pane from the docked tree. Layout mutation + OnContentFloated fire only when a real ReactorWindow was produced (review #1 — the previous broad catch around Open turned a failed transition into a success-shaped event). - Drop-overlay global Esc handler now detaches on reconciler unmount in addition to WinUI Unloaded (review #2). - Floating-window observer callbacks, BeforeInsertToolWindow strategy hook, drag-session SessionChanged broadcast, navigator commit callback, and theme/resource lookup catches all surface failures via Debug.WriteLine or narrow to the expected exception type instead of swallowing everything (reviews #3, #4, #5, #7, #8). - Splitter OnPointerCaptureLost now calls RestorePairToGrow() before the final ResizeDelta to converge with the normal release path (review #6). Persistence: - DockLayoutSerializer.Load now routes pre-current-schema documents through DockLayoutMigrationRegistry: parse to JsonNode, detect schema (absent $schema = v1 per §5.4.4), TryUpgrade, then deserialize. Adds a Load(json, registry) overload and emits a PII-safe schema-newer ETW category for forward-tolerant inputs (reviews #9 + #10). - PreviousContainerTracker.ClearAll now actually clears by swapping in a fresh ConditionalWeakTable under a lock (review #11). Surface honesty: - DockHostModel.Floating is populated by the host renderer from a per-manager floating-window tracker; doc comment makes the initial-bounds-only limitation explicit (review #12). - UseDockPanePersisted uses a canonical persisted-key encoder (pane:<typeName>|<keyText>:<userKey> with %/colon/pipe escaping) so two panes whose Key.ToString() collide get independent slots (review #13). - docking.dock detects ambiguous Key.ToString() matches and returns an explicit ambiguous-pane error (review #18). Test isolation: - New DockingGlobalsCollection ([Collection("DockingGlobals")] + DisableParallelization=true) covers DockingStringsTests, DockA11yTests, and DevtoolsDockingToolsTests — three classes that mutate process-global state (review #14). DockA11yTests now restores DockingStrings.Resolver in Dispose. - The known-failing UseEffect cleanup assertion is emitted as TAP "# SKIP" via a new Harness.Skip helper, with a back-flip to a real Check the moment the §2.25 product gap closes (review #15). - EffectCounterComponent moved off static counters; the fixture owns per-run counters and passes mount/cleanup callbacks via props (review #16). - EventListener category assertions in LayoutSerializerTests use a bounded retry helper to tolerate occasional async dispatch (review #17). Documentation: - docs/_pipeline/apps/docking/{api,overview}.md updated for the P2 reality (core Microsoft.UI.Reactor ship vehicle, DockingNativeInterop.Register, deleted vendored WinUI.Dock link) (reviews #19, #22). - DockingStrings.cs + dock-showcase sample comments updated to reflect that no .resw resource ships today; DefaultEnglish + the resolver are the localization surface (review #20). - Reactor.csproj stale "stays on disk for reference" comment about src/Reactor.Docking.Xaml/ replaced with current state (review #21). Tests / fluents: - Added 22 fluent extensions in ElementExtensions.Events.cs for DockManager event callbacks + TabViewElement.OnTabDragStarting / OnTabDragCompleted so PublicApiSurfaceGuardTests passes; the guard test itself is now scoped to public element records only (internal overlay/splitter elements aren't part of the public surface contract). - Two stale Phase-1-wrapper fixture names removed from SelfTestFixtureRegistry.AllFixtures (they had no factory case and surfaced as MSTest "fixture not found" failures). - NativeDocking_PerGroupDropTargetVisualDemo: observer-pause delays cut from 500ms/step to 50ms/step so the 20-step walk stays well inside the 15s fixture timeout under CI load; eliminates the cascading NRE in DragSessionConfirmMutatesLayout that was caused by the timed-out fixture leaving stale host state. - Mutations_OffOwnerThread_Throw uses an explicit new Thread() instead of Task.Run, so the assert can never observe a thread-id match by chance. - Load_MissingSchemaField_FallsBack renamed to Load_MissingSchemaField_TreatedAsV1AndMigrated and rewritten — empty {} now migrates as v1 (matches the integrated registry). Validation: - dotnet test tests/Reactor.Tests -p:Platform=x64 → 8720 passed, 46 skipped, 0 failed - dotnet test tests/Reactor.SelfTests -p:Platform=x64 → 813 passed, 0 failed Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 23, 2026
… override
Two regressions exposed by selftests after the initial shape-only
refactor:
1. **Model-mutator additions orphaned**: `model.Dock(newPane)` adds
a pane that isn't in `manager.Layout`. The shape-only override's
`ResolveContents` couldn't find newPane in the app's tree, so
the resolved layout had a key-only orphan with no Content — the
pane's body disappeared from the visual tree. Fix: host now
maintains a `knownPanes` `Dictionary<object, DockableContent>`
via `UseRef`, refreshed each render from `manager.Layout` and
appended to whenever a mutation (drain, tear-out, drop-confirm,
tab-close) produces a new tree. Resolve matches shape leaves
against the dict, covering both app-supplied panes and
model-mutator additions. New `DockLayoutMutator.IndexLeavesInto`
helper + `ResolveContents(shape, dict)` overload.
2. **Intentionally-empty layout collapsed to no-override**: my
first cut treated `layoutOverride is { Root: not null }` as
"use override; otherwise fall through to manager.Layout".
That conflated `LayoutOverride(null)` ("intentionally empty —
user closed the last pane") with "no override at all". The
`LayoutOverride` wrapper exists specifically to distinguish
these two — closing the last pane would otherwise resurrect
it on the next render via the `manager.Layout` fallback.
Fix: explicit three-way switch (null → use prop;
wrapper-with-null-root → empty; wrapper-with-non-null-root →
resolve).
`NativeDocking_ModelDrain_PinPrep_ToolPresentBeforePin` (#1) and
`NativeDocking_Reliability_Effect_BodyGoneFromTree` (#2) now pass.
Full NativeDocking selftest suite green except for the documented
`SplitterProgrammaticVisualDemo_TIMEOUT` known flake.
`StoreOverride(tree)` helper consolidates the 6 host-side
override-setting call sites — index into knownPanes then strip +
store. Keeps the contract uniform across drag/drop/close paths.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 23, 2026
Resolves the 22 findings from the docking feature-branch review + two test failures that surfaced while running the full suite. Behavior fixes (Native docking host): - Tear-out / FloatOp: open the floating window BEFORE removing the pane from the docked tree. Layout mutation + OnContentFloated fire only when a real ReactorWindow was produced (review #1 — the previous broad catch around Open turned a failed transition into a success-shaped event). - Drop-overlay global Esc handler now detaches on reconciler unmount in addition to WinUI Unloaded (review #2). - Floating-window observer callbacks, BeforeInsertToolWindow strategy hook, drag-session SessionChanged broadcast, navigator commit callback, and theme/resource lookup catches all surface failures via Debug.WriteLine or narrow to the expected exception type instead of swallowing everything (reviews #3, #4, #5, #7, #8). - Splitter OnPointerCaptureLost now calls RestorePairToGrow() before the final ResizeDelta to converge with the normal release path (review #6). Persistence: - DockLayoutSerializer.Load now routes pre-current-schema documents through DockLayoutMigrationRegistry: parse to JsonNode, detect schema (absent $schema = v1 per §5.4.4), TryUpgrade, then deserialize. Adds a Load(json, registry) overload and emits a PII-safe schema-newer ETW category for forward-tolerant inputs (reviews #9 + #10). - PreviousContainerTracker.ClearAll now actually clears by swapping in a fresh ConditionalWeakTable under a lock (review #11). Surface honesty: - DockHostModel.Floating is populated by the host renderer from a per-manager floating-window tracker; doc comment makes the initial-bounds-only limitation explicit (review #12). - UseDockPanePersisted uses a canonical persisted-key encoder (pane:<typeName>|<keyText>:<userKey> with %/colon/pipe escaping) so two panes whose Key.ToString() collide get independent slots (review #13). - docking.dock detects ambiguous Key.ToString() matches and returns an explicit ambiguous-pane error (review #18). Test isolation: - New DockingGlobalsCollection ([Collection("DockingGlobals")] + DisableParallelization=true) covers DockingStringsTests, DockA11yTests, and DevtoolsDockingToolsTests — three classes that mutate process-global state (review #14). DockA11yTests now restores DockingStrings.Resolver in Dispose. - The known-failing UseEffect cleanup assertion is emitted as TAP "# SKIP" via a new Harness.Skip helper, with a back-flip to a real Check the moment the §2.25 product gap closes (review #15). - EffectCounterComponent moved off static counters; the fixture owns per-run counters and passes mount/cleanup callbacks via props (review #16). - EventListener category assertions in LayoutSerializerTests use a bounded retry helper to tolerate occasional async dispatch (review #17). Documentation: - docs/_pipeline/apps/docking/{api,overview}.md updated for the P2 reality (core Microsoft.UI.Reactor ship vehicle, DockingNativeInterop.Register, deleted vendored WinUI.Dock link) (reviews #19, #22). - DockingStrings.cs + dock-showcase sample comments updated to reflect that no .resw resource ships today; DefaultEnglish + the resolver are the localization surface (review #20). - Reactor.csproj stale "stays on disk for reference" comment about src/Reactor.Docking.Xaml/ replaced with current state (review #21). Tests / fluents: - Added 22 fluent extensions in ElementExtensions.Events.cs for DockManager event callbacks + TabViewElement.OnTabDragStarting / OnTabDragCompleted so PublicApiSurfaceGuardTests passes; the guard test itself is now scoped to public element records only (internal overlay/splitter elements aren't part of the public surface contract). - Two stale Phase-1-wrapper fixture names removed from SelfTestFixtureRegistry.AllFixtures (they had no factory case and surfaced as MSTest "fixture not found" failures). - NativeDocking_PerGroupDropTargetVisualDemo: observer-pause delays cut from 500ms/step to 50ms/step so the 20-step walk stays well inside the 15s fixture timeout under CI load; eliminates the cascading NRE in DragSessionConfirmMutatesLayout that was caused by the timed-out fixture leaving stale host state. - Mutations_OffOwnerThread_Throw uses an explicit new Thread() instead of Task.Run, so the assert can never observe a thread-id match by chance. - Load_MissingSchemaField_FallsBack renamed to Load_MissingSchemaField_TreatedAsV1AndMigrated and rewritten — empty {} now migrates as v1 (matches the integrated registry). Validation: - dotnet test tests/Reactor.Tests -p:Platform=x64 → 8720 passed, 46 skipped, 0 failed - dotnet test tests/Reactor.SelfTests -p:Platform=x64 → 813 passed, 0 failed Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
3 tasks done
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 30, 2026
…nt bucketing) CR item #1 (GridView/ListBox deferred-echo) — revert SelectedIndex to the causal counter (ShouldSuppress/WriteSuppressed; drop the §8 value-diff arm), restoring main's mechanism. Empirically probed on this box: post-realization SelectionChanged is synchronous (deferral is mount-only), the counter and the value-diff arm behave identically in every production-reachable path, and the guarded -1 no-op leaves the echo counter at 0 (no strand) so a later genuine deselect still fires. The counter gate suppresses the whole trampoline fire, so it also governs the multi-select snapshot OnSelectionChanged (CR #3) and the guarded-no-op self-clear concern is moot (CR #4). ComboBox/toggles/pickers keep the value-diff arm (synchronous by construction). Descriptor + fixture narration updated to match. CR item #2 (empty ElementExtras bucket) — normalize the 14 bucketed init shims via ElementExtras.IsEmpty + Element.NormalizeExtras so writing a bucketed field to null never materializes/keeps a non-null empty bucket. An empty bucket is not Equals to null, which otherwise broke record equality between an extras-free element and one with a field cleared to null. New ElementExtrasBucketTests. CR item #6 — make Element.Extensions setter internal to remove the initializer-ordering footgun from the public surface (no in-repo external writes; bucketed shim properties stay public). Nits — ComboBox stale ShouldSuppress doc; PerformanceBudgets §4.9 dead-code TODO; Reconciler ContinueDefaultTraversal cref namespace fix (clears the CS1574 warning); TabView pinnable-tab "not byte-identical" callout; ContentDialog OnClosed tag-routing follow-up note; §4.4 ElementExtras construction-cost note. Verified: core builds clean (ARM64 + x64), Reactor.Tests 9132 passed / 62 skip, selftest ValueDiff/Echo/ComboBox/GridView/ListBox/SelectionEvent/EventStateSplit fixtures all green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 30, 2026
…nt bucketing) CR item #1 (GridView/ListBox deferred-echo) — revert SelectedIndex to the causal counter (ShouldSuppress/WriteSuppressed; drop the §8 value-diff arm), restoring main's mechanism. Empirically probed on this box: post-realization SelectionChanged is synchronous (deferral is mount-only), the counter and the value-diff arm behave identically in every production-reachable path, and the guarded -1 no-op leaves the echo counter at 0 (no strand) so a later genuine deselect still fires. The counter gate suppresses the whole trampoline fire, so it also governs the multi-select snapshot OnSelectionChanged (CR #3) and the guarded-no-op self-clear concern is moot (CR #4). ComboBox/toggles/pickers keep the value-diff arm (synchronous by construction). Descriptor + fixture narration updated to match. CR item #2 (empty ElementExtras bucket) — normalize the 14 bucketed init shims via ElementExtras.IsEmpty + Element.NormalizeExtras so writing a bucketed field to null never materializes/keeps a non-null empty bucket. An empty bucket is not Equals to null, which otherwise broke record equality between an extras-free element and one with a field cleared to null. New ElementExtrasBucketTests. CR item #6 — make Element.Extensions setter internal to remove the initializer-ordering footgun from the public surface (no in-repo external writes; bucketed shim properties stay public). Nits — ComboBox stale ShouldSuppress doc; PerformanceBudgets §4.9 dead-code TODO; Reconciler ContinueDefaultTraversal cref namespace fix (clears the CS1574 warning); TabView pinnable-tab "not byte-identical" callout; ContentDialog OnClosed tag-routing follow-up note; §4.4 ElementExtras construction-cost note. Verified: core builds clean (ARM64 + x64), Reactor.Tests 9132 passed / 62 skip, selftest ValueDiff/Echo/ComboBox/GridView/ListBox/SelectionEvent/EventStateSplit fixtures all green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
May 30, 2026
…#455) * spec(047): Phase 4 (4.0.5) - XamlHost/XamlPage own V1 registration Closes the XAML-interop slice of the §4.0 reachable-but-deferred carve: - Register XamlPageDescriptor/XamlHostDescriptor handlers in RegisterV1BuiltInHandlers so V1 auto-registration owns the two reverse-embedding element types. - Add internal Reconciler.IsElementTypeRegistered and make XamlInterop.Register idempotent (skips already-owned types) so the public API no longer trips EnsureRegistrableElementType under V1 ON. - Update XamlInteropTests double-throw test to idempotency; add V1-ON registration + clashless-Register regression tests. Verified: xunit XamlInterop/V1OnRegistration/TypeRegistry (91) green; Hosting_XamlInteropRegister selftest green V1 ON == V1 OFF. Co-authored-by: Copilot <[email protected]> * Spec 047 Phase 4 (4.0.2): port NavigationHost unmount to V1 handler Extract Reconciler.CleanupNavigationHostNode and own navigation teardown from NavigationHostHandler.Unmount on the V1 path. The flag-independent UnmountRecursive intercept becomes a !UseV1Protocol fallback so cleanup stays byte-identical V1 ON =/= V1 OFF until the V1-OFF escape path is deleted in 4.6. NavHost selftests 16/16 green under both flags; NavigationHostTests + UseNavigationTests 30/30 pass. Co-authored-by: Copilot <[email protected]> * Spec 047 CR Finding 1: fix stranded echo-suppression token in controlled descriptor entries ControlledPropEntry.Update and HandCodedControlledPropEntry.Update wrote under echo-suppression whenever the element prop changed (oldEl != newEl), even when the control already held the new value. WriteSuppressed always increments the suppress counter, consumed only by a real change event; a suppressed no-op write strands the token and silently swallows the user's next real interaction (the cross-state echo class spec 047 section 8 exists to prevent). Suppress only on real control drift (current != newValue). Add real-input echo-stranding regression fixtures across both entry types (RadioButton + ToggleSplitButton via ControlledPropEntry; TextBox + NumberBox via HandCodedControlledPropEntry). Verified red→green: all four SecondEventNotSwallowed assertions fail with the bug reintroduced and pass with the fix. Full Desc_ descriptor suite: 0 failures. Co-authored-by: Copilot <[email protected]> * Spec 047 CR Finding 2: gate V1-ON selftests in CI Add a 'Selftests (V1 ON)' CI job that runs the full selftest suite with REACTOR_USE_V1_PROTOCOL=true so V1-ON =/= V1-OFF parity is enforced by an automated gate rather than asserted by a one-off manual run. Runs the AppTests.Host directly (Program.cs maps the env var to the AppContext switch before any Reconciler is built), since Reactor.Tests/xunit does not map the flag. Mirrors the existing aot-selftests run-the-host pattern and uploads TAP output as an artifact. Also harden TabRenderer_TitleBarChrome/FlatChrome_BodyRendered with a second Harness.Render() pump: TabView lazy-realizes selected-pane body content on dispatcher messages scheduled by layout, which a single pump can race on contended runners (consistent with the documented Harness.Render mitigation). Co-authored-by: Copilot <[email protected]> * spec(047): Phase 4 (4.1) - flip UseV1Protocol ON by default Flip the Reconciler ctor default so V1 dispatch is the production path when neither the explicit ctor flag nor the AppContext switch is set. The flag now exists only as an escape hatch to force V1 OFF during the legacy-deletion window (gated to 4.5/4.6). Fix 4 tests that assumed the OFF default: - XamlInteropTests x2: assert via IsElementTypeRegistered (flag-independent) since XamlHost/Page are owned by the V1 registry under ON. - TypeRegistryTests.Override_Builtin_Type: pin to useV1Protocol:false (legacy built-in override is V1-OFF-only per 13 Q17). - RichEditBoxElementTests: tolerate TargetInvocationException-wrapped COMException from V1 new T() construction. Verified: xunit ON = 9136 passed/0 failed; full selftest ON = 0 failures. Co-authored-by: Copilot <[email protected]> * spec(047): Phase 4 (4.0.4) - lock GridView lazy realization with a scale selftest The GridViewHandler already routes through the engine's virtualizing MountGridView body (ItemsSource = Range + shared ItemTemplate + ContainerContentChanging), mirroring ListViewHandler. Add RareControl_GridViewLazy to lock that CCC lifecycle: 500 items in a 200px viewport realize only ~96 containers (< total/2), the tail item stays unrealized, the first item realizes. Identical 96/500 under V1 ON and V1 OFF - A|B parity green. Guards against a regression to the descriptor's non-virtualizing ItemsHost<> path. Co-authored-by: Copilot <[email protected]> * spec(047): Phase 4 (4.4 spec-hygiene) - cite measured 11.6 byte targets Replace the stale 100/320/500 B byte-gate estimates with the measured 11.6 targets (Target = min(Direct + 100, ReactorToday x 0.4) -> 407 / 1520 / 19200) in spec 14 cleanup, 15.1 goal 1, the 15.6 hard-gate sentence, and the 15.7 Phase 4 row. Fix the 15.6 'Phase 5 cleanup' reference to 'Phase 4' (this spec has no Phase 5). Co-authored-by: Copilot <[email protected]> * spec(047): Phase 4 (4.7) - retire obsolete REACTOR1001/REACTOR1003 analyzers The final descriptor API is fully strongly-typed: events wire via typed subscribe lambdas (no changeEvent string names) and Controlled<TValue,TArgs> unifies set/readBack so the compiler already rejects a read-back type mismatch. A repo sweep found zero string-form event references in production descriptors, so REACTOR1001 (string event ref) and REACTOR1003 (read-back type) had no source pattern left to match. Remove both no-op analyzers + their test fixtures, the two reserved diagnostic descriptors, and the REACTOR1001/1003 rows from AnalyzerReleases.Unshipped.md and the guide table. REACTOR1002 (CustomEventDelegateTypeAnalyzer) remains as the active Q10 compile-time check. Analyzer tests green (4 pass). Co-authored-by: Copilot <[email protected]> * spec(047): Phase 4 - add live progress log + 4.0.1/4.0.3 handoff context Document completed work (4.0.6 parity, 4.1 flip, 4.0.4 GridView lock, 4.4 spec-hygiene, 4.7 analyzer retirement) and the critical context for the next session: the prelude delegate handlers call legacy MountXxx bodies, so genuine 4.0.1 (modal-lifecycle decorator strategy) + 4.0.3 (TabView engine features) ports must land before 4.5 can delete the legacy switch. Includes verified build/test commands and the concurrent-selftest-build race warning. Co-authored-by: Copilot <[email protected]> * spec-047 §4.5 + §4.0.1/§4.0.3: delete legacy dispatch switch & finalize overlay/TabView ports Phase 4 close-out work, landing the genuine V1 ports together with the legacy dispatch-switch deletion they unblock. §4.0.1 overlay port: overlays are now owned by the new V1 OverlayLifecycle static module; the engine no longer delegates into legacy bodies. §4.0.3 TabView port: full TabViewDescriptor replaces the delegate TabViewHandler (deleted), with drag pipeline, pinnable headers and imperative-bridged strip slots. §4.5: both Mount/Update dispatch to V1 registry -> _typeRegistry -> composition-primitive-only switch (Component/Func/Memo/ErrorBoundary/ CommandHost/FormField/ValidationVisualizer/ValidationRule). Dead-body sweep removed the orphaned legacy Mount*/Update* bodies including the 14 overlay delegators and Mount/UpdateTabView. Overlay leaf helpers (Create/Update MenuFlyout/AppBar items) promoted to internal for OverlayLifecycle; BuildTabHeader/TryUpdatePinHeaderInPlace stay internal for TabViewDescriptor. Tests: removed the obsolete descriptor-vs-handler parity harness (Spec047V1ProtocolDescriptorFixtures + Desc_ registry entries; Echo_ real-input regression fixtures preserved); dropped the dead UpdateCommandBarFlyout/UpdateFlyoutElement reflection probes. Validation: build 0 err; xunit V1 ON 9136 pass/0 fail; full selftest 0 fail. Co-authored-by: Copilot <[email protected]> * spec-047 §4.6 — remove A|B / UseV1Protocol dead code V1 is the unconditional production path (§4.5 deleted the legacy dispatch switch), so the entire A|B testing apparatus is dead. This removes it. Reconciler: - Collapse the four ctors into a single `Reconciler(ILogger? logger = null)`; drop the `useV1Protocol` / `registerBuiltinHandlers` params, the `public bool UseV1Protocol` property, and the AppContext-switch read. - Drop the flag guard from both dispatch sites (Mount.cs:66, Update.cs:117), both unmount arms, and the NavigationHost pre-dispatch block. Tests / harness: - Remove the REACTOR_USE_V1_PROTOCOL env-var mapping (AppTests.Host/Program.cs) and the redundant `selftests-v1` CI job. - De-switch the Spec047V1Protocol / Spec047ExternalProof selftest fixtures. - Delete V1FeatureFlagTests, TypeRegistryTests.Override_Builtin, and the redundant TextBox echo-stranding fixture; migrate the echo-stranding fixtures and Ports/*PortTests to `new Reconciler()` against the built-in descriptors; reshape V1OnRegistrationTests to the always-on registration contract. Perf / tooling: - Delete the A|B perf duplicates (StressPerf.ReactorV2, BlankReactorV2, PerfBench DescriptorVariantFactory) and tools/spec047-phase1-checkpoint; rename the ReactorV2 column to Reactor in the aggregator/slnx/scripts. Validation: core build = 0 err; xunit = 9128 pass / 0 fail; Echo + V1_* + Spec047ExternalProof_* selftests = 0 fail. Perf-project consolidation measurement is deferred to the ARM64 baseline machine (§4.9). Co-authored-by: Copilot <[email protected]> * spec-047 §4.7 — graduate + lock the public V1 author surface Phase 2 decided the V1 protocol is the production model and §4.5 deleted the legacy path, so the author surface is now stable/supported. Graduate it out of [Experimental] and confirm the external-assembly proof against the locked surface. - Remove all 157 [Experimental("REACTOR_V1_PREVIEW")] attributes across 110 src/Reactor files (public author surface — IElementHandler, MountContext/ UpdateContext, ReactorBinding(<T>), ControlDescriptor + builders, Register{Type,Handler}, pool policy, WriteSuppressed, AddRawRoutedHandler — and the internal handlers/descriptors that carried it). - Drop the now-dead REACTOR_V1_PREVIEW NoWarn from all six csprojs (Reactor, Reactor.Tests, Reactor.AppTests.Host, PerfBench.ControlModel, and both external_proof projects). The external_proof control now consumes the public surface with NO experimental opt-in — the strongest form of the proof. KD-4 (external typed-event surface) was already shipped: the external MarqueeControl wires a typed CLR event via the public MountContext.BindFor -> ReactorBinding<TElement>.OnCustomEvent<TArgs> path with only a plain ProjectReference (no InternalsVisibleTo). ReactorBinding<TElement>'s ctor stays internal but is reached through public BindFor, so it is not a gap. Validation: core build = 0 err; Reactor.External.TestControl builds clean (0 err, no IL trim/AOT warnings, PublishTrimmed+IsAotCompatible on, no opt-in); xunit = 9128 pass / 0 fail; all six Spec047ExternalProof_Marquee_* selftests green; PerfBench.ControlModel + AppTests.Host build clean without the NoWarn. Co-authored-by: Copilot <[email protected]> * spec-047 §4.2 (part A): delete orphaned legacy value-control handler bodies §4.5 deleted the legacy reconciler dispatch switch arms but left the value- control MountXxx/UpdateXxx handler method bodies behind as unreachable dead code (controls now dispatch through the V1 descriptor system). Remove them: Mount.cs: MountToggleSplitButton, MountPasswordBox, MountNumberBox, MountAutoSuggestBox, MountRadioButton, MountRadioButtons, MountComboBox, MountSlider, MountRatingControl, MountColorPicker, MountCalendarDatePicker, MountDatePicker, MountTimePicker, plus the now-dead helpers EnsureToggleSwitchWiring and (Reconciler's own) EnsureTextBoxWiring. Update.cs: UpdateToggleSplitButton, UpdateTextBox, UpdatePasswordBox, UpdateNumberBox, UpdateAutoSuggestBox, UpdateRadioButton, UpdateToggleSwitch, UpdateRatingControl, UpdateColorPicker, UpdateCalendarDatePicker, UpdateDatePicker, UpdateTimePicker, UpdateRadioButtons, UpdateComboBox, UpdateCalendarView. Preserved live islands interleaved among these: MountCheckBox/UpdateCheckBox (Path-B via CheckBoxHandler), the NumberBox immediate-mode chain (NumberBoxImmediateTextChanged/...LoadedEnsureImmediateTextBox/ EnsureNumberBoxImmediateTextBoxWiring/HandleNumberBoxImmediateTextChanged plus the CanSynchronize/AreNumberBoxValuesEquivalent helpers, all live via NumberBoxDescriptor.Immediate), and SyncSelectedDates (reflection-probed). This finishes the §4.5 dead-code sweep and cuts ChangeEchoSuppressor references from ~55 to 16 (the remaining live descriptor paths are migrated in §4.2 part B). No behavior change (deleted code was unreachable). Validation: core build 0 err; xunit 9128 pass / 0 fail / 62 skip; selftests PrivMount/Echo/NumberBox/CheckBox all 0 failures. Co-authored-by: Copilot <[email protected]> * spec-047 §4.2: refresh echo-suppressor audit + defer part B with handoff The Phase-0 begin-suppress-audit.csv is stale (cites §4.5/§4.2A-deleted legacy line numbers). Add a refreshed, accurate live call-site inventory for the ChangeEchoSuppressor elimination surface and record the go/no-go decision. - New: docs/specs/047/audits/echo-suppressor-phase4-live-sites.md — the ~30 live echo sites (post-§4.2A), classified (general-controlled / coercion / float-precision / collection-batch / setter-scope / public-API), with the rationale for why full elimination (part B) is a dedicated, spec-author-involved effort rather than an autopilot pass: the counter is a causal token, value-compare is causally weaker (coincidental real-value events get swallowed), ApplySetters' EchoSuppressScopeDepth has no value to compare, and public WriteSuppressed carries no value/readback for external authors. New regression fixtures required first. - Task doc: progress log records §4.2 part A done (commit 8a67e34) and a "Deferred" block for §4.2B / §4.3 / §4.4 / §4.8 / §4.10 / §4.9 with reasons; §4.2 section gets a status note pointing at the refreshed inventory. Also corrects the §4.5 log's "0 orphaned private members remain" over-claim (§4.2A removed ~28 it missed). Co-authored-by: Copilot <[email protected]> * spec-047 §8: value-diff echo suppression PoC on the ControlledPropEntry path Per product decision, prove out the spec §8 "diff/value-compare" echo suppression on the descriptor controlled fast path, keeping the causal counter as the retained fallback everywhere else (so reverting this one path is trivial if the diff approach causes issues in practice). ControlledPropEntry (src/Reactor/Core/V1Protocol/Descriptor/PropEntry.cs) — the generic two-way `.Controlled(...)` entry used by ~10 controls (RadioButton, ToggleSplitButton, ToggleSwitch, RatingControl, ColorPicker, the date/time pickers, etc.) — now suppresses its own programmatic-write echo by VALUE: - Update arms a per-control ExpectedEcho on the DescriptorControlledPayload (value + comparer) instead of bumping ChangeEchoSuppressor's counter, then writes. Arming is gated on a non-null callback AND an existing payload (no subscription => no echo to suppress), via the new non-allocating Reconciler.TryGetControlEventPayload<T>. - The change-event trampoline drops the single event whose readback equals the armed value (one-shot), then clears the arm. A mismatch means a real user change superseded the pending write -> clear and fire the callback. - ChangeEchoSuppressor.ShouldSuppress is still honored first (external WriteSuppressed tokens + the ApplySetters setter scope, which carry no value); a matching pending arm is drained on that branch too so it cannot strand and swallow a later real interaction (rubber-duck + code-review blocking finding). - Mount clears any stale arm left on a pooled payload (KD-3: payload survives rent/return). The counter (ChangeEchoSuppressor / EchoSuppressCount / EchoSuppressScopeDepth / public ReactorBinding.WriteSuppressed) is unchanged and remains the live mechanism for the hand-coded / coercing / collection entries, the Slider/TextBox/ToggleSwitch handlers, CheckBox, NumberBox-immediate, the CalendarView shim, the setter scope, and external authors. The PoC's synchronous-change-event assumption (and the migrate-back path) is documented in-code on DescriptorControlledPayload. New selftest fixtures (Spec047ValueDiffEchoFixtures) lock the value-diff DRIFT path the existing Echo_*_RealInput stranding fixtures don't cover: a real programmatic update lands on the control, does NOT echo into the callback, and a subsequent real interaction still fires. Validation (x64): core build 0 err; xunit 9128 pass / 0 fail; selftests --filter Echo (no-echo + stranding), ValueDiff (new drift), SettersScope (setter scope), Spec047ExternalProof (public WriteSuppressed counter) all 0 failures. Co-authored-by: Copilot <[email protected]> * spec-047 §8: migrate TextBox echo suppression to value-diff (PoC) Extends the §8 value-diff echo-suppression proof-of-concept from the ControlledPropEntry fast path to the live TextBox path (TextBoxHandler, the registered handler — the descriptor is an unregistered proof-point). The legacy counter (ChangeEchoSuppressor.WriteSuppressed / ShouldSuppress) is replaced for TextBoxHandler's controlled `Text` writes by arming an ExpectedEchoText on the per-control TextBoxEventPayload: the TextChanged trampoline drops the single event whose readback matches (then clears the one-shot arm). The arm is left pending after the write — like the counter, which leaves its suppression elevated for a possibly-deferred TextChanged. Stale arms are cleared on the next Mount (pool reuse). The counter is retained for the paths it still owns: external public ReactorBinding.WriteSuppressed and the ApplySetters setter-scope. The trampoline checks ShouldSuppress first (and drains a matching arm on that branch so a counter-suppressed echo can't strand the arm), then value-diff. Arming is gated on a TextChanged trampoline being wired now OR about to be wired this Update (newEl.OnChanged != null) — EnsureTextBoxWiring runs at the end of Update, so a null->non-null OnChanged transition combined with a value change still arms (creating the payload if needed) and the trampoline goes live before any deferred echo. This preserves the legacy counter's subscription-timing-independent suppression and avoids stranding a SelectionChanged-only TextBox. Accepted PoC tradeoff: value-diff only drops on an exact readback match, so a write WinUI coerces (e.g. single-line stripping \r\n) surfaces as a real change rather than being dropped. Documented in-code with a migrate-back path to the counter. Selftest fixtures added (Spec047ValueDiffEchoFixtures): ValueDiff_TextBox_Drift, _SnapBack, _Transition. Validated (x64): core build clean; xunit 9128/0; selftests Echo + ValueDiff + SettersScope 0 failures (incl. EchoSuppress_TextBox_*); DataGrid E2E (click cell -> type -> commit) + EventHandler TextBox keydown E2E passed. Co-authored-by: Copilot <[email protected]> * spec-047 §8: migrate safe echo-suppression paths to value-diff (hybrid) Migrate the synchronous, exact-comparable, single-controlled-value round-trips off the causal ChangeEchoSuppressor counter onto a value-diff arm, while RETAINING the counter as the documented fallback for paths value-comparison cannot model. End state is an intentional hybrid (no ReactorState byte win — adds one ref field — chosen for correctness/self-healing on migrated paths). Shared infra: - ReactorState.PendingEchoMatch (one-shot Func<object?,bool>?), reset at the same 3 sites as the counter (ClearCurrentEventHandlers, DetachReactorState, pool-return). - ChangeEchoSuppressor.ArmExpectedEcho / ClearExpectedEcho / ShouldSuppressEcho. Counter/scope wins first (external WriteSuppressed + ApplySetters carry no expected value); else the one-shot value predicate is consumed. - HandCodedControlledPropEntry opt-in `valueDiffEcho` + ControlDescriptor builder param: Update arms the expected echo then writes bare; the per- descriptor trampoline calls ShouldSuppressEcho(ctrl, readback). Migrated (valueDiffEcho / ShouldSuppressEcho): ComboBox, FlipView, GridView, ListBox, Pivot, PipsPager, RadioButtons, SelectorBar, TabView, TemplatedFlipView descriptors + ToggleSwitchHandler. (TextBoxHandler / ControlledPropEntry were already value-diff via their own payload arm.) Retained on the counter (rationale in spec 8.3): Slider/NumberBox doubles, NumberBox coercion, CalendarView collection, AutoSuggest/Password/RichEdit strings, Expander, CheckBox path-B, ApplySetters scope, public WriteSuppressed. Key insight: WinUI selection (SelectionChanged) and Toggled fire SYNCHRONOUSLY inside the property write (unlike deferred TextBox.TextChanged), so no arm-ahead-of-wiring is needed; a null->non-null transition simply produces no echo before the trampoline subscribes. Code-review-driven strand fixes: - ShouldSuppressEcho clears PendingEchoMatch UNCONDITIONALLY in the counter branch (safe: only synchronous controls use this arm; deferred TextBox uses a separate HasExpectedEcho payload arm), preventing a stranded arm from swallowing a later coincidental real event. - HandCodedControlledPropEntry.Update clears the arm after a guarded/coerced no-op write (post-write readback != nv) so the never-fired echo cannot strand. Docs: spec §8.3 (new) documents the hybrid + retained-counter rationale and supersedes the wholesale-deletion plan; task-doc progress log records part B'. Tests: new ValueDiff_ComboBox_Drift, ValueDiff_ToggleSwitch_Drift, and ValueDiff_GridView_GuardedNoOpStrand selftest fixtures. Validated x64: core build 0 err; xunit 9128/0; ValueDiff + Echo + migrated-control selftests 0 fail; DataGrid E2E pass. Co-authored-by: Copilot <[email protected]> * docs(spec-047 §4.2): record value-diff hybrid (part B') in phase-4 task doc Update the §4.2 section of the phase-4 task doc to reflect the value-diff echo migration that landed in c5c1399: - New "Part B'" status block + checked-off checklist for the shared value-diff arm, the migrated descriptors/handler, the strand-safety fixes, and the new regression fixtures. - Mark the original "delete + tolerance metadata + ColorPicker shim" plan (now "Part B") as DEFERRED and SUPERSEDED by spec §8.3, with the counter-retained hybrid rationale; its full-elimination boxes stay unchecked. Co-authored-by: Copilot <[email protected]> * spec-047 §4.3: split EventHandlerState — routed family → ModifierEventHandlerState Carve the monolithic per-element EventHandlerState into the §9.2 shape: the WinUI true-routed-input family (pointer/key/tap/focus/sizechanged/ accesskey — 21 Current* + 20 trampolines) is renamed in place to ModifierEventHandlerState (lazy on ReactorState.Modifiers); control-intrinsic events move fully onto the already-shipped per-control ControlEventStateBox payloads. - Delete dead legacy Image/ScrollViewer/ScrollView Mount/Update/Ensure bodies (the registered descriptors own their event wiring) + their 5 EHS trampoline fields. Delete 3 orphaned EHS fields (ToggleSwitchToggled/TextBoxTextChanged/ TextBoxSelectionChanged — referenced only in the struct def). - Migrate the 2 live control-intrinsic paths off the shared struct onto ControlEventStateBox payloads: Button.Click → ButtonEventPayload.ClickTrampoline and NumberBox immediate-mode wiring flag → NumberBoxEventPayload.ImmediateInnerWired. Both resolve the same native-DO-keyed ReactorState, so the issue #114/#86 shared-trampoline dedup invariant is preserved; trampolines keep reading the live element via GetElementTag (CurrentClick untouched — it is preserved across pool return and must not stash a per-owner delegate). - Rename EventHandlerState→ModifierEventHandlerState, ReactorState.Events→Modifiers, GetOrCreateEventState→GetOrCreateModifierState across all callers; refresh the 5 <see cref> doc references. - Correct the stale ControlEventStateBox/payload comments that claimed pool reset clears ControlEventState on return — it is PRESERVED across rent/return (#114), dropped only on full detach. Validation (x64): core build 0 err; xunit 9128 pass / 0 fail; Button / NumberBox / Image / Scroll / Pool / EventHandler selftests 0 fail. M10/M11 byte measurement deferred to the ARM64 baseline machine (§4.9); the §9.2 pool-lifecycle hazard fixtures land next. Co-authored-by: Copilot <[email protected]> * spec-047 §4.3: add §9.2 event-state-split pool-lifecycle hazard fixtures Lock the post-split contract with AppTests.Host self-test fixtures (Spec047EventStateSplitFixtures.cs, registered in SelfTestFixtureRegistry): - NoDuplicateSubscriptionAcrossPoolReuse — issue #114 guard: rent→fire→return→ re-rent→fire, the preserved ControlEventState trampoline fires the LIVE element exactly once (never double-subscribes). - HandlerTypeMismatchResetsBox — the ControlEventStateBox HandlerType discriminator deterministically replaces the box on type mismatch (no InvalidCastException); doubles as the hot-reload type-identity proxy. - DualReturnIdempotent — returning the same control twice is idempotent; re-rent still fires exactly once. - ModifierStateLazyForIntrinsicOnly — §9.4 alloc-shape proxy for the ARM64-blocked M10/M11 byte measurement: an intrinsic-only control leaves ReactorState.Modifiers null while ControlEventState is allocated; a routed-modifier control allocates Modifiers. - AddRawRoutedHandler_HandledEventsToo — the §9.5/Q11 escape hatch is intact on Mount/UpdateContext and independent of the split. The live "Handled child → parent still fires" leg is a documented TAP SKIP (WinUI 3 cannot synthesize a KeyRoutedEventArgs / RaiseEvent an input event headlessly) — covered by the Appium E2E KeyDownTest. Validation (x64): host build 0 err; EventStateSplit / Pool / EventHandler selftests 0 failures. Co-authored-by: Copilot <[email protected]> * docs(spec-047 §4.3): check off EventHandlerState-split task boxes + progress log Mark all §4.3 task-doc checkboxes done (the monolith is gone; control-intrinsic events fully on ControlEventStateBox payloads; routed family renamed to ModifierEventHandlerState; §9.2 hazard fixtures landed). M10/M11 byte/frequency measurement noted ARM64-deferred to §4.9; alloc-shape asserted via selftest in this x64 env. Add the §4.3 progress-log entry. Co-authored-by: Copilot <[email protected]> * spec-047 §4.4: bucket the Element base into ElementExtras + land §11.6 byte-gate constants Mirror the proven spec-034 ElementModifiers shim-bucket pattern: move the 14 cross-cutting nullable Element base fields (Attached, ImplicitTransitions, ThemeTransitions, ThemeBindings, LayoutAnimation, AnimationConfig, ElementTransition, InteractionStates, StaggerConfig, KeyframeAnimations, ScrollAnimation, ConnectedAnimationKey, ResourceOverrides, ContextValues) into a single nullable value-equality sub-record `ElementExtras`, exposed via one `Element.Extensions` slot. Each field name survives as a public get/init shim (get => Extensions?.X; init => copy-on-write into Extensions), so in the lean case (Extensions == null) the base carries only Key/Modifiers/Extensions — the §11.7 byte win — while all ~180 existing readers and `with`-expression writers (including the read-then-write composites in ElementExtensions.cs) compile and behave unchanged. Named ElementExtras to avoid the existing ElementExtensions static class. - Add `Extensions is null && b.Extensions is null` fast-path in ShallowEquals so the common no-Extras element skips the three structural (Attached/ThemeBindings/ ContextValues) compares in the hot reconcile diff path; update the CanSkipUpdate/ShallowEquals invariant doc. Record value-equality is preserved (the 14 move into the value-equality ElementExtras; the reconciler diffs via the structural helpers, not Element.Equals). - Land the §11.6 hard byte-gate TARGET constants (PerformanceBudgets.cs): M1 ≤407 / M2 ≤1520 / M3 ≤19200 (measured baselines 1018/~3800/~48000 ×0.4). The gate MEASUREMENT/enforcement is ARM64-baseline-blocked → deferred to §4.9. Validation (x64): core build 0 err; xunit 9128 pass / 0 fail (incl. ElementModifiersBucketTests); Animation/Transition/Theme/Context/Attached/Stagger/ Keyframe/Scroll/ConnectedAnimation/Resource selftests 0 fail. Only Element.cs + the new PerformanceBudgets.cs changed. Co-authored-by: Copilot <[email protected]> * docs(spec-047 §4.4): check off bucketed-Element-base task boxes + progress log Mark the bucketing + reader/writer-migration boxes done (ElementExtras shim bucket; zero call-site edits; PerformanceBudgets §11.6 target constants landed). The byte-gate enforcement/measurement boxes stay open — ARM64-baseline-blocked, deferred to §4.9. Add the §4.4 progress-log entry. Co-authored-by: Copilot <[email protected]> * spec-047 §4.8: document the final author-facing surface (stable, post-split) Promote the V1 control-authoring guide out of "preview/provisional" and bring it in line with the post-Phase-4 reality (hand-maintained pages — extensibility- preview.md has no .md.dt template; filename kept to preserve inbound spec links). docs/guide/extensibility-preview.md: - Drop the [Experimental]/REACTOR_V1_PREVIEW/breaking-change banner; mark the surface stable. Replace "Enabling the V1 path / off by default" with a "Dispatch order" section (V1 registry → _typeRegistry → composition-primitive switch; no flag, no legacy MountXxx fallthrough). - Correct the pool-reset enumeration: ControlEventState is PRESERVED across rent/return (#114), not cleared — trampolines stay subscribed and read the live tag; dropped only on full detach / replaced on HandlerType mismatch. The shared modifier state is ModifierEventHandlerState (ReactorState.Modifiers, lazy), cleared via ClearCurrentHandlers. - Correct the per-control event-state section: EventHandlerState was split into ModifierEventHandlerState + per-control ControlEventStateBox (§9.2) — done, not "Phase 3/4". - Rewrite WriteSuppressed to the §8.3 hybrid (value-diff for synchronous single-value controls + retained suppress-counter fallback; signature stable). - Replace the children-strategy table with the final 10-strategy set; drop the Phase-status column. Drop the "descriptor authoring = Phase 2 gate" item and the NoWarn REACTOR_V1_PREVIEW checklist step (plain ProjectReference, no IVT/opt-in). - Add a "Choosing an authoring shape (decision tree)" section (spec §6.1.1): descriptor prop/engine shapes vs hand-coded IElementHandler, the children-strategy picker, echo + pool-policy notes. AGENTS.md: - Rewrite "Adding a new WinUI control" to the V1 descriptor path (Element record → ControlDescriptor/IElementHandler → RegisterV1BuiltInHandlers → selftest). - Rewrite "Echo suppression for value controls" to the §8.3 hybrid (ChangeEchoSuppressor retained as the counter fallback; authors use WriteSuppressed/.Controlled/valueDiffEcho). - Update the per-element-state line to ModifierEventHandlerState + ControlEventStateBox. Docs-only; mur not available in this env so no generated pages were recompiled. Co-authored-by: Copilot <[email protected]> * docs(spec-047 §4.8): check off final-documentation task boxes + progress log Mark all §4.8 boxes done (extensibility guide promoted to stable; §6.1.1 decision tree added; AGENTS.md updated to the V1 descriptor model + §8.3 echo hybrid + ModifierEventHandlerState/ControlEventStateBox). The generated-pages box is N/A in this env (mur unavailable; the edited page is hand-maintained). Note: the task's "ChangeEchoSuppressor is deleted" premise was corrected to the settled hybrid (retained). Add the §4.8 progress-log entry. Co-authored-by: Copilot <[email protected]> * docs(spec-047 §4.9): record perf-ratification handoff (ARM64-baseline-blocked) §4.9 is entirely a measurement/ratification gate on LAPTOP-4MEP83VI and is not executable in the x64 dev environment. Annotate the section with a clear handoff: all code the gates measure is already landed (§11.6 target constants §4.4, single-Reactor perf-project consolidation §4.6, EHS split §4.3, bucketed Element base §4.4, AOT-clean external proof + CI AOT job §4.7); the KD-3 M1 binder-check fold is deliberately NOT applied (measurement-gated, and prior related micro-opts were net-negative). Boxes stay unchecked until the baseline capture lands; added the baseline-operator runbook + progress-log entry. Co-authored-by: Copilot <[email protected]> * spec-047 §4.10: Phase 4 close-out — status, dead-code sweep, validation Final close-out of the Phase 4 V1-migration cleanup. - Status: marked the main tracker header + spec §14 "Phase 4 — cleanup" as code-complete — migration closed; V1 is the unconditional production path. Reconciled the exit-gate/cleanup wording against the settled outcomes: the "delete ChangeEchoSuppressor" item is superseded by the §8.3 value-diff/counter HYBRID (suppressor intentionally retained; WriteSuppressed signature unchanged), and the §11.6 byte-gate + ARM64 ratification are carved out as the only outstanding baseline-machine (LAPTOP-4MEP83VI) items. - Dead-code sweep: grep-clean across src + tests — no live UseV1Protocol / REACTOR_USE_V1_PROTOCOL / ReactorV2 / registerBuiltinHandlers / EventHandlerState (monolith); only historical comments remain. ChangeEchoSuppressor is retained by design (hybrid), so it is removed from the sweep list. - Tidied a stale PoolPolicyTests TODO: the real FrameworkElement rent/return reset contract is now covered by the §4.3 self-test fixtures; corrected its "ControlEventState cleared" wording to "preserved across rent/return (#114)". Validation (x64): full solution build (Reactor.slnx -p:Platform=x64) 0 err; full xunit 9128 pass / 0 fail; full selftest 0 fail modulo the known docking-family flakiness (DockHooks_* / SidePopup_*) that fails intermittently under full-suite headless load and passes deterministically when filtered (confirmed: both filters 0 failures; full-run count varied 7→6 across runs) — pre-existing, not a regression. Outstanding (handed off, baseline-machine-only): §4.9 ARM64 stable-AC perf ratification + §4.4 §11.6 hard byte-gate measurement/enforcement. Co-authored-by: Copilot <[email protected]> * spec-047 §4.10: address PR #455 CR feedback (echo-suppression + Element bucketing) CR item #1 (GridView/ListBox deferred-echo) — revert SelectedIndex to the causal counter (ShouldSuppress/WriteSuppressed; drop the §8 value-diff arm), restoring main's mechanism. Empirically probed on this box: post-realization SelectionChanged is synchronous (deferral is mount-only), the counter and the value-diff arm behave identically in every production-reachable path, and the guarded -1 no-op leaves the echo counter at 0 (no strand) so a later genuine deselect still fires. The counter gate suppresses the whole trampoline fire, so it also governs the multi-select snapshot OnSelectionChanged (CR #3) and the guarded-no-op self-clear concern is moot (CR #4). ComboBox/toggles/pickers keep the value-diff arm (synchronous by construction). Descriptor + fixture narration updated to match. CR item #2 (empty ElementExtras bucket) — normalize the 14 bucketed init shims via ElementExtras.IsEmpty + Element.NormalizeExtras so writing a bucketed field to null never materializes/keeps a non-null empty bucket. An empty bucket is not Equals to null, which otherwise broke record equality between an extras-free element and one with a field cleared to null. New ElementExtrasBucketTests. CR item #6 — make Element.Extensions setter internal to remove the initializer-ordering footgun from the public surface (no in-repo external writes; bucketed shim properties stay public). Nits — ComboBox stale ShouldSuppress doc; PerformanceBudgets §4.9 dead-code TODO; Reconciler ContinueDefaultTraversal cref namespace fix (clears the CS1574 warning); TabView pinnable-tab "not byte-identical" callout; ContentDialog OnClosed tag-routing follow-up note; §4.4 ElementExtras construction-cost note. Verified: core builds clean (ARM64 + x64), Reactor.Tests 9132 passed / 62 skip, selftest ValueDiff/Echo/ComboBox/GridView/ListBox/SelectionEvent/EventStateSplit fixtures all green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
Jun 2, 2026
Code-review findings (C:\temp\reactor-advanced-win2d-review.md): #1 HIGH — initially paused Win2DAnimatedCanvas can never resume Win2DAnimatedCanvasHandler.Mount wrote ctrl.Paused = el.IsPaused, but Update never writes Paused (intentional: Win2D-on-WinUI-3 game-thread park bug). An app mounted with isPaused:true could never unpause. Fixed: never touch ctrl.Paused at any stage; IsPaused gates the user's OnUpdate delegate via InvokeUpdate. New selftest fixture 'Win2D_AnimatedCanvas_InitialPausedResumes' locks in the invariant. #2 HIGH — unsynchronized Ref<T> across UI/game threads Rewrote UseDrawState XML doc to be honest: Ref<T> is a plain auto-property, has no memory barriers, does not protect compound mutations. New doc lists per-shape synchronization options (volatile, Interlocked, lock, producer/consumer queue). Updated win2d-canvas.md.dt threading section to match. Fixed the actual race in ParticleStorm: Burst is now a ConcurrentQueue<(x,y,n)> producer; ParticleField.Step drains the queue on the game thread BEFORE iterating the particle array. No more torn Particle structs from UI-thread mutation racing the game-thread loop. #3 MED — RedrawKey uses reference equality Win2DCanvasHandler diff was !ReferenceEquals; boxed ints differ across renders, so every parent re-render triggered a redundant Invalidate. Switched to !Equals. New selftest fixture 'Win2D_Canvas_SameRedrawKeyNoExtraDraws' verifies the no-op behavior. #4 MED — docs/sample reference nonexistent '.Of(...)' API Updated win2d-canvas.md.dt (4 occurrences), cheat-sheet.md.dt (1), samples/apps/particle-storm/README.md (1) to match the actual factory shape: Win2DCanvas(...) / Win2DAnimatedCanvas(...) / Win2DVirtualCanvas(...) via 'using static Microsoft.UI.Reactor.Advanced.Factories;'. Recompiled docs/guide/win2d-canvas.md and docs/guide/cheat-sheet.md. #5 MED — missing screenshot + placeholder perf Removed broken ../../samples/apps/particle-storm/screenshot.png reference from the Win2D guide template (this was the mkdocs --strict failure on the CI Docs build job). Toned down the 'canonical performance proof' claim — Particle Storm is now described as the 'canonical worked example' and the guide tells readers to capture their own FPS numbers on their own hardware. #6 MED — skipped placeholder tests Selftest coverage gap acknowledged. Added two new fixtures (above) to cover the two scenarios most affected by review bugs (#1 and #3). The headless xUnit placeholders for handler updates and device-loss remain skipped — those genuinely need live WinUI activation, which the AppTests.Host selftest tier provides. #7 LOW — silent catches in PackLocalCommand Replaced catch { /* best effort */ } with explicit Console.Error warnings (stale-package cleanup + HTTP-cache-clear paths). Pack-local still succeeds when cleanup fails, but the user sees why. CodeQL inline findings: - Win2DCanvasFixtures.WaitForCollectedOrDetached: removed GC.Collect() calls. Visual-tree detach check is the observable invariant; weak-ref is a secondary signal under normal GC, not a forced collection probe. - Win2DVirtualCanvasHandler.Update: replaced double != check with a SizesEqual helper using a 0.5 DIP epsilon (below display rounding, above float-precision noise from layout/devicescale math). - PackLocalCommand / TrimAssertions / threading test Path.Combine warnings: not addressed (low priority, all in test/CLI code; intent is clear and operands are repo-internal). CI failures (https://github.com/microsoft/microsoft-ui-reactor/actions/runs/26819092595, https://github.com/microsoft/microsoft-ui-reactor/actions/runs/26819092535): - Pack (x64 + arm64) — NU5026 'Reactor.Advanced.dll not found': the release workflow's 'dotnet build/pack' runs without -p:Platform, so MSBuild defaults to AnyCPU. Reactor.Advanced.csproj had Platforms='x64;ARM64' only (no AnyCPU). Added AnyCPU to match Reactor.csproj. Both Pack steps now resolve. - Docs build — mkdocs --strict failed on the broken screenshot link (review finding #5 above); removing the reference fixes it. Verification: - dotnet build Reactor.slnx -p:Platform=x64: clean (0/0). - dotnet test tests/Reactor.Advanced.Tests -p:Platform=x64: 27 passed. - Win2D selftests (JIT): 5 fixtures, 11/11 assertions green (added InitialPausedResumes + SameRedrawKeyNoExtraDraws). - mur docs compile --topic win2d-canvas/cheat-sheet: clean. Co-authored-by: Copilot <[email protected]>
Chris Anderson (codemonkeychris)
added a commit
that referenced
this pull request
Jun 2, 2026
* spec 053: Reactor.Advanced + Win2D canvas integration
Implements docs/specs/053-reactor-advanced-and-win2d-canvas.md across all
four phases (per the implementation tracker):
Phase 1 — Library + L0/L1
- src/Reactor.Advanced/: new sibling library, ProjectReference-only consumer
of Reactor core (no InternalsVisibleTo). Three element/handler triples
(Win2DCanvas / Win2DAnimatedCanvas / Win2DVirtualCanvas) plus modifiers
(ClearColor, Paused, TargetFps, Set) and three hooks (UseDrawState,
UseCanvasResources, UseDrawCommand).
- Per-library trim unit: Factories class with single static cctor registers
all three handlers. Authors consume via 'using static Microsoft.UI.Reactor
.Advanced.Factories;' alongside the core factories, calling factories by
their natural name (Win2DCanvas(...) etc.) — matching the in-tree DSL
pattern. Touching any factory roots all three; touching none strips all
three (verified by AOT trim probes).
- tests/Reactor.Advanced.Tests/: 27 passing, 4 skipped-covered-by-selftests.
- tests/aot_trim_proof/Reactor.AotHelloWorld.Advanced{,.Positive}{,.TrimAssertions}/:
negative (zero handlers when no canvas factory called) + positive
(handlers present when Win2DCanvas(...) is called) trim probes.
- mur pack-local now emits Microsoft.UI.Reactor.Advanced.{version}.nupkg
alongside the core package.
Phase 1 game-thread isolation fix
- Win2DAnimatedCanvas Update/Draw fire on Win2D's game thread, not the
WinUI dispatcher. Original Reactor binding path called DependencyProperty
APIs from the trampoline, producing RPC_E_WRONG_THREAD (0xC000027B with
WER P7=8001010e) at AOT-published startup. Fixed by subscribing Update/
Draw directly with a volatile per-control element holder and tracking
unsubscribe delegates for clean Unmount.
Phase 1 IsPaused workaround
- Writing CanvasAnimatedControl.Paused causes a known Win2D-on-WinUI-3 bug:
the game thread wakes for exactly one tick after Paused=false and then
parks permanently. Handler now never writes ctrl.Paused — IsPaused
instead gates the user's OnUpdate callback (simulation stops) while
leaving OnDraw active (last frame stays visible). Authors who want true
game-thread suspension can opt in via Setters.
Phase 2 — Particle Storm sample
- samples/apps/particle-storm/: ~50k-particle Win2D animated canvas demo
with chase/idle physics modes, cursor-driven gravity, periodic auto-
burst, speed-modulated palette, real wall-clock fps meter, AOT publish
gate. Sidebar is a Component<SidebarProps> per Reactor convention.
Phase 3 — Docs + selftests + skill
- docs/_pipeline/apps/win2d-canvas/ + templates/win2d-canvas.md.dt:
doc-app with 4 snippets + manifest, comprehensive-tier guide page.
- tests/Reactor.AppTests.Host/SelfTest/Fixtures/Win2DCanvasFixtures.cs:
three fixtures (manual/animated/virtual canvas mount), two-place
registration in SelfTestFixtureRegistry, all 7 assertions green under
both JIT and AOT.
- skills/advanced.md + plugins/reactor/skills/reactor-advanced/SKILL.md:
two-place agent skill install; bundled into the Advanced nupkg under
agentkit/skills/reactor-advanced.md.
Supporting changes outside spec-053 scope (justified):
- src/Reactor.Analyzers{,.Internal}/, Reactor.Localization.Generator/:
added TreatAsLocalProperty='PublishTrimmed' + PublishTrimmed=false so
Roslyn analyzer ProjectReferences don't inherit Reactor.Advanced's
PublishTrimmed=true (NETSDK1207 isolation).
- src/Reactor.Cli/Pack/PackLocalCommand.cs: added Advanced as a third
pack target.
Verification gates green:
- dotnet build Reactor.slnx -p:Platform=x64 — 0/0
- dotnet test tests/Reactor.Advanced.Tests -p:Platform=x64 — 27 passed
- Win2D selftests under JIT and AOT — 7/7 assertions each
- mur pack-local — produces 3 nupkgs side-by-side
- AOT trim probes — negative shows handlers stripped; positive shows present
- src/Reactor/ unchanged (per spec section 2 Goal 5)
Co-authored-by: Copilot <[email protected]>
* docs: recompile cheat-sheet, advanced, architecture-overview after spec-053 template edits
Phase 3's full mur docs compile run hung partway, so only docs/guide/win2d-canvas.md was
regenerated in the initial PR commit. The cheat-sheet / advanced / architecture-overview
templates had spec-053 cross-link edits that hadn't been compiled through. Running each
topic individually completed cleanly.
Co-authored-by: Copilot <[email protected]>
* spec 053: address review feedback + fix CI failures
Code-review findings (C:\temp\reactor-advanced-win2d-review.md):
#1 HIGH — initially paused Win2DAnimatedCanvas can never resume
Win2DAnimatedCanvasHandler.Mount wrote ctrl.Paused = el.IsPaused, but
Update never writes Paused (intentional: Win2D-on-WinUI-3 game-thread
park bug). An app mounted with isPaused:true could never unpause.
Fixed: never touch ctrl.Paused at any stage; IsPaused gates the user's
OnUpdate delegate via InvokeUpdate. New selftest fixture
'Win2D_AnimatedCanvas_InitialPausedResumes' locks in the invariant.
#2 HIGH — unsynchronized Ref<T> across UI/game threads
Rewrote UseDrawState XML doc to be honest: Ref<T> is a plain
auto-property, has no memory barriers, does not protect compound
mutations. New doc lists per-shape synchronization options (volatile,
Interlocked, lock, producer/consumer queue). Updated win2d-canvas.md.dt
threading section to match.
Fixed the actual race in ParticleStorm: Burst is now a
ConcurrentQueue<(x,y,n)> producer; ParticleField.Step drains the queue
on the game thread BEFORE iterating the particle array. No more torn
Particle structs from UI-thread mutation racing the game-thread loop.
#3 MED — RedrawKey uses reference equality
Win2DCanvasHandler diff was !ReferenceEquals; boxed ints differ across
renders, so every parent re-render triggered a redundant Invalidate.
Switched to !Equals. New selftest fixture
'Win2D_Canvas_SameRedrawKeyNoExtraDraws' verifies the no-op behavior.
#4 MED — docs/sample reference nonexistent '.Of(...)' API
Updated win2d-canvas.md.dt (4 occurrences), cheat-sheet.md.dt (1),
samples/apps/particle-storm/README.md (1) to match the actual factory
shape: Win2DCanvas(...) / Win2DAnimatedCanvas(...) / Win2DVirtualCanvas(...)
via 'using static Microsoft.UI.Reactor.Advanced.Factories;'.
Recompiled docs/guide/win2d-canvas.md and docs/guide/cheat-sheet.md.
#5 MED — missing screenshot + placeholder perf
Removed broken ../../samples/apps/particle-storm/screenshot.png
reference from the Win2D guide template (this was the mkdocs --strict
failure on the CI Docs build job). Toned down the 'canonical
performance proof' claim — Particle Storm is now described as the
'canonical worked example' and the guide tells readers to capture
their own FPS numbers on their own hardware.
#6 MED — skipped placeholder tests
Selftest coverage gap acknowledged. Added two new fixtures (above) to
cover the two scenarios most affected by review bugs (#1 and #3).
The headless xUnit placeholders for handler updates and device-loss
remain skipped — those genuinely need live WinUI activation, which
the AppTests.Host selftest tier provides.
#7 LOW — silent catches in PackLocalCommand
Replaced catch { /* best effort */ } with explicit Console.Error
warnings (stale-package cleanup + HTTP-cache-clear paths). Pack-local
still succeeds when cleanup fails, but the user sees why.
CodeQL inline findings:
- Win2DCanvasFixtures.WaitForCollectedOrDetached: removed GC.Collect()
calls. Visual-tree detach check is the observable invariant; weak-ref
is a secondary signal under normal GC, not a forced collection probe.
- Win2DVirtualCanvasHandler.Update: replaced double != check with a
SizesEqual helper using a 0.5 DIP epsilon (below display rounding,
above float-precision noise from layout/devicescale math).
- PackLocalCommand / TrimAssertions / threading test Path.Combine
warnings: not addressed (low priority, all in test/CLI code; intent
is clear and operands are repo-internal).
CI failures (https://github.com/microsoft/microsoft-ui-reactor/actions/runs/26819092595,
https://github.com/microsoft/microsoft-ui-reactor/actions/runs/26819092535):
- Pack (x64 + arm64) — NU5026 'Reactor.Advanced.dll not found': the
release workflow's 'dotnet build/pack' runs without -p:Platform, so
MSBuild defaults to AnyCPU. Reactor.Advanced.csproj had
Platforms='x64;ARM64' only (no AnyCPU). Added AnyCPU to match
Reactor.csproj. Both Pack steps now resolve.
- Docs build — mkdocs --strict failed on the broken screenshot link
(review finding #5 above); removing the reference fixes it.
Verification:
- dotnet build Reactor.slnx -p:Platform=x64: clean (0/0).
- dotnet test tests/Reactor.Advanced.Tests -p:Platform=x64: 27 passed.
- Win2D selftests (JIT): 5 fixtures, 11/11 assertions green
(added InitialPausedResumes + SameRedrawKeyNoExtraDraws).
- mur docs compile --topic win2d-canvas/cheat-sheet: clean.
Co-authored-by: Copilot <[email protected]>
* spec 053: fix release Pack CI + address new CR feedback (round 2)
CI fix — Pack (x64 + arm64) job:
Local repro on Reactor.slnx Release build:
src/Reactor/bin/Release/.../Reactor.dll present (AnyCPU)
src/Reactor/bin/ARM64/Release/.../Reactor.dll present (ARM64)
src/Reactor.Advanced/bin/ARM64/Release/.../*.dll present (ARM64)
src/Reactor.Advanced/bin/Release/.../*.dll MISSING
Reactor.csproj happens to land at bin/Release/ (AnyCPU) because its
analyzer ProjectReferences (netstandard2.0 AnyCPU) force an AnyCPU
sub-build. Reactor.Advanced has no AnyCPU-forcing consumer in the
slnx, so the no-Platform 'dotnet build Reactor.slnx --configuration
Release' only builds it for ARM64. The 'dotnet pack --no-build'
Advanced step then looks at bin/Release/ and fails with NU5026.
Added explicit 'Build Advanced (AnyCPU)' step before 'Pack Advanced
NuGet' in .github/workflows/release.yml, mirroring the Templates
pattern (which also passes -p:Platform=AnyCPU). The Pack step now
uses -p:Platform=AnyCPU for symmetry.
Verified locally that the produced nupkg contains
lib/net10.0-windows10.0.22621/Reactor.Advanced.dll plus .pri, .xml,
and the bundled agentkit/skills/reactor-advanced.md.
CR feedback (round 2, github-code-quality bot):
- src/Reactor.Cli/Pack/PackLocalCommand.cs:68 — Path.Combine
flagged. Switched to Path.Join (preserves segments even if a
later segment is rooted; relevant defense-in-depth here).
- src/Reactor.Cli/Pack/PackLocalCommand.cs:159 — generic catch in
DeleteStaleNupkg. Replaced with specific catches for IOException,
UnauthorizedAccessException, and System.Security.SecurityException
(the three real failure modes for File.Delete).
- src/Reactor.Advanced/Win2D/Hooks/UseCanvasResources.cs:69 —
generic 'catch when (disposed)' on the create() failure path.
Replaced with typed catches for OperationCanceledException and
ObjectDisposedException (the cancellation/teardown races that
actually happen here); other failures still propagate so real
create() bugs aren't masked.
- tests/aot_trim_proof/.../TrimAssertionTests.cs:56 — Path.Combine
on appDirectoryName. Added an IsPathRooted guard (returns
string.Empty on invalid input, matching the existing failure
behavior) and switched to Path.Join for the combine.
Verification:
- dotnet build Reactor.slnx -p:Platform=x64: clean (0/0).
- dotnet test tests/Reactor.Advanced.Tests -p:Platform=x64: 27 passed.
- Standalone pack verified: nupkg contains Reactor.Advanced.dll.
Co-authored-by: Copilot <[email protected]>
---------
Co-authored-by: Copilot <[email protected]>
This was referenced Jun 6, 2026
This was referenced Jun 23, 2026
Merged
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jun 26, 2026
Hot keyed list-diff path (grid steady state) allocated heavily and missed fast-paths even when keys were unchanged. Eliminate per-diff allocations and add the missing fast-path, preserving diff behavior exactly. ChildReconciler.cs: - Keyed prefix/suffix loops now take the Element.CanSkipUpdate early-exit that the positional path has, so stable keyed rows no longer re-diff every tick (#30); cache children.Count once instead of re-reading the COM IVector.get_Size per suffix iteration (#37). - Replace HashSet-returning ComputeLIS with allocation-free ComputeLISInto filling a pooled bool mask; pool tails/tailIndices/predecessors from ArrayPool (#31/#32). Keep a thin ComputeLIS(int[]) wrapper for tests. - Pool ReconcileKeyedMiddle's working arrays (ArrayPool) and the two key->index maps (re-entrancy-safe ThreadStatic dict pool); buffers cleared and returned on every exit (#33). - Filter: count-pass + single Element[] fill, no List+ToArray (#36). - GetKey: cache Type.Name via ConcurrentDictionary (#38). KeyedListDiff.cs: - Rent newKeys from ArrayPool<string>, threading explicit newCount (rented array may be larger); returned clearArray:true in a finally (#2). - Move the no-op (SequenceEqual) + empty/empty fast paths ABOVE the duplicate scan so the steady-state grid case never allocates/scans a dup set (#1). - Fold the churn-bailout decision into ApplyGeneral, computed from the same post-prefix/suffix scratch map the general walk builds (diff-range churn == full-range churn), removing the O(2n) null-marker pre-pass (#34). - Pool the doomed ReactorRow[] (ArrayPool, descending IComparer sort over [0,removes), cleared+returned) (#3). - Lazy-allocate movedRows only on an actual move under an ambient (#35). - In-place SyncLastKeysToSource instead of LastKeys Clear()+Add (#10). - HasDuplicates reuses state.Scratch (TryAdd) for 4+ keys instead of a fresh HashSet (#11); cached null-key diagnostic sample (#41). Tests: add pooling non-corruption coverage (rented-buffer-larger-than-count, interleaved independent states, randomized stress vs oracle with survivor identity, pooled doomed removes, churn with shared prefix+suffix, Scratch reuse for the dup scan) and ComputeLISInto bool-mask coverage. Full Reactor.Tests suite green (9693 passed); core lib Release build is warning-clean (AOT/trim). Closes #653 Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jun 27, 2026
…tests The keyed-middle reconciliation in ChildReconciler patched surviving controls by their FINAL panel index while the panel was only partially rearranged, so on reorders a survivor was patched against the wrong control (C1, CRITICAL): e.g. rotation [a,b,c,d]->[b,c,d,a] rendered "c" at slot 0 and scrambled keyed identity (focus/animation/state landed on the wrong row). A related stale keyToIndex (only the moved key was rewritten) left shifted siblings mis-indexed after an insert/move (H1). Fix: extract the index logic into RunKeyedMiddleCore<TSink> behind a struct-generic IKeyedMiddleSink seam (devirtualized, AOT-clean) and replace the left-to-right loop with the canonical right-to-left LIS walk. Each item is positioned immediately before its already-placed right neighbour; LIS members stay put and only out-of-LIS movers relocate (minimal moves). Every survivor is patched at its CURRENT live position, resolved from a pooled oldRelToPanel int[] that is mutated in lock-step with every Insert/Move so it stays exact -- fixing C1 and H1 together. The production RealKeyedMiddleSink drives the identical Mount/Move/ UpdateChild/Unmount/Replace + ambient enter/move behaviour as before. oldRelToPanel replaces the second pooled key->index dict (one fewer rented dict per call). Tests: - ChildReconcilerKeyedMiddleCoreTests (new): a headless SimKeyedMiddleSink drives the SAME RunKeyedMiddleCore over identity cells (exact production parity, no live-WinUI selftest wall), with a 4-invariant oracle (length, prefix/suffix untouched, per-slot identity+content, every patch hits its claimed survivor) across rotation, full reverse, scramble, block-swap, inserts/removes/duplicates and prefix/suffix offsets. A faithful pre-fix reproduction proves the rotation regression test has teeth (the buggy walk corrupts content[0] and mis-patches; the real core is clean). - KeyedListDiffPoolingTests: two GC.GetAllocatedBytesForCurrentThread budgets guarding the #1/#2/#11 pooling -- no-op steady-state diff is 0 B/iter and a 128-key reorder is 72 B/diff; reverting the pooling (a new string[128] + a 128-entry HashSet per diff) fails them. Diff correctness preserved; pooled buffers returned on every exit. Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jun 27, 2026
…ff (#657) * perf: eliminate per-diff allocations in ChildReconciler + KeyedListDiff Hot keyed list-diff path (grid steady state) allocated heavily and missed fast-paths even when keys were unchanged. Eliminate per-diff allocations and add the missing fast-path, preserving diff behavior exactly. ChildReconciler.cs: - Keyed prefix/suffix loops now take the Element.CanSkipUpdate early-exit that the positional path has, so stable keyed rows no longer re-diff every tick (#30); cache children.Count once instead of re-reading the COM IVector.get_Size per suffix iteration (#37). - Replace HashSet-returning ComputeLIS with allocation-free ComputeLISInto filling a pooled bool mask; pool tails/tailIndices/predecessors from ArrayPool (#31/#32). Keep a thin ComputeLIS(int[]) wrapper for tests. - Pool ReconcileKeyedMiddle's working arrays (ArrayPool) and the two key->index maps (re-entrancy-safe ThreadStatic dict pool); buffers cleared and returned on every exit (#33). - Filter: count-pass + single Element[] fill, no List+ToArray (#36). - GetKey: cache Type.Name via ConcurrentDictionary (#38). KeyedListDiff.cs: - Rent newKeys from ArrayPool<string>, threading explicit newCount (rented array may be larger); returned clearArray:true in a finally (#2). - Move the no-op (SequenceEqual) + empty/empty fast paths ABOVE the duplicate scan so the steady-state grid case never allocates/scans a dup set (#1). - Fold the churn-bailout decision into ApplyGeneral, computed from the same post-prefix/suffix scratch map the general walk builds (diff-range churn == full-range churn), removing the O(2n) null-marker pre-pass (#34). - Pool the doomed ReactorRow[] (ArrayPool, descending IComparer sort over [0,removes), cleared+returned) (#3). - Lazy-allocate movedRows only on an actual move under an ambient (#35). - In-place SyncLastKeysToSource instead of LastKeys Clear()+Add (#10). - HasDuplicates reuses state.Scratch (TryAdd) for 4+ keys instead of a fresh HashSet (#11); cached null-key diagnostic sample (#41). Tests: add pooling non-corruption coverage (rented-buffer-larger-than-count, interleaved independent states, randomized stress vs oracle with survivor identity, pooled doomed removes, churn with shared prefix+suffix, Scratch reuse for the dup scan) and ComputeLISInto bool-mask coverage. Full Reactor.Tests suite green (9693 passed); core lib Release build is warning-clean (AOT/trim). Closes #653 Co-authored-by: Copilot <[email protected]> * perf: address PR review on keyed-diff allocation fixes Review follow-ups on #657 (keyed list-diff allocation work): - ChildReconciler.ReconcileKeyedMiddle: return the pooled matched and inLis bool[] buffers with clearArray:false instead of true (Copilot review). Both are value-typed (no reference pinning) and have their used range fully (re)initialized before any read - matched via the Array.Clear on rent, inLis via ComputeLISInto leading clear - so the full-array wipe on return was avoidable O(rented-capacity) work on the hot path. Matches how the int[] newToOld already returns. Reference-typed pooled buffers (string[]/ReactorRow[] in KeyedListDiff) still clear. - Tests (ChildReconcilerLisIntoTests): replace the circular oracle that compared ComputeLISInto against ComputeLIS (now a thin wrapper over it) with an independent brute-force LIS-length DP that honors the -1 unmapped sentinel, asserting the mask marks a valid strictly-increasing subsequence of maximal length. - Tests (ChildReconcilerKeyedSkipTests, new): cover the #30 keyed CanSkipUpdate fast path - an identical keyed list skips every row with no ops and no child-control access, across repeated stable frames. Co-authored-by: Copilot <[email protected]> * fix: correct keyed-middle reorder identity (C1/H1) + reorder & alloc tests The keyed-middle reconciliation in ChildReconciler patched surviving controls by their FINAL panel index while the panel was only partially rearranged, so on reorders a survivor was patched against the wrong control (C1, CRITICAL): e.g. rotation [a,b,c,d]->[b,c,d,a] rendered "c" at slot 0 and scrambled keyed identity (focus/animation/state landed on the wrong row). A related stale keyToIndex (only the moved key was rewritten) left shifted siblings mis-indexed after an insert/move (H1). Fix: extract the index logic into RunKeyedMiddleCore<TSink> behind a struct-generic IKeyedMiddleSink seam (devirtualized, AOT-clean) and replace the left-to-right loop with the canonical right-to-left LIS walk. Each item is positioned immediately before its already-placed right neighbour; LIS members stay put and only out-of-LIS movers relocate (minimal moves). Every survivor is patched at its CURRENT live position, resolved from a pooled oldRelToPanel int[] that is mutated in lock-step with every Insert/Move so it stays exact -- fixing C1 and H1 together. The production RealKeyedMiddleSink drives the identical Mount/Move/ UpdateChild/Unmount/Replace + ambient enter/move behaviour as before. oldRelToPanel replaces the second pooled key->index dict (one fewer rented dict per call). Tests: - ChildReconcilerKeyedMiddleCoreTests (new): a headless SimKeyedMiddleSink drives the SAME RunKeyedMiddleCore over identity cells (exact production parity, no live-WinUI selftest wall), with a 4-invariant oracle (length, prefix/suffix untouched, per-slot identity+content, every patch hits its claimed survivor) across rotation, full reverse, scramble, block-swap, inserts/removes/duplicates and prefix/suffix offsets. A faithful pre-fix reproduction proves the rotation regression test has teeth (the buggy walk corrupts content[0] and mis-patches; the real core is clean). - KeyedListDiffPoolingTests: two GC.GetAllocatedBytesForCurrentThread budgets guarding the #1/#2/#11 pooling -- no-op steady-state diff is 0 B/iter and a 128-key reorder is 72 B/diff; reverting the pooling (a new string[128] + a 128-entry HashSet per diff) fails them. Diff correctness preserved; pooled buffers returned on every exit. Co-authored-by: Copilot <[email protected]> * fix: gate keyed no-op fast path on duplicate-free state + test hardening Address Copilot re-review of e664f9f. KeyedListDiff: the no-op fast path runs above the duplicate scan (#1), so an UNCHANGED list that already holds duplicate keys -- the state a prior duplicate bailout leaves behind, since ReactorListState.Reset preserves the dups in Source/LastKeys but collapses ByKey to first occurrences -- would match LastKeys and return Empty, silently skipping the duplicate bailout/diagnostic and leaving the diff in an invalid duplicate state. Gate the fast path on `state.ByKey.Count == oldCount`: true exactly for the duplicate-free steady state (allocation-free path preserved), false when dups were collapsed (re-takes the bailout). The check is O(1) and short-circuits before the O(n) SequenceEqualOrdinal, so the common unique-key path pays nothing. No-op steady-state allocation stays 0 B/iter. Tests: - KeyedListDiffTests: new Apply_Unchanged_Duplicate_List_Re_Bails_Instead_ Of_NoOp_FastPath -- proves an unchanged duplicate list re-bails; verified to FAIL without the guard (takes the no-op path and returns Empty). - ChildReconcilerLisIntoTests: strengthen the LIS oracle to assert selected indices are never the unmapped -1 sentinel (a buggy impl could swap a real member for a -1 and still satisfy strictly-increasing + length). - KeyedListDiffPoolingTests: drop the unused `using System.Buffers;` (fully-qualify the one ArrayPool cref) flagged by the reviewer. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jun 29, 2026
Addresses the dual-review findings on PR #750: #1 (BLOCKING, confirmed by RED test) theme propagation: the full-cache-hit early-out returned a reference-equal Children array, which makes the container ShallowEquals-skip its subtree (Element.cs ~622-699) so theme-sensitive descendants never re-apply their brush on a theme change. Gate the same-array early-out on the prior render having NO theme-sensitive cell (tracked as MemoCellsState.AnyThemeSensitive via ChildDiffHints.IsThemeSensitive). Theme- sensitive lists fall through to the fresh-array path (container recurses, theme re-applies); non-theme-sensitive lists keep the 632->32B win. New adjudicating tests in UseMemoCellsThemeSafetyTests. #2 (HIGH) predicate consistency: AllItemsEqual now uses object.Equals (exact match to the per-cell reuse loop) instead of EqualityComparer<T>.Default, so the early-out can't diverge for IEquatable<T> types. Dropped the UseMemoCellsByKey early-out entirely (its 'equal items imply identical keys' assumption + reused KeyToIndex was unsafe for impure key selectors); ByKey still reuses elements. #3 (MEDIUM) deps snapshot: restored deps.ToArray() on the deps-CHANGED store path (UseEffect/UseMemo/UseCallback) so an explicit mutable object[] a caller mutates can't corrupt the stored previous-deps. Runs only on deps-change, never the steady-state hot path, so the per-render win (call-site array) is unchanged. LOW delegate-kind guard: ValueHookState.SetterKind discriminates UseState vs UseReducer vs two-arg dispatch so an invalid same-slot swap producing a coincidentally same-typed delegate (Action<int>) re-materializes instead of reusing the wrong one. Measured (bytes/render): UseState/UseReducer/UsePersisted still 0; UseMemoCells cache-hit non-theme-sensitive ref still 32; theme-sensitive now 640 (correctly falls through). Full suite 9929 green; build 0/0. Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jun 29, 2026
Addresses the dual-review findings on PR #750: #1 (BLOCKING, confirmed by RED test) theme propagation: the full-cache-hit early-out returned a reference-equal Children array, which makes the container ShallowEquals-skip its subtree (Element.cs ~622-699) so theme-sensitive descendants never re-apply their brush on a theme change. Gate the same-array early-out on the prior render having NO theme-sensitive cell (tracked as MemoCellsState.AnyThemeSensitive via ChildDiffHints.IsThemeSensitive). Theme- sensitive lists fall through to the fresh-array path (container recurses, theme re-applies); non-theme-sensitive lists keep the 632->32B win. New adjudicating tests in UseMemoCellsThemeSafetyTests. #2 (HIGH) predicate consistency: AllItemsEqual now uses object.Equals (exact match to the per-cell reuse loop) instead of EqualityComparer<T>.Default, so the early-out can't diverge for IEquatable<T> types. Dropped the UseMemoCellsByKey early-out entirely (its 'equal items imply identical keys' assumption + reused KeyToIndex was unsafe for impure key selectors); ByKey still reuses elements. #3 (MEDIUM) deps snapshot: restored deps.ToArray() on the deps-CHANGED store path (UseEffect/UseMemo/UseCallback) so an explicit mutable object[] a caller mutates can't corrupt the stored previous-deps. Runs only on deps-change, never the steady-state hot path, so the per-render win (call-site array) is unchanged. LOW delegate-kind guard: ValueHookState.SetterKind discriminates UseState vs UseReducer vs two-arg dispatch so an invalid same-slot swap producing a coincidentally same-typed delegate (Action<int>) re-materializes instead of reusing the wrong one. Measured (bytes/render): UseState/UseReducer/UsePersisted still 0; UseMemoCells cache-hit non-theme-sensitive ref still 32; theme-sensitive now 640 (correctly falls through). Full suite 9929 green; build 0/0. Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jun 30, 2026
Addresses the dual-review findings on PR #750: #1 (BLOCKING, confirmed by RED test) theme propagation: the full-cache-hit early-out returned a reference-equal Children array, which makes the container ShallowEquals-skip its subtree (Element.cs ~622-699) so theme-sensitive descendants never re-apply their brush on a theme change. Gate the same-array early-out on the prior render having NO theme-sensitive cell (tracked as MemoCellsState.AnyThemeSensitive via ChildDiffHints.IsThemeSensitive). Theme- sensitive lists fall through to the fresh-array path (container recurses, theme re-applies); non-theme-sensitive lists keep the 632->32B win. New adjudicating tests in UseMemoCellsThemeSafetyTests. #2 (HIGH) predicate consistency: AllItemsEqual now uses object.Equals (exact match to the per-cell reuse loop) instead of EqualityComparer<T>.Default, so the early-out can't diverge for IEquatable<T> types. Dropped the UseMemoCellsByKey early-out entirely (its 'equal items imply identical keys' assumption + reused KeyToIndex was unsafe for impure key selectors); ByKey still reuses elements. #3 (MEDIUM) deps snapshot: restored deps.ToArray() on the deps-CHANGED store path (UseEffect/UseMemo/UseCallback) so an explicit mutable object[] a caller mutates can't corrupt the stored previous-deps. Runs only on deps-change, never the steady-state hot path, so the per-render win (call-site array) is unchanged. LOW delegate-kind guard: ValueHookState.SetterKind discriminates UseState vs UseReducer vs two-arg dispatch so an invalid same-slot swap producing a coincidentally same-typed delegate (Action<int>) re-materializes instead of reusing the wrong one. Measured (bytes/render): UseState/UseReducer/UsePersisted still 0; UseMemoCells cache-hit non-theme-sensitive ref still 32; theme-sensitive now 640 (correctly falls through). Full suite 9929 green; build 0/0. Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jun 30, 2026
…659) (#750) * perf(hooks): cache hook delegates + drop per-render hook allocations (#659) Cache ref-stable hook delegates on the (identity-stable) hook cell and add a full-reuse early-out to UseMemoCells, eliminating per-render allocations on the component render hot path. Measured via a headless GC-alloc harness (tests/Reactor.Tests/HookAllocBench.cs, env-gated REACTOR_ALLOC_BENCH): UseState x1/x4 96/384 -> 0 (#43 cached setter) UseReducer<T>/<S,A> 96/104 -> 0 (#44 cached updater/dispatch + latest-reducer cell) UsePersisted 96 -> 0 (#53 cached setter) UseCallback 152 -> 64 (#46 inlined, dropped () => callback wrapper) UseMemoCells cache-hit 632 -> 32 (#47 full-reuse early-out; residual is caller params array) Also: #42 lazy lock (no Lock unless threadSafe), #48 drop redundant deps .ToArray(), #50 _hooks initial capacity 8, #51 ContextHooks struct enumerator (no per-render heap iterator on the reconciler's per-component loop). Hook semantics preserved: call-order stable; cached delegates read live cell value and the current re-render callback; threadSafe path keeps its lock; two-arg reducer dispatch honors the latest render's reducer. UseMemoCells full cache-hit returns the prior children array (no rebuild). New regression tests in HookDelegateCachingTests. Co-authored-by: Copilot <[email protected]> * fix(hooks): harden UseMemoCells early-out + hook-cache per #659 review Addresses the dual-review findings on PR #750: #1 (BLOCKING, confirmed by RED test) theme propagation: the full-cache-hit early-out returned a reference-equal Children array, which makes the container ShallowEquals-skip its subtree (Element.cs ~622-699) so theme-sensitive descendants never re-apply their brush on a theme change. Gate the same-array early-out on the prior render having NO theme-sensitive cell (tracked as MemoCellsState.AnyThemeSensitive via ChildDiffHints.IsThemeSensitive). Theme- sensitive lists fall through to the fresh-array path (container recurses, theme re-applies); non-theme-sensitive lists keep the 632->32B win. New adjudicating tests in UseMemoCellsThemeSafetyTests. #2 (HIGH) predicate consistency: AllItemsEqual now uses object.Equals (exact match to the per-cell reuse loop) instead of EqualityComparer<T>.Default, so the early-out can't diverge for IEquatable<T> types. Dropped the UseMemoCellsByKey early-out entirely (its 'equal items imply identical keys' assumption + reused KeyToIndex was unsafe for impure key selectors); ByKey still reuses elements. #3 (MEDIUM) deps snapshot: restored deps.ToArray() on the deps-CHANGED store path (UseEffect/UseMemo/UseCallback) so an explicit mutable object[] a caller mutates can't corrupt the stored previous-deps. Runs only on deps-change, never the steady-state hot path, so the per-render win (call-site array) is unchanged. LOW delegate-kind guard: ValueHookState.SetterKind discriminates UseState vs UseReducer vs two-arg dispatch so an invalid same-slot swap producing a coincidentally same-typed delegate (Action<int>) re-materializes instead of reusing the wrong one. Measured (bytes/render): UseState/UseReducer/UsePersisted still 0; UseMemoCells cache-hit non-theme-sensitive ref still 32; theme-sensitive now 640 (correctly falls through). Full suite 9929 green; build 0/0. Co-authored-by: Copilot <[email protected]> * test(hooks): end-to-end theme-propagation guard for UseMemoCells early-out (#659) Adds UseMemoCells_BaseReThemeOnAncestorToggle selftest: a base UseMemoCells list of theme-sensitive cells under an ancestor RequestedTheme toggle, driven through a full value-equal cache hit, asserts the cell's themed Foreground re-resolves on the toggle (000000 Light -> FFFFFF Dark). Empirical result (verified by running this WITH and WITHOUT the AnyThemeSensitive gate): the themed Foreground re-resolves IDENTICALLY in both cases. A .Foreground(Theme.X) binding compiles to a {ThemeResource} Style setter that WinUI re-resolves natively on the cell's effective-theme change, independent of whether Reactor recurses or the container ShallowEquals-skips it — so the early-out's container skip does not strand a themed-Foreground descendant. The AnyThemeSensitive gate (5ead003) is retained as conservative insurance matching ChildDiffHints.IsThemeSensitive. (A ResourceOverride ThemeRef->concrete-brush does not re-resolve on this toggle, but it is wrong already at mount — a pre-existing GetEffectiveThemeName-during-reconcile issue unrelated to this PR — so it is not asserted here.) Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jul 1, 2026
…inary compat, Update-path tests MUST-FIX #1 (exception-safety): the Update shallow-skip arm set _ambientRequestedTheme before the method try, restoring it manually before the early return — an exception in the skip arm (SetElementTag / ApplyThemeBindings / ApplyResourceOverrides / RefreshGestureDragStateOnSkip) would bypass the restore and leak the ambient theme to callers/siblings. Now the field is written ONLY on the non-skip path INSIDE the try/finally (the skip arm reads the local effectiveTheme and never touches the field), so a leak is impossible by construction. Mount.cs field write likewise moved inside its try for consistency. MUST-FIX #2 (test coverage): add PostMountAncestorToggleReResolves — toggles an ancestor RequestedTheme on a LATER render and asserts a ThemeRef ResourceOverride re-resolves through BOTH Update arms (shallow-skip arm and full-update branch) via concrete (non-self-healing) brushes. Verified it genuinely guards the paths: forcing either call site to pass ElementTheme.Default turns both re-resolve asserts RED. RECOMMENDED (binary compat): restore the original 3-arg ApplyResourceOverrides public overload delegating to the 4-arg (now a required param), so precompiled REACTOR_V1_PREVIEW callers keep binding. Both reactor.api.txt copies regenerated. OPTIONAL: add SiblingSubtreesResolveIndependently — two sibling subtrees of different RequestedTheme each resolve their own brush, guarding the per-frame save/restore isolation. Validation: Reactor.Tests 9978/0 (incl. api-index up-to-date); Item1Mount (5 fixtures) + Issue675/StructuralSkip/UseMemoCells/ThemeBrush 0 failures on ARM64; Release core 0/0. Co-authored-by: Copilot App <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jul 1, 2026
…theme at mount (#771) * fix(reconciler): resolve ThemeRef ResourceOverrides against ancestor theme at mount A ThemeRef-backed ResourceOverride (.Resources(r => r.Set(key, Theme.Ref(...)))) resolved its concrete brush via ThemeRef.Resolve(key, fe). That walk needs the element parented; at mount the control is not yet in the visual tree, so an ancestor RequestedTheme is unreachable and resolution falls back to the app theme. A subtree with ancestor RequestedTheme=Dark under a Light app got the LIGHT brush. Thread the ancestor-aware effective theme top-down through Mount/Update (_ambientRequestedTheme: own RequestedTheme wins, else inherited), and pass it to ApplyResourceOverrides, which resolves via ThemeRef.Resolve(key, isDark) when an ambient theme is supplied. Falls back to fe-based resolution otherwise (direct callers / host-window themes outside the Reactor tree). Adds live selftests proving the fix (RED->GREEN): single-level + nested ancestor inheritance resolve the ancestor brush at mount; an element's own RequestedTheme still wins (regression guard). Co-authored-by: Copilot App <[email protected]> * fix(reconciler): address PR #771 review — leak-proof ambient theme, binary compat, Update-path tests MUST-FIX #1 (exception-safety): the Update shallow-skip arm set _ambientRequestedTheme before the method try, restoring it manually before the early return — an exception in the skip arm (SetElementTag / ApplyThemeBindings / ApplyResourceOverrides / RefreshGestureDragStateOnSkip) would bypass the restore and leak the ambient theme to callers/siblings. Now the field is written ONLY on the non-skip path INSIDE the try/finally (the skip arm reads the local effectiveTheme and never touches the field), so a leak is impossible by construction. Mount.cs field write likewise moved inside its try for consistency. MUST-FIX #2 (test coverage): add PostMountAncestorToggleReResolves — toggles an ancestor RequestedTheme on a LATER render and asserts a ThemeRef ResourceOverride re-resolves through BOTH Update arms (shallow-skip arm and full-update branch) via concrete (non-self-healing) brushes. Verified it genuinely guards the paths: forcing either call site to pass ElementTheme.Default turns both re-resolve asserts RED. RECOMMENDED (binary compat): restore the original 3-arg ApplyResourceOverrides public overload delegating to the 4-arg (now a required param), so precompiled REACTOR_V1_PREVIEW callers keep binding. Both reactor.api.txt copies regenerated. OPTIONAL: add SiblingSubtreesResolveIndependently — two sibling subtrees of different RequestedTheme each resolve their own brush, guarding the per-frame save/restore isolation. Validation: Reactor.Tests 9978/0 (incl. api-index up-to-date); Item1Mount (5 fixtures) + Issue675/StructuralSkip/UseMemoCells/ThemeBrush 0 failures on ARM64; Release core 0/0. Co-authored-by: Copilot App <[email protected]> --------- Co-authored-by: Copilot App <[email protected]>
This was referenced Jul 2, 2026
[Feature] In-build "did you mean" for mistyped Reactor factory names (CS0103) — REACTOR_DYM_003
#832
Closed
ReneeGA2020
pushed a commit
to ReneeGA2020/microsoft-ui-reactor
that referenced
this pull request
Jul 9, 2026
Add ControlledInputAnalyzer (Reactor.Hooks, Warning) + code fix. Flags a
controlled-input DSL factory call (TextBox, PasswordBox, NumberBox, Slider,
ComboBox, CheckBox, ToggleSwitch, RatingControl, CalendarDatePicker, …) whose
value argument is state-derived (identifier / member access) but whose change
callback is present yet inert — an empty-block lambda or a lambda that never
references its parameter. The control renders the value and silently drops the
user's edits (the XAML Mode=OneWay / read-it-back-via-x:Name habit).
Gating (spec 060 §4.1): fires only on an explicit state-derived value; a bare
TextBox("label") or an omitted callback is a legitimate read-only display and is
left alone. Factory shapes are non-uniform (ComboBox's value is arg microsoft#2, Slider's
callback is arg microsoft#4), so value/callback are matched by parameter type — the single
Optional<T> value param and the first delegate param — not by fixed position. An
explicit .IsReadOnly(true)/.IsReadOnly() already in the chain suppresses the rule.
Fix (TextBox, RatingControl only — the two controls with an IsReadOnly modifier):
wraps the call with .IsReadOnly(true) to make read-only intent explicit. Controls
without IsReadOnly are nudge-only. Never .IsEnabled(false) (destructive).
Adds the AnalyzerReleases.Unshipped row, the agent-kit cheat-table row, and the
analyzer-architecture template rules-table row. 20 analyzer/code-fix tests.
Co-authored-by: Copilot App <[email protected]>
This was referenced Aug 27, 2026
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Sep 1, 2026
1. Forced re-decode applied to the wrong arm
------------------------------------------------------------------
ResolveForResync used BitmapCreateOptions.IgnoreImageCache for every
image-backed projection. That is right for a declared icon -- ApplyChrome
re-runs spec.Icon.Apply(...) every time, so a declared file replaced in
place really does reach the caption and the title bar must follow. It is
wrong for the convention arm, whose caption serves a cached HICON from
TryApplyExeIconFallback forever: forcing a re-decode there burns a decode
on every unrelated WindowSpec update AND makes the title bar adopt bytes
the caption never sees.
Same rule as rounds 6 and 7, third arm: match the caching of whichever
window arm produced the value. ResolveForSpec now reports which arm won
via an out parameter rather than having the caller re-derive it -- deriving
the same fact a second way is how two copies drift apart.
TitleBarIcon_RefreshesReplacedFile still passes (before=32 after=1): it
declares its icon, so it stays on the arm that re-decodes.
2. A replacement title bar's reference was wiped by the old one's unmount
------------------------------------------------------------------
ChildReconciler's type-mismatch branch mounts the replacement subtree
before unmounting the old control. The new mount records
_titleBarIconControl; the old control's unmount then reached
ClearTitleBarControl, which cleared it unconditionally. That field is
written only at mount, so the live title bar became permanently unreachable
by the icon push.
Fixed by passing the unmounting control down and clearing only on a match.
Only that field is guarded -- the height fields keep their unconditional
semantics because ApplyTitleBarHeightOption re-establishes them on every
update, so a spurious clear there is self-healing. Mine is not.
The fixture took two attempts, and the first one is worth recording
------------------------------------------------------------------
I first wrote this as a KEYED replacement (.WithKey("bar-0") ->
"bar-1"). It passed under mutation -- i.e. it proved nothing. Instrumenting
the actual order showed why:
keyed: MARK #1 / CLEAR #1 / MARK #2 (unmount, then mount)
type mismatch: MARK #1 / MARK #2 / CLEAR #1 (mount, then unmount)
Only the second interleaving can strand the new reference. Reaching it
needs the child's element TYPE to change while the new subtree still
contains a TitleBar (TitleBar -> VStack(TitleBar)), because two TitleBars
at one position take CanUpdate and never unmount at all.
With the corrected shape the mutation reddens it:
# typeSwap: before=.../External.ico
# typeSwap: after=.../External.ico
not ok TitleBarIcon_TypeSwap_ReplacementStillTracked
That is the third time this session an oracle looked right, named the right
thing, and could not observe the failure. Renamed the fixture to
TitleBarIcon_TypeReplacement so nobody "simplifies" it back to a keyed
swap, and wrote the measured orders into the fixture comment.
Verified:
- 13799 unit tests, 0 failures
- 1498 selftest checks, 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host, Reactor.Tests
(caught a Release-only CS0419 ambiguous cref from the new overload)
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Sep 1, 2026
1. Forced re-decode applied to the wrong arm
------------------------------------------------------------------
ResolveForResync used BitmapCreateOptions.IgnoreImageCache for every
image-backed projection. That is right for a declared icon -- ApplyChrome
re-runs spec.Icon.Apply(...) every time, so a declared file replaced in
place really does reach the caption and the title bar must follow. It is
wrong for the convention arm, whose caption serves a cached HICON from
TryApplyExeIconFallback forever: forcing a re-decode there burns a decode
on every unrelated WindowSpec update AND makes the title bar adopt bytes
the caption never sees.
Same rule as rounds 6 and 7, third arm: match the caching of whichever
window arm produced the value. ResolveForSpec now reports which arm won
via an out parameter rather than having the caller re-derive it -- deriving
the same fact a second way is how two copies drift apart.
TitleBarIcon_RefreshesReplacedFile still passes (before=32 after=1): it
declares its icon, so it stays on the arm that re-decodes.
2. A replacement title bar's reference was wiped by the old one's unmount
------------------------------------------------------------------
ChildReconciler's type-mismatch branch mounts the replacement subtree
before unmounting the old control. The new mount records
_titleBarIconControl; the old control's unmount then reached
ClearTitleBarControl, which cleared it unconditionally. That field is
written only at mount, so the live title bar became permanently unreachable
by the icon push.
Fixed by passing the unmounting control down and clearing only on a match.
Only that field is guarded -- the height fields keep their unconditional
semantics because ApplyTitleBarHeightOption re-establishes them on every
update, so a spurious clear there is self-healing. Mine is not.
The fixture took two attempts, and the first one is worth recording
------------------------------------------------------------------
I first wrote this as a KEYED replacement (.WithKey("bar-0") ->
"bar-1"). It passed under mutation -- i.e. it proved nothing. Instrumenting
the actual order showed why:
keyed: MARK #1 / CLEAR #1 / MARK #2 (unmount, then mount)
type mismatch: MARK #1 / MARK #2 / CLEAR #1 (mount, then unmount)
Only the second interleaving can strand the new reference. Reaching it
needs the child's element TYPE to change while the new subtree still
contains a TitleBar (TitleBar -> VStack(TitleBar)), because two TitleBars
at one position take CanUpdate and never unmount at all.
With the corrected shape the mutation reddens it:
# typeSwap: before=.../External.ico
# typeSwap: after=.../External.ico
not ok TitleBarIcon_TypeSwap_ReplacementStillTracked
That is the third time this session an oracle looked right, named the right
thing, and could not observe the failure. Renamed the fixture to
TitleBarIcon_TypeReplacement so nobody "simplifies" it back to a keyed
swap, and wrote the measured orders into the fixture comment.
Verified:
- 13799 unit tests, 0 failures
- 1498 selftest checks, 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host, Reactor.Tests
(caught a Release-only CS0419 ambiguous cref from the new overload)
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Sep 1, 2026
* TitleBar defaults its icon from the window icon
A TitleBar with no declared icon showed nothing, even when the app had a
perfectly good icon, so every app had to restate it:
ReactorApp.Run<App>("MyApp", icon: WindowIcon.FromPath("Assets/AppIcon.ico"));
var titleBar = TitleBar("MyApp").Icon("ms-appx:///Assets/AppIcon.ico"); // redundant
The descriptor wrote IconSource unconditionally, so a null Icon wrote null.
It now projects through TitleBarIconDefault, which inherits the window's icon.
Precedence mirrors ReactorWindow.ApplyChrome -- declared WindowSpec.Icon
first, then the Assets\AppIcon.ico convention -- with one deliberate
divergence: the window chain's third stage yields a raw HICON from the
executable's PE resources, and a XAML IconSource needs an ImageSource, so
that stage is not inherited. A title bar with no resolvable icon degrades to
the previous behaviour rather than throwing or showing a broken image.
Rather than re-implement the chain, the resolution is shared: WindowIcon
gains TryResolvePath (extracted from Apply) and the Assets\AppIcon.ico probe
moves to AppIconConvention, so the title bar and the window caption cannot
disagree about which file an icon names.
Adds .NoIcon(), because record init properties make "never set an icon" and
"explicitly set none" indistinguishable, and those now mean opposite things.
Co-authored-by: Copilot App <[email protected]>
* Follow the window icon after it changes, not just at mount
PR review (correctness + alternative-solution, independently) caught that the
inherited icon was ambient window state laundered through an element diff.
OneWayPropEntry.Update decides whether to write by comparing get(oldElement)
with get(newElement). That works only for values derived from the element.
The inherited default is read from the owning window, so once WindowSpec.Icon
changed, both the old and the new element projected the *same new* value, the
comparison found them equal, and the control kept the previous icon forever --
while the window caption updated correctly.
The icon write is now an Imperative entry that compares against what was last
written to the control rather than against the previous element, and
ReactorWindow pushes a re-sync from ApplyChrome. That mirrors how the caption
height already reaches the mounted control via SyncTitleBarControlHeight.
Ownership is recorded in the per-control table rather than read back off the
element: Reconciler.SetElementTagIfNeeded leaves a callback-free TitleBar
untagged, so GetElementTag returns null for exactly the common case here.
Also from review:
- Isolate the tests that create and delete assets under AppContext.BaseDirectory
and mutate the process-wide app-root override. WindowIconResourceUriTests
writes into the same directory, so in parallel one class could delete a
fixture the other was using. Both now share a non-parallel collection.
- Extract ResolveForSpec(WindowSpec?) so precedence is testable without staging
a live window, and cover the two untested rules: the Embed guard, and a
declared icon that resolves to nothing falling through to the convention.
- Add selftests for the update path -- one proving the icon follows a window
icon change and clears when it is removed, one proving an explicit icon
survives it. Removing the window push reddens exactly those three checks.
- Call out the behaviour change for existing apps in the windows guide.
Declined: samples/Reactor.TestApp and samples/ReactorGallery still set
TitleBar.Icon explicitly. That remains a valid use of the API -- the feature
removes the obligation, not the option -- and neither sample sets a
WindowSpec.Icon, so dropping the line would silently re-point them at the
convention probe with no way to verify the result here.
Co-authored-by: Copilot App <[email protected]>
* Make the zero control's negative explicit, and stop cleanup masking failures
Multi-model cross-check flagged that the selftest scratch roots live under
Path.GetTempPath(). Declined the suggested relocation -- CreateScratchAppRoot
builds a freshly-created GUID-named directory so nothing can pre-exist in it,
and temp scratch roots are already how DevtoolsFixtures does this -- but the
underlying point stands: 'the convention probe finds nothing here' is the whole
basis for reading a null IconSource as evidence, so the zero control now
asserts it rather than implying it.
Also stop the unit tests' finally-block cleanup from throwing. Deleting a
scratch directory that is unexpectedly non-empty would replace the real
assertion failure with a cleanup error and hide what actually broke.
Co-authored-by: Copilot App <[email protected]>
* Resolve the pushed icon against the window's own spec, not ambient state
Review asked for a two-window arm, on the grounds that nothing distinguished
"read *the* window" from "read *this element's* window". Writing it found a
real bug -- in the push path rather than the pull path.
ReactorHost scopes ReactorApp.ActiveHostInternal around each *render*, with an
explicit save/restore whose own comment names the hazard ("a second window's
components observe the wrong owning window"). So the pull direction -- the
descriptor prop resolving through the ambient host during reconcile -- is
per-window correct.
ApplyChrome is not inside that scope. An app reaches it from
ReactorWindow.Update at any time, so with two windows open the ambient host is
routinely some *other* window. ResyncInheritedIcon called ResolveDefault(),
which reads ambient state, so updating a window that was not currently ambient
wrote the other window's icon into its title bar. It now takes the spec of the
window applying chrome.
The first version of the test did not catch this. Updating the *last-opened*
window passes either way: that window is already the ambient one, so a
spec-vs-ambient mix-up looks identical to correct behaviour. Only updating the
earlier window -- deliberately arranging for the applying window not to be the
ambient one -- distinguishes them. Verified by running the arm before the fix:
window A's title bar showed WindowC.ico, which is B's icon.
Also rename the two TryResolvePath failure logs, and the TryResolveExistingPath
probe log, off the "WindowIcon.Apply:" prefix. Reached from the title-bar path
they named a function that was not on the stack.
Co-authored-by: Copilot App <[email protected]>
* Compile the title-bar-icon example instead of hand-typing it
The Docs build job failed on InlineSnippetLedgerTests: the "Title bar icon"
section I added carried a raw ```csharp block, which nothing compiles and the
docs-snippet-gate cannot see, yet it reads as code to copy. That gate exists
because of #1139 -- hand-typed C# in the guides was rotting unnoticed.
Moved the example into the windows doc app as a `title-bar-icon` snippet,
following the shape of the neighbouring `window-icon` one: a static class
holding a non-executing Run, plus two components showing the inherited icon and
the .NoIcon() opt-out. The guide now references it by snippet id, so the code in
the docs is code the build compiles.
Reactor.DocPipeline.Tests: 435/435 (CI had 434/435).
Co-authored-by: Copilot App <[email protected]>
* Address code-quality findings in the new tests
Eight automated findings, all in test code. Seven taken as-is; one taken in
spirit but not to the letter.
Float equality (2). `part.ActualWidth == 0` is exact equality on a layout
double. Replaced both sites with a shared IconPartIsAbsentOrCollapsed helper
using a tolerance. The positive arms' oracle (ActualWidth > 0) is unchanged, so
the arms that have to discriminate still do.
Empty catch blocks (4) and the implicit null filter (1). Restructured CleanUp
around a BestEffortDelete helper: two non-empty catches that report the leaked
scratch path via Trace instead of four silent ones, and `.Where(d => d is not
null)` instead of filtering inside the loop. Dispose now routes through the same
helper rather than carrying its own pair of comment-only catches.
Generic catch (1) -- narrowed, but not as suggested. The tool proposed catching
COMException alone. The house comment this fixture inherited from
TitleBarHeightFixtures says the window may be "already closing, disposed, or
mid-native-teardown", and ObjectDisposedException / InvalidOperationException
are not COMExceptions -- narrowing that far would let a teardown fault escape
and replace a real assertion result, which is the exact failure the catch exists
to prevent. Narrowed instead to the set ReactorWindow.IsIconApplyFailure already
uses at the same boundary: COMException, InvalidOperationException,
ArgumentException. Narrower than Exception, and still covers every state the
comment names.
Reactor.Tests TitleBarIconDefaultTests 28/28; TitleBarIcon_ selftests 7 fixtures,
0 failures.
Co-authored-by: Copilot App <[email protected]>
* Stop the ambient push clobbering setter icons, and harden the URI build
Copilot review, six findings. Two were substantive.
**Setter precedence.** Raw `.Set(...)` setters run after every descriptor prop --
the documented "setters apply last / win" rule (spec 058,
DescriptorHandler.ApplySetters) -- so `.Set(b => b.IconSource = ...)` legitimately
owns the slot even when the element declares no Icon. The out-of-band resync from
ApplyChrome has no setters to replay and was writing IconSource unconditionally,
so any WindowSpec update clobbered the author's value.
AppliedIcon now records the IconSource instance it wrote, and ResyncInheritedIcon
skips when the control no longer carries it. Mirrors ReactorWindow's
_reactorAppliedIcon, which gates the window icon teardown the same way. Verified
by removing the guard: the setter's FontIconSource became an ImageIconSource on
window update while the mount positive control stayed green.
This is the third instance of one pattern -- the push path not honouring a rule
the pull path does. The first two were the OneWay ambient diff and the
wrong-window spec read.
**URI hardening.** WindowIcon.TryResolveExistingPath is permissive at one edge:
when its own probe throws it reports success with the original unverified source,
so a filesystem that merely refuses the probe never suppresses a working icon.
Sound for the window, whose consumer passes it to SetIcon inside a catch -- but
this projection runs inside a render, where an escaping UriFormatException would
take the frame down over a cosmetic icon. Guarded the projection with
Uri.TryCreate rather than tightening the shared resolver, which would change
window-icon behaviour that was verified behaviour-preserving. A path that cannot
form a URI degrades to no title-bar icon, matching the rest of the contract.
Also: the two shipped windowing authoring guides now document the inherited
default and .NoIcon(); removed a duplicated <summary> on ResolveDefault; and
retired two stale references to the OneWay diff that the Imperative rewrite
replaced.
TitleBarIconDefaultTests 28/28; TitleBarIcon_ selftests 8 fixtures, 0 failures;
Release clean for src/Reactor, Reactor.Tests and AppTests.Host.
Co-authored-by: Copilot App <[email protected]>
* Close three holes the review's suppressed comments found
The second Copilot review generated no new inline comments but suppressed five,
three of which were real.
**Cache staleness (2 of them).** Both resolved-path caches were write-once. The
window re-probes the filesystem on every ApplyChrome, so an asset appearing after
a cached miss updated the caption while the title bar stayed blank, and one
deleted after a cached hit left the title bar showing an icon the caption had
dropped. Exactly the divergence that sharing the resolver exists to prevent. The
out-of-band resync now invalidates first, so both surfaces probe in lockstep.
Resync only runs on a spec change, so this costs one or two File.Exists calls at
a moment the window is already making them.
**SuppressIcon ordering.** Both Icon and SuppressIcon are public init properties,
so a record initializer can set both, and Project checked Icon first -- rendering
an icon for an element whose SuppressIcon contract says the icon is suppressed
entirely. The fluent .Icon()/.NoIcon() pair normalizes the other field, so this
was only reachable by direct construction, but reachable is reachable. Checks
SuppressIcon first now.
**Null setters.** The identity guard added last round cannot see a setter that
wrote IconSource = null: when the projection was also null, the author's null and
ours are the same reference, so adding a WindowSpec.Icon overwrote it.
The first attempt at this -- skip the push for any setter-bearing element -- was
wrong, and the existing fixtures caught it: every BarComponent uses
.Set(b => capture = b), so that guard disabled inheritance wholesale and reddened
six checks across Follows and PerWindow. Narrowed to the genuinely ambiguous
window: decline only when the recorded source was null AND the element has
setters. A title bar caught by that still picks the icon up on its next render.
Also documented TryResolvePath's permissive edge on the method itself rather than
promising the stricter behaviour, since the title-bar projection already has to
defend against it.
Mutation-checked both the narrow guard and the earlier identity guard: each
reddens exactly its own arm. Reactor.Tests 31/31; selftests 1481 checks, 0
failures; 13,718 unit tests, 0 failures; Release clean.
Co-authored-by: Copilot App <[email protected]>
* Observe setter ownership instead of guessing it
Review round 3: two inline comments and one suppressed. Two were real; one was
a misdiagnosis I verified rather than accepted.
**Setter ownership is now ground truth.** Last round's guard used
`Setters.Length > 0` as a proxy for "a setter owns the icon slot". Wrong in both
directions, as the review said: `.Set(b => capture = b)` owns nothing, and a
setter added on a later render was invisible behind Apply's equality fast path
(the suppressed comment). Replaced with ObserveAfterSetters, called from the
reconciler's existing post-modifier hook in Reconciler.Mount/Update -- the first
point at which setters have actually run, so "did a setter take the slot?" is
observable rather than guessable. That also refreshes ownership on renders where
the icon write was skipped, closing the staleness hole.
One case stays ambiguous by construction and is now documented: a setter writing
IconSource = null when the projection was also null holds the same reference this
type wrote. The push may write over it once; the next render re-runs the setter,
the observation sees the divergence, and ownership latches permanently. The
NullSetter fixture asserts that whole sequence rather than a state the design
does not actually guarantee.
**The ShallowEquals finding was incorrect.** The claim was that
TitleBar("x") -> .NoIcon() takes Reconciler.Update's shallow-skip and strands the
old icon. It cannot: Element.ShallowEquals has no TitleBarElement arm, so it falls
to `_ => false` and a TitleBar pair never skips. The arm that does compare
TitleBar props is Element.OwnPropsEqual, a different method used only by the
devtools highlight overlay behind ReactorFeatureFlags.HighlightReconcileChanges.
Established by measurement, not reading: a fixture toggling a mounted title bar
between inherited, .NoIcon() and an explicit icon passes with the arm's icon
comparison removed, and a probe showed every conjunct of that arm true while
ShallowEquals returned false -- because the arm is in the other method. Both
invariants are now pinned by tests so a future arm added to ShallowEquals cannot
silently introduce the stranding the review was worried about.
Kept the icon comparison in OwnPropsEqual on its own merits: an icon change is a
change to the element's own WinUI-mapped props, which is exactly what that method
reports, so without it the overlay would leave a title bar unmarked on a render
that swapped its icon. Described accurately rather than as a skip-path fix.
13,720 unit tests, 0 failures; 1482 selftest checks, 0 failures; Release clean.
Co-authored-by: Copilot App <[email protected]>
* Let a setter-free render reclaim the icon slot, and log the change
Review round 4: three inline comments and one suppressed. One real bug, one
real omission, two stale comments I had written myself.
**Author ownership latched permanently.** Apply's equality fast path never
consulted AuthorOwned, so once ObserveAfterSetters marked a record as
setter-owned, a later render that removed `.Set(b => b.IconSource = ...)` hit
`last.ElementOwned == owned && last.Value == projected` and returned without
writing. Reactor never reclaimed the slot: the setter's icon stayed on the
control forever and ownership stayed latched. The fast path now bypasses for an
author-owned record. Cost is one redundant write per render while a setter owns
the slot -- the same write any descriptor prop under a setter already pays, since
the setter overwrites it immediately afterwards.
Getting the test right took two attempts, and the failure mode is worth
recording. The obvious ordering -- change the window icon, then drop the setter
-- passes with or without the fix, because the changed projection routes around
the fast path entirely. The bug is only reachable when the setter is dropped
with the projection unchanged, so the fixture now does exactly that and asserts
the reclaim, the subsequent re-tracking, and that re-adding the setter still
wins. Mutation-checked in the corrected ordering: the icon stays FontIconSource
after the drop.
**No CHANGELOG entry.** The contributor rules at the top of CHANGELOG.md require
significant or breaking changes under [Unreleased]. Added a Changed entry
describing the new inheritance and pointing apps that want a bare title bar at
.NoIcon(), plus an Added entry for .NoIcon() itself.
**Two stale comments, both mine.** ResyncInheritedIcon's remarks still said any
element carrying setters blocks the resync, which is the Setters.Length
behaviour that was rejected two rounds ago; it now describes observed IconSource
ownership and says explicitly not to reintroduce the count-based version. The
toggle fixture's header still asserted a ShallowEquals arm that does not exist;
it now describes what that fixture actually covers and points at the unit tests
that pin the invariant.
13,720 unit tests, 0 failures; 1482 selftest checks, 0 failures; Release clean.
Co-authored-by: Copilot App <[email protected]>
* Refresh the title-bar icon when the file behind it is replaced
Review round 5, one finding. ResyncInheritedIcon skipped the write whenever the
projected value compared equal -- but that value is a Uri, so it compares equal
even when the bytes at that path have been replaced. ApplyChrome reloads the
caption's HICON from disk on every apply, so replacing Assets\AppIcon.ico (or a
declared icon) in place and then updating the window refreshed the caption while
the title bar kept showing a stale decode. That is exactly the divergence
sharing the resolver exists to prevent.
The resync now always rebuilds. Two details worth stating:
* A plain BitmapImage is keyed on its URI, so re-creating one for a path whose
bytes changed can serve the previous decode. The resync path builds with
BitmapCreateOptions.IgnoreImageCache to force the re-read; normal renders go
through IconResolver and keep the cache.
* Only the out-of-band resync loses the equality skip, and it runs on spec
changes rather than per render. Apply's per-render fast path is untouched.
The oracle is decoded pixel size, not the URI -- the path is unchanged by
construction, so nothing else can tell the two states apart. The fixture swaps a
32x32 .ico for a 256x256 PNG under the same name and asserts the reading moves.
Mutation-checked: with the equality skip restored it reads 32 before and after.
The fixture also asserts its replacement asset exists before using it, which
earned its keep immediately -- the PNG ships under Microsoft.UI.Xaml\Assets, not
the host's own Assets, so the first version would otherwise have silently
degraded to a no-op instead of failing.
13,720 unit tests, 0 failures; 1483 selftest checks, 0 failures.
Co-authored-by: Copilot App <[email protected]>
* Make the replaced-file title bar fixture self-sufficient across tiers
#1155 added SelfTestFixtureRegistry.TierRequirements, and an undeclared
fixture defaults to SelfTestTier.Any -- so all eleven TitleBarIcon fixtures
run under MSIX package identity as well as unpackaged.
TitleBarIcon_RefreshesReplacedFile needed a second image with different
dimensions, and was reading one out of the WinUI framework package:
Microsoft.UI.Xaml\Assets\NoiseAsset_256x256_PNG.png
under AppContext.BaseDirectory. That path is a framework-package layout
detail, not something this host owns, and is not guaranteed to resolve when
BaseDirectory is the app's MSIX install root. The fixture asserts the file
exists before using it, so a miss would have failed the packaged tier rather
than skipping -- correct behaviour for an instrument, but a failure about
the environment rather than about the code under test.
Carry the bytes instead: a 1x1 PNG embedded as base64. WIC sniffs content
rather than trusting the .ico extension, so writing it over Swappable.ico
decodes fine and the reading moves 32 -> 1 instead of 32 -> 256. Nothing
outside the fixture is consulted, so both tiers behave identically.
Mutation-checked after the change, because swapping the byte source could
in principle have made the oracle stop discriminating. Removing
BitmapCreateOptions.IgnoreImageCache from ResolveForResync:
# replace: before=32
# replace: after=32
not ok TitleBarIcon_Replace_PicksUpNewBytes (before=32 after=32)
The stale cached decode is still observed, so the check still fails when
the forced re-read is removed and passes when it is present.
Note the filter that found this: `--filter "TitleBarIcon_Replace"` matched
zero fixtures and reported "Total failures: 0", which reads as a pass. The
filter is a prefix over *fixture* names and the fixture is
TitleBarIcon_RefreshesReplacedFile -- "Repla" is not a prefix of "Refre".
A no-match is not a measurement; the real run above is the positive control.
Verified post-rebase onto main (5a4bbe37):
- 13797 unit tests, 0 failures
- 1495 selftest checks, 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host, Reactor.Tests
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Fix two title bar icon defects found by review round 6
Both were real; both verified against the code rather than taken on trust,
and both are now pinned by an assertion that fails without the fix.
1. The resync re-probed the filesystem on a false premise
------------------------------------------------------------------
ResyncInheritedIcon called InvalidateCaches() with the comment "ApplyChrome
has just re-probed the filesystem for the caption; re-probe here too ... so
the two surfaces cannot drift."
That claim is simply false. TryApplyExeIconFallback caches *both* outcomes
for the window's lifetime -- a hit via _exeFallbackHIcon and a miss via
_exeFallbackAttempted -- and says so explicitly:
// One attempt per window is enough: neither source can appear while
// the window is alive.
So the caption never re-probes, and re-probing here *created* the very
divergence the comment claimed to prevent: an Assets\AppIcon.ico appearing
mid-run would light up the title bar while the caption kept serving its
cached miss.
Removed the invalidation and rewrote the rationale to describe what the
code actually does. A *declared* icon still re-resolves on change, because
that cache is keyed on the WindowIcon reference -- so the behaviour that
matters is unaffected, which the eleven existing fixtures confirm.
The two caches are still not scope-identical: this one is process-wide,
the window's is per-window, so a second window opened after an asset
appeared would re-probe for its caption while this memo stays cold.
Documented as accepted residue rather than engineered away -- it requires
the asset to materialize while the app runs, which both layers already
document as out of scope.
2. The icon push was a permanent no-op when not content-extended
------------------------------------------------------------------
SyncTitleBarIcon read _titleBarControl, whose only assignment is in
SetElementTitleBarHeight. RegisterWindowTitleBar returns before it when
WindowSpec.ExtendsContentIntoTitleBar is explicitly false:
if (explicitValue == false) return; // Element.cs:5164
...
ApplyTitleBarHeightOption(titleBar, element); // never reached
That is a supported mode -- Phase7WindowingFixtures runs several windows in
it. The icon was correct at mount (the descriptor entry runs regardless),
but the window held no reference to push to, so a later
ReactorWindow.Update changing WindowSpec.Icon left the title bar stale
forever. Nothing else would have corrected it: Update does not schedule a
render.
Fixed by capturing the control in MarkTitleBarControlPresent, which is
already called unconditionally before that early return. Deliberately a
separate weak reference rather than reusing _titleBarControl: that one
belongs to the issue-#917 height state machine, whose sameControl fast path
would start skipping caption writes it previously performed if the icon
path populated it early.
New fixture TitleBarIcon_NotExtendedTracksIcon, mutation-checked by
restoring the old _titleBarControl read:
# notExtended: before=.../External.ico
# notExtended: after=.../External.ico
not ok TitleBarIcon_NotExtended_TracksWindowIconChange
not ok TitleBarIcon_NotExtended_IconActuallyChanged
# Total failures: 2
The stale icon is directly observed. Note only those two checks reddened --
the extended-mode Follows fixture still passed -- so the new arm is
evidence about this mode specifically rather than a duplicate of coverage
that already existed. It also asserts !ExtendsContentIntoTitleBar as a
positive control, because without that the fixture would silently degrade
into a copy of Follows if anything ever flipped the window back.
Verified:
- 13797 unit tests, 0 failures
- 1496 selftest checks, 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Mirror ApplyChrome's icon caching arm by arm (review round 7)
Round 6 established the rule: cache exactly as the window arm that produced
the value caches. It fixed one direction and, in doing so, got the other
direction wrong -- I removed the invalidation wholesale rather than per arm.
ApplyChrome's two arms do not cache alike:
declared spec.Icon is { } icon && icon.Apply(_appWindow) -- no memo,
re-resolves the path on every single application
fallback TryApplyExeIconFallback() -- caches BOTH
a hit (_exeFallbackHIcon) and a miss (_exeFallbackAttempted)
for the window's lifetime
TitleBarIconDefault memoized both. For the convention arm that is correct
and was the round-6 fix. For the declared arm it is the mirror-image bug:
s_declared is keyed on the WindowIcon *reference*, so a same-instance
WindowIcon whose file is deployed after an initial miss -- or deleted after
a hit -- moves the window caption while the title bar serves the stale
answer forever. WindowIcon.FromPath does no I/O at construction, so naming
a not-yet-deployed asset is a legal declaration, not a misuse.
Fixed by clearing only s_declared in ResyncInheritedIcon and leaving the
convention memo standing, so each arm now matches its counterpart.
New fixture TitleBarIcon_DeferredAssetAppears holds ONE WindowIcon instance
across all three states (absent -> deployed -> deleted) and asserts that
identity, because a fixture that built a fresh WindowIcon per update would
take the key-mismatch path and pass regardless of what the cache does --
the same non-discriminating shape as re-resolving the already-ambient
window in the two-window arm.
Mutation-checked by removing the clear:
# deferred: initial=<null>
# deferred: appeared=
not ok TitleBarIcon_Deferred_PicksUpDeployedAsset (uri=)
# Total failures: 1
The stale cached miss is directly observed, and only that check reddened.
Stated honestly: the mutation isolates the *appearance* direction only. Once
the icon never appears, the later "removed" check passes vacuously. Both
directions are governed by the same single statement, so the code under test
is proven; the removal check earns its place as documentation and as a guard
against a future asymmetric change, not as independent mutation evidence.
Two stale comments corrected (both flagged as suppressed review comments;
both were mine):
- The ms-appx remark claimed the packaged case "could not be measured
here (the self-test host is WindowsPackageType=None)". Stale since
#1155: Reactor.PackagedTests.Host links every fixture source from
Reactor.AppTests.Host, and these fixtures declare no tier -- so
SelfTestTier.Any -- which puts the FromResource("ms-appx:///...") arm
of TitleBarIcon_WindowSpec under real package identity.
- The replaced-file oracle comment still said the replacement decodes at
256x256. It has been a 1x1 PNG since the previous commit made that
fixture self-sufficient across tiers.
Verified:
- 13797 unit tests, 0 failures
- 1497 selftest checks, 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host
One full-suite run failed OverlayLifecycle_Expire_GoneAfterHold /
_DictDrained. Not attributed to this change: the fixture is a timing-based
expiry probe, it passed 3/3 in isolation and on a clean full-suite rerun,
the immediately preceding full run was green on near-identical code, and
nothing here touches overlay lifecycle.
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Agree with the window on which icon SOURCE won (review round 8)
TryResolveDeclared only performs the first half of what ApplyChrome does.
WindowIcon.Apply is:
if (!TryResolvePath(out var target)) return false;
try { appWindow.SetIcon(target); return true; }
catch { ...; return false; }
so a declared icon can resolve to a real file and still be refused by
SetIcon, at which point ApplyChrome falls through to the convention/PE
fallback. The title bar went on projecting the rejected file -- rendering
nothing while the window showed its fallback. That is precisely the
caption/title-bar disagreement this feature exists to prevent.
Fixed by carrying the window's actual verdict instead of re-deriving a
proxy for it. ReactorWindow records DeclaredIconApplied in ApplyChrome, at
the point the decision is made, and both projection entry points forward it.
Tri-state on purpose. null means "no decision yet" (or no live window) and
keeps the optimistic pre-existing behaviour, so a title bar that mounts
before the first ApplyChrome behaves exactly as before; SyncTitleBarIcon
runs at the end of that same ApplyChrome, so the authoritative answer lands
immediately after.
On testing this, and why there is no selftest
------------------------------------------------------------------
I tried to stage a real SetIcon rejection and could not. Two probes, both
measured rather than assumed:
a text file named .ico -> windowAcceptedDeclared=True
a real .ico held FileShare.None -> windowAcceptedDeclared=True
AppWindow.SetIcon (Windows App SDK 2.1) does not throw for a path that
exists; it appears to apply a default silently -- the same shape as the
documented ms-appx behaviour. So resolve-succeeded-then-rejected is not
reachable end to end from a fixture, and I deleted the selftest rather than
leave one whose assertions could not distinguish healthy from broken.
Worth recording that the fixture's instrument check is what caught this.
It asserted win.DeclaredIconApplied == false before asserting anything
about the icon, so the run reported "the scenario did not occur" instead of
"the fix does not work" -- which is what the three red checks would
otherwise have read as.
Covered headlessly instead, where the logic is pure and the oracle is real:
A_Declared_Icon_The_Window_Rejected_Falls_Through_To_The_Convention pins
that declaredIconApplied:false takes the convention arm even though the
declared file resolves, with declaredIconApplied:true as the positive
control on the same spec so the assertion is about the verdict and not
about a missing file. An_Undecided_Window_Still_Honours_The_Declaration
pins the null arm.
Mutation-checked by dropping the `declaredIconApplied is not false` guard:
failed ...A_Declared_Icon_The_Window_Rejected_Falls_Through_To_The_Convention
total: 35 failed: 1
Only that test reddened.
The measured SetIcon permissiveness is recorded on the parameter's doc so
the next reader does not repeat the two probes.
Verified:
- 13799 unit tests, 0 failures
- 1497 selftest checks, 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host, Reactor.Tests
(caught a Release-only CS1573 for the new param -- Debug was green)
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Two more caching/lifetime fixes (review round 9)
1. Forced re-decode applied to the wrong arm
------------------------------------------------------------------
ResolveForResync used BitmapCreateOptions.IgnoreImageCache for every
image-backed projection. That is right for a declared icon -- ApplyChrome
re-runs spec.Icon.Apply(...) every time, so a declared file replaced in
place really does reach the caption and the title bar must follow. It is
wrong for the convention arm, whose caption serves a cached HICON from
TryApplyExeIconFallback forever: forcing a re-decode there burns a decode
on every unrelated WindowSpec update AND makes the title bar adopt bytes
the caption never sees.
Same rule as rounds 6 and 7, third arm: match the caching of whichever
window arm produced the value. ResolveForSpec now reports which arm won
via an out parameter rather than having the caller re-derive it -- deriving
the same fact a second way is how two copies drift apart.
TitleBarIcon_RefreshesReplacedFile still passes (before=32 after=1): it
declares its icon, so it stays on the arm that re-decodes.
2. A replacement title bar's reference was wiped by the old one's unmount
------------------------------------------------------------------
ChildReconciler's type-mismatch branch mounts the replacement subtree
before unmounting the old control. The new mount records
_titleBarIconControl; the old control's unmount then reached
ClearTitleBarControl, which cleared it unconditionally. That field is
written only at mount, so the live title bar became permanently unreachable
by the icon push.
Fixed by passing the unmounting control down and clearing only on a match.
Only that field is guarded -- the height fields keep their unconditional
semantics because ApplyTitleBarHeightOption re-establishes them on every
update, so a spurious clear there is self-healing. Mine is not.
The fixture took two attempts, and the first one is worth recording
------------------------------------------------------------------
I first wrote this as a KEYED replacement (.WithKey("bar-0") ->
"bar-1"). It passed under mutation -- i.e. it proved nothing. Instrumenting
the actual order showed why:
keyed: MARK #1 / CLEAR #1 / MARK #2 (unmount, then mount)
type mismatch: MARK #1 / MARK #2 / CLEAR #1 (mount, then unmount)
Only the second interleaving can strand the new reference. Reaching it
needs the child's element TYPE to change while the new subtree still
contains a TitleBar (TitleBar -> VStack(TitleBar)), because two TitleBars
at one position take CanUpdate and never unmount at all.
With the corrected shape the mutation reddens it:
# typeSwap: before=.../External.ico
# typeSwap: after=.../External.ico
not ok TitleBarIcon_TypeSwap_ReplacementStillTracked
That is the third time this session an oracle looked right, named the right
thing, and could not observe the failure. Renamed the fixture to
TitleBarIcon_TypeReplacement so nobody "simplifies" it back to a keyed
swap, and wrote the measured orders into the fixture comment.
Verified:
- 13799 unit tests, 0 failures
- 1498 selftest checks, 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host, Reactor.Tests
(caught a Release-only CS0419 ambiguous cref from the new overload)
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Make a stale title bar unmount a no-op for ALL window state (round 10)
Round 9 guarded _titleBarIconControl against the stale unmount that arrives
after a replacement TitleBar has already mounted. It guarded only that
field, and the reasoning for stopping there -- "the height fields are
re-established by the next ApplyTitleBarHeightOption, so a spurious clear
is self-healing" -- was wrong about _titleBarControlMounted, which nothing
re-establishes.
ApplyChrome resolves content extension as:
spec.ExtendsContentIntoTitleBar ?? _titleBarControlMounted
so once the stale unmount clears that latch, the next ReactorWindow.Update
drops the window out of content-extended mode with a title bar still live.
Measured before fixing, by adding the assertion to the existing type-swap
fixture and running it against the round-9 code:
# typeSwap: extendedAfterSwap=True
# typeSwap: extendedAfterUpdate=False
not ok TitleBarIcon_TypeSwap_StillExtendedAfterUpdate
Both readings are logged, so the pair is a differential oracle rather than
a bare boolean: the True immediately before is what makes the False
attributable to the update.
Fixed by hoisting the guard to the top of ClearTitleBarControl and
returning early. A stale unmount -- one whose control is not the one
currently tracked -- now touches nothing at all, which is the honest
statement of the invariant and does not need re-deriving per field. An
unmount with no tracked control, or from a caller that passes none, clears
unconditionally exactly as before.
This is a pre-existing defect rather than one this PR introduced: the
unconditional clear predates the icon work. It surfaced here because the
icon push is the first consumer that keeps a mount-only reference, and the
fixture that proves it is the same one round 9 added.
After the fix: extendedAfterUpdate=True.
Verified:
- 13799 unit tests, 0 failures
- 1498 selftest checks, 0 failures -- including the Phase7 windowing
fixtures that assert the *normal* TitleBar unmount still withdraws
ExtendsContentIntoTitleBar and the caption height, so the early return
does not weaken the non-stale path
- Release clean: src/Reactor, Reactor.AppTests.Host
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Agree with the window on the CONVENTION source too (round 11)
Fourth arm of the same rule, from a suppressed review comment.
TryResolveDeclared proving a file exists is not proof the window adopted it
-- that was round 8. The identical gap existed one level down:
LoadConventionAssetIcon calls LoadImageW, which returns 0 for a file it
cannot load, after which LoadExecutablePeIcon supplies the HICON instead.
AppIconConvention.TryGetAssetPath only calls File.Exists, so the title bar
projected the convention asset while the caption showed the PE icon. WIC is
more permissive than LoadImageW (a PNG named .ico decodes in one and not
the other), so the two really can disagree.
ReactorWindow now records ConventionIconApplied where the fallback picks a
source, and the projection returns null when the convention lost -- there
is no ImageSource for a PE resource, so no icon is the documented and
correct outcome, not a mark the caption is not showing.
Unified the probe root, which is the part worth reading
------------------------------------------------------------------
The first version of this failed six existing fixtures, and the reason is
more interesting than the fix. ReactorWindow probed AppContext.BaseDirectory
while TitleBarIconDefault probed an overridable root. In production those
are the same directory, so the asymmetry was invisible; under test they are
not, and gating the title bar on the window's verdict made the title bar
obey a verdict about a file it had never looked at.
That is the same defect class this PR keeps fixing -- one fact derived two
ways -- so it is fixed the same way rather than worked around. The probe
root now lives on AppIconConvention and both consumers read it, so an
override moves them together and the verdict is always about the file the
projection resolved. TitleBarIconDefault.ConventionProbeRoot is now a
forwarder.
Covered by A_Convention_Asset_The_Window_Could_Not_Load_Yields_No_Icon,
with both null (undecided) and true as positive controls on the same asset
so the null is attributable to the verdict rather than to a missing file.
Mutation-checked by dropping the guard:
failed ...A_Convention_Asset_The_Window_Could_Not_Load_Yields_No_Icon
total: 36 failed: 1
Also in this commit
------------------------------------------------------------------
Two github-code-quality findings on the type-swap fixture, reported as
"condition is always true" and "condition is always false" on the same two
lines. They contradicted each other and both suggested deleting a guard.
The cause is nullable flow analysis: `var original = comp.Bar` links the
local to the field's slot, so `if (original is null) return;` narrows the
FIELD, and the later `var replacement = comp.Bar` inherits non-null. The
analyzer cannot see that the phase change re-renders and reassigns it, so
both conclusions are wrong at runtime and deleting either guard would have
removed one that can genuinely fire.
Fixed at the root instead: the component exposes ReadBar() rather than a
public field. A method call is not slot-tracked, so no state leaks between
the two reads and both guards stay.
Rebased onto main (one new commit); the CHANGELOG conflict kept both
entries.
Verified:
- 13818 unit tests, 0 failures
- 1498 selftest checks; the only failures are Issue487_SV2ParkedAtBottom
and Issue487_SV2ClampObserved, the known environment-dependent pair
(reproduced on unmodified main, CI green on the same SHA, nothing to do
with windowing)
- Release clean: src/Reactor, Reactor.AppTests.Host, Reactor.Tests
(caught three more Release-only XML-doc errors Debug was happy with)
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Reconcile the convention verdict by path, not by a shared probe root
The round-11 fix was right about the defect and wrong about the mechanism,
and the mechanism is what broke CI.
What went wrong
------------------------------------------------------------------
To let the title bar act on the window's "did the convention asset actually
load" verdict, I made ReactorWindow.LoadConventionAssetIcon read a shared,
test-overridable probe root instead of AppContext.BaseDirectory. That made
the window's native icon load follow the test override.
Measured consequence, not inferred:
PE icon count in Reactor.AppTests.Host.exe : 0 (ExtractIconExW -1)
Assets\AppIcon.ico shipped by the host : none
So in the self-test host the whole HICON path -- LoadImageW,
GetIconIdFromIcon, AppWindow.SetIcon, DestroyIcon -- was *dead code* before
that commit: both loaders returned 0 and TryApplyExeIconFallback bailed.
Redirecting the root made ~4 fixtures create a real Assets\AppIcon.ico under
the scratch root, so the window began creating, applying and destroying real
icon handles for the first time, in a host that opens and closes windows
continuously.
Selftests had been green on the three preceding commits and then failed on
both attempts of the next run, with STATUS_ACCESS_VIOLATION (0xC0000005) and
a *different* blamed fixture each time (ConnectedAnimation_OrphanOnlyPass...,
then OneWayClearValue) -- the harness's own documented signature for a
native Host death whose victim is positional. Three full local runs and two
runs of CI's exact command did not reproduce it, so the mechanism could not
be proven locally; but a newly-live native handle path is the only new
native surface that commit added, and steering the window's real SetIcon
from a test was never something the override should have done.
The fix
------------------------------------------------------------------
Reconcile by path instead of by shared root.
ReactorWindow keeps probing AppContext.BaseDirectory -- always, no override
-- and records UnloadableConventionIconPath: the convention file it probed
and could *not* load, or null. The title bar keeps its own redirectable
probe root and drops the convention arm only when the window's failed path
is the same file it just resolved.
That is the same principle the rest of this PR follows, applied one level
up: agree with the window about the source, but first check that both are
talking about the same file. Comparing paths is not deriving one fact twice
-- it is refusing to combine two facts until they are known to refer to the
same object. A bare boolean could not express that, which is what forced the
shared root.
Behaviour is unchanged in production, where the two roots are the same
directory. In tests the verdict is simply inert, which is correct: the
window never looked at the scratch file.
Tests
------------------------------------------------------------------
A_Convention_Asset_The_Window_Could_Not_Load_Yields_No_Icon
unchanged intent, now passing the failed path; no-verdict positive
control on the same asset so the null is about the verdict
A_Verdict_About_A_Different_File_Does_Not_Blank_The_Title_Bar
new -- pins the inertness that makes the redirect unnecessary, and is
the arm that would have caught the original regression
Mutation-checked (`if (false && unloadableConventionPath is not null)`):
failed ...A_Convention_Asset_The_Window_Could_Not_Load_Yields_No_Icon
total: 37 failed: 1
Verified:
- 13819 unit tests, 0 failures
- 14/14 TitleBarIcon fixtures
- 1597/1597 via CI's exact command
(dotnet test tests/Reactor.SelfTests -p:Platform=x64), 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host, Reactor.Tests
One instrument note for the next reader: an earlier run of this sweep
reported one failure that was a stale binary -- `dotnet test --no-build`
after restoring mutated source runs the mutant, not the restored code. The
numbers above are from a rebuilt tree.
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Record the convention verdict pessimistically (review round 12)
UnloadableConventionIconPath was written from the LoadImageW result alone,
so it described the *load*, not the *adoption*. Between those two there is
another failure boundary: GetIconIdFromIcon / AppWindow.SetIcon can throw,
IsIconApplyFailure swallows it, and TryApplyExeIconFallback returns false
with the window showing no icon at all -- while the record said the asset
loaded fine and the title bar went on projecting it.
Same divergence the record exists to prevent, one boundary further along.
Now written pessimistically: set as soon as a candidate file is found, and
cleared only after SetIcon has returned. Both failure paths -- the decode
miss and the throw -- therefore leave it naming the file, which is the
truthful answer in each case.
The clear is also gated on the handle having come from the convention
loader, captured before `hIcon` is reassigned by the PE fallback. A PE icon
adopted after the convention asset failed to decode must not clear the
record: the convention really was not adopted, and a PE resource is not
something the title bar can project.
No test change. The reachable arms are already covered by
A_Convention_Asset_The_Window_Could_Not_Load_Yields_No_Icon and
A_Verdict_About_A_Different_File_Does_Not_Blank_The_Title_Bar, which pin
the projection's behaviour given a verdict. The newly-covered arm is the
throw out of SetIcon, and that is not stageable: two independent probes
earlier in this PR established that AppWindow.SetIcon does not throw for a
path that exists -- it silently applies a default -- which is the same
reason the round-8 selftest was deleted rather than left as a
non-discriminating oracle. Recording it here rather than adding a test that
cannot fail.
Verified:
- 13819 unit tests, 0 failures
- 14/14 TitleBarIcon fixtures
- 1597/1597 via CI's exact command
(dotnet test tests/Reactor.SelfTests -p:Platform=x64), 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Skip the resync write when neither the icon nor its bytes changed (round 13)
Two suppressed review comments, both real.
1. A decode on every unrelated window update
------------------------------------------------------------------
ApplyChrome runs on every unequal WindowSpec, and the resync had no early
exit, so with a declared icon a Title change -- or an opacity tweak, or any
other unrelated field -- rebuilt a BitmapImage with IgnoreImageCache and
re-read the file from disk. Uncached I/O and a decode on routine updates.
The obvious fix (compare the projection and skip when equal) is the one
round 7 had to REMOVE, because replacing a file in place leaves the
projected Uri identical and the refresh was lost. Both requirements hold at
once if the comparison includes the file itself, so the applied record now
carries a stamp -- last-write time and length -- and the resync skips only
when the projection AND the stamp both match.
Consequences:
- unrelated update, file untouched -> no write, no decode (new)
- same path, new bytes -> stamp differs -> rewrite (kept)
- projection changed -> rewrite (kept)
A stat failure returns null, which compares unequal to a real stamp and so
falls through to the rewrite: the safe direction, costing one redundant
decode rather than a stale icon.
The resolved path is reported out of ResolveForSpec rather than derived
back out of the projected Uri, because that Uri may be ms-appx: and mapping
it back is exactly the second-derivation pattern that has drifted twice in
this PR already. Both caches now carry the path alongside the value.
Mutation-checked by making FileStamp always return null, which collapses
the new condition into the round-7 bug:
# replace: before=32
# replace: after=32
not ok TitleBarIcon_Replace_PicksUpNewBytes (before=32 after=32)
So the stamp is load-bearing, and TitleBarIcon_RefreshesReplacedFile is
what pins it. The skip itself is covered in the other direction by the
eleven fixtures that still pass: several update a window repeatedly and
assert the icon is still correct afterwards.
2. In-place mutation of an inherited IconSource
------------------------------------------------------------------
ObserveAfterSetters compares by reference, so a setter that mutates the
inherited source instead of replacing it -- ((ImageIconSource)b.IconSource)
.ImageSource = ... -- does not latch ownership, and a later resync can
overwrite it.
Documented rather than detected. Detecting it means deep-inspecting a
control-owned object on every render, and the recovery is identical to the
null-setter ambiguity already documented two paragraphs above: the next
render re-runs the setter. Replacing the value is the supported way to
claim the slot; reaching into the instance this type created is outside
that contract, and now says so.
Verified:
- 13819 unit tests, 0 failures
- 14/14 TitleBarIcon fixtures
- 1597/1597 via CI's exact command
(dotnet test tests/Reactor.SelfTests -p:Platform=x64), 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host, Reactor.Tests
(caught one more Release-only CS1573 for the new out parameter)
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Refresh every mounted title bar, not just the last one (round 14)
MarkTitleBarControlPresent stored a single WeakReference, so an out-of-band
WindowSpec.Icon change refreshed only the most recently mounted TitleBar and
left every other one showing a stale icon.
Multiple title bars in one window is a shipped shape, not a hypothetical.
Verified in this repo rather than taken from the review:
samples/ReactorGallery/GalleryShell.cs:173 the shell's own bar
.../ControlPages/Navigation/TitleBarPage.cs:23,30,42 three previews
so navigating the Gallery to its TitleBar page has four live at once.
Now a list, with entries removed on unmount and dead targets pruned
opportunistically on mount. SyncTitleBarIcon iterates all of them, and the
teardown-reentry catch moved inside the loop so one closing bar cannot stop
the others being refreshed.
This also lets ClearTitleBarControl state its invariant honestly. Round 10
withdrew the window-wide state unless the unmounting control was not the
tracked one -- an identity check standing in for "is anything still
mounted". With a list that question is answerable directly: drop this
entry, and withdraw only once the list is empty. Same protection for the
mount-before-unmount replacement ordering, without the proxy.
The fixture is TitleBarIcon_TwoBarsInOneWindow, and the discriminating
assertion is on the FIRST bar -- the one the old last-writer-wins reference
had already forgotten by the time the second mounted. Asserting only the
second would have passed against the bug, which is the same trap as the
naive two-window arm. Mutation-checked by restoring last-writer-wins:
# twoBars: first=.../External.ico <- stale
# twoBars: second=.../Second.ico
not ok TitleBarIcon_TwoBars_FirstFollows
Only that check reddened. It also asserts the two controls are distinct
instances, so the fixture cannot silently degrade into a single-bar test.
Verified:
- 13819 unit tests, 0 failures
- 1499 selftest checks, 0 failures (raw host)
- CI's exact command: the only failure is the known
Issue487_SV2ParkedAtBottom / Issue487_SV2ClampObserved pair --
environment-dependent, reproduced on unmodified main, unrelated to
windowing
- Release clean: src/Reactor, Reactor.AppTests.Host
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Forget a departed title bar's caption height (review round 15)
The round-14 early return protects the surviving bars' window-wide state,
but it protected too much. The issue-#917 height state is a single slot --
_elementTitleBarHeight, _titleBarControl and its two flags all describe
whichever bar wrote last -- so returning early left the window sized to a
bar that had just been removed, still holding a reference to it.
Now, when other bars remain and the departing one is the current height
writer, the contribution is withdrawn: slot cleared, ApplyTitleBarHeight
re-run. A surviving bar re-establishes its own on its next
SetElementTitleBarHeight.
Deliberately does NOT promote another bar's height. Which of several
simultaneously-mounted bars should own the caption is an open question in
the height design -- today's answer is "the last one to write" -- and
answering it inside an unmount path would settle it by accident.
The fixture took two attempts, and the first one is the point
------------------------------------------------------------------
I first wrote it as one component owning both bars and toggling the Tall
one. It passed under mutation, i.e. proved nothing: removing the Tall bar
re-rendered the survivor in the same pass, so the survivor rewrote the slot
and repaired the state incidentally. The caption went Tall -> Standard
whether or not the product forgot the departed writer.
The review said "localized component rerender", and that word is
load-bearing. Each bar is now its own Component, so removing the Tall one
re-renders only itself and the survivor's Render never runs again:
with the fix: # barHeights: afterRemoval=Standard
without the fix: # barHeights: afterRemoval=Tall
not ok TitleBarIcon_BarHeights_DepartedWriterForgotten
That is the fourth time in this PR an oracle looked right, named the right
thing, and could not observe the failure -- so the reason the two bars must
live in separate components is written into the fixture.
It also asserts Tall was applied first (no departed writer, nothing to
forget) and that the window is still content-extended afterwards, which is
what the early return exists to protect.
On the second (suppressed) comment: mtime+length
------------------------------------------------------------------
Correct that last-write-time plus length is a staleness heuristic, not a
content hash: a same-length rewrite that preserves the timestamp would be
missed. Keeping it, because the two review findings pull in opposite
directions -- round 13 asked to stop re-decoding on every unrelated window
update, and "always rebuild for accepted declared icons" is exactly that
behaviour restored. A content hash trades the decode for a full file read
on every update, which is the same objection with a smaller constant.
mtime+size is the staleness signal make, MSBuild and every incremental
build system rely on; defeating it takes deliberate timestamp restoration.
The trade is now stated at the comparison rather than left implicit.
Verified:
- 13819 unit tests, 0 failures
- 1500 selftest checks, 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Avoid a static write from Render in the two-bar height fixture
github-code-quality flagged the static Setter field being assigned from
TallBar.Render. Applied the suggested shape: the static instance pointer is
published from the constructor, the setter lives in an instance field, and
callers go through static SetPhase/Ready/Reset helpers.
Re-checked discrimination after the refactor rather than assuming a
test-only change is inert -- removing DropHeightContributionIfWrittenBy
still reddens it:
# barHeights: afterRemoval=Tall
not ok TitleBarIcon_BarHeights_DepartedWriterForgotten (Tall)
Verified: 1500 selftest checks, 0 failures; Release clean.
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Track mounted title bars strongly, not by weak RCW reference
A WeakReference<TitleBar> tracks the managed wrapper, not the native
control. This repo has already been bitten by that distinction: the
ReactorAttached.StateProperty notes in Reconciler.cs exist because a
ConditionalWeakTable keyed per-RCW returned a different state object for
each wrapper of one native element and attached duplicate trampolines.
Two consequences here. The wrapper can be collected while XAML still owns
the element, after which the entry is pruned and the visible title bar
silently stops following WindowSpec.Icon. And because TitleBarIconDefault's
applied-icon record is keyed on the same wrapper, losing it also loses the
ownership record that keeps the push from clobbering a .Set(...) icon.
Mount and unmount are both explicit here -- MarkTitleBarControlPresent and
ClearTitleBarControl -- so a strong reference with deterministic removal is
strictly better than a weak one with opportunistic pruning: no collection
race, and the exact wrapper used for the push is the one the record is
keyed on, so the two can never diverge onto different wrappers.
Not a leak: entries are removed at unmount, and the list is per-window, so
anything still in it dies with the window. The pruning loops are gone with
the weak refs, which also simplifies both call sites.
Left AppliedIcon in its CWT rather than moving it onto native attached
state. With the wrapper held strongly for the mounted lifetime, the key
stays alive and every access goes through that one reference -- Reactor
never re-derives a TitleBar by walking the tree -- so the duplicate-wrapper
case the CWT is vulnerable to is unreachable from these paths. Moving it
would touch ReactorAttached for no behavioural gain here.
Also snapshots the list before iterating in SyncTitleBarIcon, since the
teardown-reentry path could re-enter and mutate it mid-loop.
Verified:
- 13819 unit tests, 0 failures
- 1500 selftest checks, 0 failures
- Release clean: src/Reactor, Reactor.AppTests.Host
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Do not clobber a one-shot .OnMount icon, and drop the fixture's static
Two findings from review round 18.
1. .OnMount(...) icon lost on the next render
------------------------------------------------------------------
ObserveAfterSetters runs after ApplyModifiers, so it also sees the write
made by a one-shot .OnMount(...) action and latches AuthorOwned. Apply then
deliberately bypasses its equality fast path for an author-owned slot --
correct for a .Set(...) setter, which re-runs every render and immediately
wins again, and necessary so the projection can return if the setter is
later removed. A mount action does not re-run, so that same rewrite
destroyed the author's icon permanently on the very next render.
The two are indistinguishable from the control alone; the element supplies
the missing half. AppliedIcon now records AuthorRepeats -- whether the
element carries any .Set(...) setters -- and Apply leaves the slot alone
when ownership is one-shot.
This is NOT the discredited "Setters.Length implies ownership" test that an
earlier round removed. Ownership is still ground truth read off the control;
the element only answers whether the observed write is repeatable.
Fixture TitleBarIcon_OnMountIconSurvives, mutation-checked by deleting the
one-shot guard:
# onMount: after=ImageIconSource
not ok TitleBarIcon_OnMount_SurvivesRerender (ImageIconSource)
The scratch root deliberately ships a convention asset, so the failing value
is the *inherited* icon rather than null -- the oracle distinguishes the
author's value from Reactor's, not from nothing. The element deliberately
carries no setters, since a capture-only .Set would make the write repeating
and invert the expected behaviour.
2. Static write in the two-bar height fixture
------------------------------------------------------------------
Round 16 moved the static write from Render to the constructor on that
review's advice; round 18 flagged the constructor. The rule covers instance
methods, properties and constructors alike, so relocating the write could
never satisfy it. Removed the static entirely instead: the fixture owns a
PhaseHandle and passes it as props via Component<TallBar, PhaseHandle>, so
Render writes to an instance field of an object the fixture already holds.
Verified:
- 13819 unit tests, 0 failures
- 1501 selftest checks; only the known Issue487_SV2ParkedAtBottom /
Issue487_SV2ClampObserved pair fails -- environment-dependent,
reproduced on unmodified main, unrelated to windowing
- Release clean: src/Reactor, Reactor.AppTests.Host
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: a835913d-1966-41c4-b6e4-71ab470f3c45
* Sharpen the one-shot icon rule at both its boundaries (round 19)
The round-18 guard was right in principle and too crude at both ends.
1. Setters.Length cannot classify repeatability
------------------------------------------------------------------
It says the element carries setters, not that a setter wrote the icon. So
.OnMount(b => b.IconSource = custom).Set(b => captured = b) was recorded as
repeating on the strength of a capture setter that never touches the icon,
and the next render overwrote the mount value with nothing to restore it --
the exact regression round 18 set out to fix, reintroduced through the side
door.
Resolved with an isMount signal from the two call sites rather than a second
observation point: the mount action can only have run on the mount pass, so
a divergence seen on any later render is necessarily a setter's and does
repeat. On the mount pass an element carrying a mount action is treated as
one-shot -- the safe direction, since if a setter really wrote the value the
next render writes it again and the record upgrades itself to repeating.
2. The one-shot was preserved t…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Please accept this contribution adding the standard Microsoft SECURITY.MD 🔒 file to help the community understand the security policy and how to safely report security issues. GitHub uses the presence of this file to light-up security reminders and a link to the file. This pull request commits the latest official SECURITY.MD file from https://github.com/microsoft/repo-templates/blob/main/shared/SECURITY.md.
Microsoft teams can learn more about this effort and share feedback within the open source guidance available internally.