Skip to content

Make ShutdownPolicy govern process lifetime (#1204) - #1205

Merged
Alexandre Zollinger Chohfi (azchohfi) merged 22 commits into
mainfrom
azchohfi-fix-shutdown-policy-explicit
Sep 15, 2026
Merged

Alexandre Zollinger Chohfi (azchohfi) merged 22 commits into
mainfrom
azchohfi-fix-shutdown-policy-explicit

Conversation

@azchohfi

@azchohfi Alexandre Zollinger Chohfi (azchohfi) commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #1204.

The bug

ShutdownPolicy never reached the platform. Application.Start sets the UI thread's Application.DispatcherShutdownMode to OnLastWindowClose, so the XAML runtime quit the DispatcherQueue event loop on last-window-close — before EvaluateShutdownPolicy could veto it. An app with ShutdownPolicy.Explicit and a live tray icon exited with code 0 the moment its window closed. git grep DispatcherShutdownMode returned nothing.

The fix

OnLaunched switches the mode to OnExplicitShutdown once, before any window exists, for every policy. The platform stops being a second, uncoordinated decision-maker — it cannot see Explicit, a surviving tray icon, or ExcludeFromShutdownPolicy.

Ownership is unconditional, not derived from the policy. Deriving it left two holes, both found in review: under the default policy the platform could still end a process whose last window was an auxiliary one (contradicting the #647 guarantee the guide already made), and the policy and the platform could disagree in the window between a setter and its dispatcher hop. With ownership unconditional, ShutdownPolicy is a plain store again — nothing to race.

Ownership is scoped to launches Reactor drives (the Run(startup) callback and the Run<TRoot> bridge) and to Application.Current is ReactorApplication. A host that constructs ReactorApplication directly, or embeds ReactorHostControl in its own Application, owns its own windows — Reactor would only leave it pumping forever.

Taking the loop over means Reactor must now own every exit, so the surrounding paths were closed up:

  • Both launch paths run the zero-surface decision from a finally, shared as ExitIfStartupOpenedNoSurface.
  • UnregisterTrayIcon stopped re-deriving the exit condition and calls the evaluator.
  • Exits fall back to DispatcherQueue.EnqueueEventLoopExit if Application.Exit() throws — deliberately catching broadly, because Exit() runs user Closed callbacks.
  • A failed OpenWindow no longer decides lifetime, and now closes the native window rather than only disposing it.

Verified on a real app

The issue's repro, built as a standalone unpackaged WinUI app outside the repo and closed with a cross-process WM_CLOSE (what Alt+F4 sends). Same app binary, only Reactor rebuilt:

Scenario Before After
Explicit + tray EXITED(0) survives, loop still pumping
Explicit, no tray EXITED(0) survives
OnLastSurfaceClosed + tray EXITED(0) survives
OnPrimaryWindowClosed EXITED(0) EXITED(0) — unchanged

EXITED(0) is verbatim the reported symptom. The full spec 036 §13.6 tray-app shape also works end to end: close → windows=0 tray=1 → reopen a window → close → ReactorApp.Exit(7) exits cleanly with 7.

Tests

  • Headless — policy round-tripping, and that the setter stayed a plain store with no platform side effect.
  • Selftest — the mode really moves to OnExplicitShutdown, and flipping the policy does not move it.
  • Out-of-process (17 tests) — the only tier that can observe process lifetime or reach a branch guarded by Application.Current is ReactorApplication. Covers surviving last-window-close, zero-surface startup, reopening afterwards, the Multi-window batch teardown 0xC0000005 ACCESS_VIOLATION at process exit (general dispose-ordering) #647 auxiliary window, the last-tray-icon exit, the legacy Run<TRoot> entry point, handled startup/configure failures, a post-registration mount failure, and an embedder's Application being left alone.

Every "stays alive" arm has a counterpart asserting the opposite outcome, and the zero-surface arms assert the open/close markers are absent so they can't pass as an open-then-close. Each oracle was mutation-checked — removing the ownership call, no-opping the window close, deleting the ownership gate, bypassing the zero-surface branch, and re-enabling policy evaluation on a failed open each redden exactly the arms they should.

Suites: unit 13,902 pass / 0 fail; Release solution build 0 errors; CI green.

Also here

  • Reactor.SelfTests stamps its configuration and TFM into the assembly so the shared host locator stops hardcoding Debug, which would run a stale host under dotnet test -c Release.
  • Docs: CHANGELOG, spec 036 §6.2, the windows.md guide (via its template), and a TESTING.md section on the probe modes.

No public API change, so no API-index regeneration.

Pre-review: the repo's pr-review skill flagged 1 high + 5 medium + 1 low across 8 dimensions, all fixed before opening. Sixteen Copilot review rounds and the CodeQL findings are addressed; all threads resolved.

WinUI's Application.Start sets the UI thread's
Application.DispatcherShutdownMode to OnLastWindowClose, so the XAML
runtime quit the DispatcherQueue event loop on last-window-close before
EvaluateShutdownPolicy's Explicit / OnLastSurfaceClosed arms could veto
it. An app with ShutdownPolicy.Explicit and a live tray icon exited with
code 0 the moment its window closed, as if the policy were the default.

Derive the platform mode from the policy instead: Explicit and
OnLastSurfaceClosed map to OnExplicitShutdown, handing process lifetime
to EvaluateShutdownPolicy; OnPrimaryWindowClosed keeps the platform
default, which already agrees with it. The write happens in OnLaunched
for a policy chosen before Run, and from the ShutdownPolicy setter for a
later change. The property is per-thread, so an off-thread set posts to
the UI dispatcher rather than blocking on the hop.

Reactor only writes it when it owns the Application. An app embedding
ReactorHostControl never calls Application.Start, so the platform has
already defaulted its mode to OnExplicitShutdown; writing
OnLastWindowClose there would make that process exit when its last
window closes.

Tests span three tiers, each mutation-checked:
  * headless mapping tests, including totality over ShutdownPolicy and a
    differential against the default policy;
  * a selftest fixture that seeds DispatcherShutdownMode to the opposite
    value before each arm, so the assertion cannot be a tautology;
  * out-of-process probes, because neither in-process tier can observe
    process lifetime or reach a branch guarded by
    "Application.Current is ReactorApplication". --shutdown-policy-probe
    covers surviving last-window-close, zero-surface startup, and
    reopening a window afterwards; --shutdown-policy-gate-probe runs a
    non-Reactor Application and asserts Reactor leaves its lifetime
    alone. Every arm has a counterpart asserting the opposite outcome.

Also stamp the configuration and TFM into Reactor.SelfTests so the
shared host locator stops hardcoding Debug, which would have run a stale
host under dotnet test -c Release.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03
@github-actions

github-actions Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build metrics

Artifact sizes for ec80f0f vs the base branch (5dc7a87).

Packages (compressed .nupkg)

Artifact base PR Δ
Microsoft.UI.Reactor.nupkg 1.70 MB 1.70 MB +3.15 KB (+0.18%) ⚠️
Microsoft.UI.Reactor.Advanced.nupkg 487.7 KB 487.7 KB +0 B (0.00%) ≈
Microsoft.UI.Reactor.Devtools.nupkg 283.3 KB 283.3 KB +6 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor

Artifact base PR Δ
Reactor.Analyzers.dll 373.0 KB 373.0 KB +0 B (0.00%) ≈
Reactor.dll 2.43 MB 2.43 MB +1.00 KB (+0.04%) ≈
Reactor.Localization.Generator.dll 16.0 KB 16.0 KB +0 B (0.00%) ≈
Reactor.Wrappers.Abstractions.dll 10.5 KB 10.5 KB +0 B (0.00%) ≈
Reactor.Wrappers.Generator.dll 99.5 KB 99.5 KB +0 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor.Advanced

Artifact base PR Δ
Reactor.Advanced.dll 1021.5 KB 1021.5 KB +0 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor.Devtools

Artifact base PR Δ
Microsoft.UI.Reactor.Devtools.dll 784.5 KB 784.5 KB +0 B (0.00%) ≈

✅ smaller / ⚠️ larger / ≈ within noise. Sizes come from a Release dotnet pack on the CI runner: packages are the compressed .nupkg download size, assemblies the uncompressed DLL inside it.
workflow run.

Comment thread src/Reactor/Hosting/ReactorApp.cs Fixed
@github-actions

github-actions Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

🧪 Merged coverage

Coverage for ec80f0f vs the base branch (5dc7a87) — unit + selftest merged.

Metric base PR Δ
Line 85.78% 85.76% -0.02 pp ≈
Branch 77.55% (957/1234) 77.63% (958/1234) +0.08 pp ≈

No coverage change beyond the noise floor. ✅

✅ higher / ⚠️ lower / ≈ within noise. Δ is in percentage points; coverage is unit + selftest merged (Debug x64) on the CI runner. Cobertura reports attached to the workflow run as artifacts.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Two moderate ReactorApp issues remain around policy/mode synchronization and auxiliary-window lifetime handling; the documentation nit also remains.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

This PR makes ShutdownPolicy govern WinUI dispatcher lifetime, adds process-lifetime coverage, and updates related documentation.

Changes:

  • Maps policies to dispatcher shutdown modes with thread-aware updates.
  • Adds unit, selftest, and out-of-process coverage.
  • Updates test infrastructure, specifications, guides, and changelog.
File summaries
File Summary
tests/Reactor.Tests/WindowShutdownPolicyTests.cs Tests policy-to-dispatcher mapping.
tests/Reactor.SelfTests/ShutdownPolicyProcessLifetimeTests.cs Tests real process lifetime.
tests/Reactor.SelfTests/SelfTestBatch.cs Integrates shared host process tests.
tests/Reactor.SelfTests/Reactor.SelfTests.csproj Stamps configuration and TFM metadata.
tests/Reactor.SelfTests/HostProcess.cs Provides shared host discovery and execution.
tests/Reactor.AppTests.Host/ShutdownPolicyProbe.cs Provides lifetime probes.
tests/Reactor.AppTests.Host/ShutdownPolicyGateProbe.cs Tests embedded-application ownership gating.
tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs Registers new fixtures.
tests/Reactor.AppTests.Host/SelfTest/Fixtures/ShutdownPolicyDispatcherModeFixtures.cs Tests live dispatcher-mode projection.
tests/Reactor.AppTests.Host/Program.cs Registers probe modes.
TESTING.md Documents selftest and probe behavior.
src/Reactor/Hosting/ReactorApp.cs Applies shutdown policy to WinUI. Findings: Moderate (2 votes): policy and queued dispatcher-mode updates can temporarily diverge. Moderate (1 vote): auxiliary windows can still cause dispatcher shutdown under OnLastWindowClose. Nit (1 vote): embedded-host XML documentation is grammatically incomplete.
docs/specs/036-window-design.md Documents platform projection semantics.
docs/guide/windows.md Updates the Windows guide.
docs/_pipeline/templates/windows.md.dt Updates the guide template.
CHANGELOG.md Records the shutdown-policy fix.
Review details

Suppressed comments (2)

src/Reactor/Hosting/ReactorApp.cs:242

  • This mapping still lets WinUI end the dispatcher without consulting EvaluateShutdownPolicy when the last native window is an auxiliary one. DockFloatingWindow.Open can create an ExcludeFromShutdownPolicy window with no elected primary; closing it yields closedWasPrimary == false (so the Reactor policy says to stay alive), but OnLastWindowClose still unwinds the loop. That contradicts the documented/spec contract that only the elected primary triggers OnPrimaryWindowClosed shutdown. Project this policy to OnExplicitShutdown too and let Reactor perform the primary/zero-surface exits, updating the mapping tests/docs accordingly.
            _ => DispatcherShutdownMode.OnLastWindowClose,

src/Reactor/Hosting/ReactorApp.cs:205

  • This new XML documentation is grammatically incomplete: in its own keeps its own lifetime is missing the object that owns the Application. The malformed sentence makes the embedded-host ownership guarantee unclear.
    /// hosting <c>ReactorHostControl</c> in its own keeps its own lifetime.</para>
  • Files reviewed: 16/16 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/Reactor/Hosting/ReactorApp.cs Resolved
Addresses the Copilot review on #1205.

Deriving DispatcherShutdownMode from the policy left two holes:

  * Under the default policy the platform stayed on OnLastWindowClose, so
    it could still end a process whose last window was an auxiliary one.
    ExcludeFromShutdownPolicy windows are never elected primary, so
    closing one leaves closedWasPrimary false and EvaluateShutdownPolicy
    says stay alive — but WinUI unwound the loop anyway, contradicting
    the guarantee the windows guide already made for issue #647.

  * The policy and the platform could disagree. The setter published the
    new policy immediately and posted the matching mode write to the UI
    dispatcher, so a close in that interval read the new policy (skip
    SafeExit) while the platform was still on the old mode (unwind) —
    the exact failure this change exists to prevent.

Take ownership once at launch for every policy instead. The platform
stops being a second decision-maker, so EvaluateShutdownPolicy, the
zero-surface check in OnLaunched, and an explicit Exit are the only ways
the process ends. That makes the issue-#647 guarantee real, and it lets
ShutdownPolicy go back to a plain store with nothing to race.

Safe because ReactorWindow subscribes to the native Window.Closed and
UnregisterWindow runs in a finally, so Reactor observes a user close the
same as an app close; the zero-window startup path exits explicitly.

Tests follow the design: the mapping tests are gone with the mapping, the
fixture now asserts ownership is policy-independent, and the probe gains
an --excluded-window arm covering the issue-#647 case that was
previously unreachable. Removing the ownership call reddens 4 lifetime
tests and 4 fixture checks while their preconditions stay green.

Also fix the incomplete sentence in the ShutdownPolicy XML docs.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Two moderate test-coverage issues and five documentation/comment nits remain unresolved.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (6)

Previously missed (1) — in code that hasn't changed since the last review.

tests/Reactor.AppTests.Host/ShutdownPolicyGateProbe.cs:9

  • The probe documentation refers to ReactorApp.SyncDispatcherShutdownMode, but that member does not exist; the implemented helper is TakeOwnershipOfDispatcherLifetime. This stale name makes the ownership gate harder to navigate.

docs/specs/036-window-design.md:557

  • The spec repeats the incorrect claim that an app embedding ReactorHostControl never calls Application.Start. The app owns and starts its own WinUI Application; only ReactorApp should skip taking ownership in that case. Please describe the gate in terms of not changing a non-Reactor application's existing shutdown mode.
Reactor only takes ownership when it owns the `Application`: an app
embedding `ReactorHostControl` never calls `Application.Start`, so its
mode already defaults to `OnExplicitShutdown` and Reactor must not change
that app's lifetime.

src/Reactor/Hosting/ReactorApp.cs:228

  • The PR description's stated contract no longer matches this implementation: it says OnPrimaryWindowClosed maps to OnLastWindowClose and that later ShutdownPolicy setter changes update the platform, but this method always writes OnExplicitShutdown and the setter at lines 186-189 is only a Volatile.Write. Please update the description to the unconditional-ownership design, or implement the mapping it currently promises.
    internal static void TakeOwnershipOfDispatcherLifetime()
    {
        if (Application.Current is not ReactorApplication app) return;
        try { app.DispatcherShutdownMode = DispatcherShutdownMode.OnExplicitShutdown; }
        catch (Exception ex) { global::System.Diagnostics.Debug.WriteLine($"[Reactor] TakeOwnershipOfDispatcherLifetime failed: {ex.GetType().Name}: {ex.Message}"); }

tests/Reactor.AppTests.Host/ShutdownPolicyGateProbe.cs:81

  • This comment is left over from the discarded policy-to-platform mapping: Reactor no longer writes OnLastWindowClose for the default policy; TakeOwnershipOfDispatcherLifetime writes OnExplicitShutdown for every policy. Describe this as intentionally seeding the opposite value so a failed ownership gate is observable.
                    // OnLastWindowClose is what Reactor writes for the DEFAULT
                    // policy, so seeding it here means a gate that failed open
                    // would visibly flip it to OnExplicitShutdown below.

tests/Reactor.SelfTests/ShutdownPolicyProcessLifetimeTests.cs:104

  • This process-level suite only exercises OnLastSurfaceClosed with --with-tray, so it never verifies the normal exit when the final window closes with no tray icon. A regression in the new explicit dispatcher setup or the last-surface arm could make that case stay alive while all current process tests still pass; add the opposite control with RunProbe("OnLastSurfaceClosed") and assert LOOP-EXITED plus exit code 1.
    public void OnLastSurfaceClosed_Keeps_Process_Alive_While_A_Tray_Icon_Remains()
    {
        // The tray icon is what makes this arm meaningful: with no surviving
        // surface, OnLastSurfaceClosed is *supposed* to end the process, and a
        // tray-less run would exit for the right reason while looking exactly
        // like the bug.
        var result = RunProbe("OnLastSurfaceClosed", TrayFlag);
        var detail = Detail("OnLastSurfaceClosed", $"{ProbeFlag} {TrayFlag}", result);

        StringAssert.Contains(result.Stdout, AliveMarker,
            $"A live tray icon should have kept the process running after the last window closed.\n{detail}");
        StringAssert.Contains(result.Stdout, "trayIcons=1",
            $"The probe reported no tray icon, so this run did not exercise the surviving-surface case.\n{detail}");
        Assert.AreEqual(AliveExitCode, result.ExitCode, detail);

tests/Reactor.Tests/WindowShutdownPolicyTests.cs:154

  • Because this test runs without an Application and no window is registered, EvaluateShutdownPolicy(false) has no observable effect: SafeExit only calls Application.Current?.Exit(), while Assert.Empty(ReactorApp.Windows) is already true before the call. A mutation that incorrectly exits (or removes this branch) would still pass, so move this assertion to the process probe or remove this vacuous unit test.
            ReactorApp.ShutdownPolicy = ShutdownPolicy.OnPrimaryWindowClosed;
            ReactorApp.EvaluateShutdownPolicy(closedWasPrimary: false);
            Assert.Empty(ReactorApp.Windows);
  • Files reviewed: 16/16 changed files
  • Comments generated: 2
  • Review effort level: Lite

Comment thread docs/_pipeline/templates/windows.md.dt Resolved
Comment thread src/Reactor/Hosting/ReactorApp.cs Resolved
Comment thread src/Reactor/Hosting/ReactorApp.cs Fixed
Addresses round 2 of the Copilot review on #1205.

The ownership gate was justified with a claim that is simply wrong: that
an app embedding ReactorHostControl "never calls Application.Start". It
does — it is an ordinary WinUI app; what it does not use is
ReactorApplication. The gate is right, the reason given for it was not,
so state the actual one: Reactor does not manage that app's windows or
decide when its process ends, so it leaves its DispatcherShutdownMode at
whatever the app chose. Corrected in the XML docs, spec 036 and the guide.

The guide also still opened with "Reactor drives DispatcherShutdownMode
from the policy", left over from the per-policy mapping. Ownership is now
unconditional and changing the policy moves nothing, which is the
opposite of what that sentence implied.

Remove EvaluateShutdownPolicy_Leaves_The_App_Alive_When_A_NonPrimary_Window_Closes.
It was vacuous: with no Application, SafeExit reduces to
Application.Current?.Exit(), so the exit and no-exit branches are
indistinguishable, and its assertion was already true before the call.
The behaviour it claimed to cover is the probe's --excluded-window arm,
which can actually observe the process.

Add the missing control for OnLastSurfaceClosed: with no tray icon left,
the last window closing must still end the process. Every other process
test asserts "stays alive", so without this a regression that made the
policy never exit would have gone unnoticed.

Also refresh two stale comments in ShutdownPolicyGateProbe that still
named SyncDispatcherShutdownMode and the per-policy mapping.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Moderate test gaps leave shutdown and embedder-ownership scenarios insufficiently validated.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (4)

Previously missed (1) — in code that hasn't changed since the last review.

tests/Reactor.AppTests.Host/ShutdownPolicyGateProbe.cs:93

  • This probe never invokes TakeOwnershipOfDispatcherLifetime; it only assigns ReactorApp.ShutdownPolicy, and the reviewed setter is intentionally a plain store. Consequently GATE-VIOLATED is unreachable regardless of whether the ownership guard is removed, so this test cannot validate the embedded/non-Reactor ownership gate it claims to cover. Call the internal ownership method after seeding the plain Application (or exercise an actual ReactorHostControl embedding path) before reading after.

tests/Reactor.SelfTests/ShutdownPolicyProcessLifetimeTests.cs:104

  • Checking trayIcons=1 proves only that the tray icon was created; it does not prove that the window was removed. If the close call fails, this process still reports STILL-ALIVE with windows=1 and the test passes. Also assert windows=0 so this arm really exercises a surviving tray icon after the last window closes.
        StringAssert.Contains(result.Stdout, AliveMarker,
            $"A live tray icon should have kept the process running after the last window closed.\n{detail}");
        StringAssert.Contains(result.Stdout, "trayIcons=1",
            $"The probe reported no tray icon, so this run did not exercise the surviving-surface case.\n{detail}");
        Assert.AreEqual(AliveExitCode, result.ExitCode, detail);

tests/Reactor.SelfTests/ShutdownPolicyProcessLifetimeTests.cs:212

  • The auxiliary-window arm has the same false-positive path: an excluded window leaves primaryElected=False, and if window.Close() fails the alive timer still reports success while windows=1. Add an assertion for windows=0 so this test validates that an actually closed auxiliary window does not terminate the process.
        StringAssert.Contains(result.Stdout, "primaryElected=False",
            $"The probe's window was elected primary, so this run never reached the auxiliary-window case.\n{detail}");
        StringAssert.Contains(result.Stdout, AliveMarker,
            $"Closing an auxiliary window ended the process, contradicting the documented issue-#647 behaviour.\n{detail}");
        Assert.AreEqual(AliveExitCode, result.ExitCode, detail);

tests/Reactor.SelfTests/ShutdownPolicyProcessLifetimeTests.cs:87

  • This arm does not verify that the last window actually closed. If window.Close() becomes a no-op or fails to unregister the window, the probe still emits STILL-ALIVE (with windows=1) and exits 42, satisfying both assertions without testing last-window lifetime. Assert the windows=0 marker here before accepting the alive result.
        StringAssert.Contains(result.Stdout, AliveMarker,
            $"The process exited when its last window closed — DispatcherShutdownMode was never raised to OnExplicitShutdown.\n{detail}");
        Assert.AreEqual(AliveExitCode, result.ExitCode,
            $"ReactorApp.Exit() should have been the only thing that ended the process.\n{detail}");
  • Files reviewed: 16/16 changed files
  • Comments generated: 1
  • Review effort level: Lite

Addresses round 3 of the Copilot review on #1205.

The gate probe went vacuous in the previous commit and I did not re-run
its mutation to notice. It drove the gate by setting ReactorApp.Shutdown-
Policy, which was correct while the setter pushed to the platform; once
the setter became a plain store, that assignment wrote nothing, so
GATE-VIOLATED was unreachable and the probe reported success whether or
not the gate existed. Call TakeOwnershipOfDispatcherLifetime directly —
the method that actually carries the gate, and the one OnLaunched calls.
Verified by mutation: deleting the gate now yields GATE-VIOLATED.

The three "stays alive" process arms asserted the marker but never that
the window had closed, so a Close() that silently no-opped would leave
the window open, the process trivially alive, and the tests green.
Assert windows=0 as well. Verified by mutation: no-opping the close now
reddens six arms; before it reddened three.

Remove EvaluateShutdownPolicy_Accepts_Both_Polarities_Of_ClosedWasPrimary.
It asserted nothing — two void calls whose branches are indistinguishable
without an Application — so it counted as coverage while proving nothing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Final tray-icon closure bypasses EvaluateShutdownPolicy, leaving a critical shutdown-path issue unresolved.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

tests/Reactor.AppTests.Host/ShutdownPolicyProbe.cs:109

  • The usage text omits the newly supported --excluded-window option, so an invalid invocation cannot discover that probe mode even though Run parses it below. Include this flag in the usage line (and keep the option list in sync with the parser).
                $"[{TrayFlag}] [{NoWindowFlag}] [{ReopenFlag}]");
  • Files reviewed: 16/16 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread src/Reactor/Hosting/ReactorApp.cs Resolved
Addresses round 4 of the Copilot review on #1205.

UnregisterTrayIcon re-derived the OnLastSurfaceClosed condition inline
and called SafeExit itself, so the invariant this PR documents — that
every surface-close exit is EvaluateShutdownPolicy's decision — was not
actually true. Call the evaluator instead. A tray icon is never the
elected primary, so closedWasPrimary is false, which makes the
OnPrimaryWindowClosed and Explicit arms no-ops and leaves the
OnLastSurfaceClosed arm, whose condition is exactly what was spelled out
inline. Behaviour is unchanged across all three policies; the duplicated
decision point is not.

That path had no process-level coverage, so add it: --close-tray closes
the surviving tray icon after the window has gone and looks again, giving
a matched pair — OnLastSurfaceClosed must exit once the last surface is
gone, Explicit must not. The pair is what makes either arm meaningful.

Also list --excluded-window and --close-tray in the probe's usage text.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved critical and moderate review comments remain, including dispatcher ownership failure handling.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

docs/_pipeline/templates/windows.md.dt:572

  • This says the policy table is exhaustive for every exit and that every exit is decided by evaluating a surface close, but the implementation also exits during zero-surface startup and through explicit ReactorApp.Exit (the spec in docs/specs/036-window-design.md:544-546 calls out all three paths). Please narrow this generated-guide sentence to surface-close exits and mention the other two termination paths so the guide does not contradict the spec.
or `ExcludeFromShutdownPolicy`. Ownership is unconditional — it does not vary with
the policy — so the table above is exhaustive: every exit is Reactor's decision,
made by evaluating the policy when a surface closes.
  • Files reviewed: 16/16 changed files
  • Comments generated: 2
  • Review effort level: Lite

Comment thread src/Reactor/Hosting/ReactorApp.cs Resolved
Comment thread TESTING.md Resolved
Addresses round 5 of the Copilot review on #1205.

TakeOwnershipOfDispatcherLifetime caught every exception and reported it
through Debug.WriteLine, which compiles away in Release. That is the one
write standing between the app and issue #1204, so a silent failure would
leave ShutdownPolicy reporting Explicit while WinUI was still free to end
the process — the original bug, now invisible.

Catch only what a teardown-racing WinRT property write can realistically
throw (matching PrepareOpenWindowsForExit) and report those through
AppLogger, which is a real release diagnostic. Anything else propagates:
this runs synchronously in OnLaunched before the startup callback, so an
unexpected fault there is a startup bug and should not be hidden.

Stop short of failing fatally. The property exists in the pinned
WinAppSDK and is written on the UI thread on an Application constructed
moments earlier, so a failure is theoretical; turning it into a crash
would trade a degraded lifetime for a dead app.

Also correct the guide, which claimed the policy table covers every exit.
It covers surface closes; zero-surface startup and ReactorApp.Exit are
the other two paths, as the spec already said. And list --close-tray in
the TESTING.md flag table.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Dispatcher-mode setup failures can be swallowed, allowing startup without shutdown ownership.

Get a fresh assessment by requesting another Copilot review.

Review details
  • Files reviewed: 16/16 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread src/Reactor/Hosting/ReactorApp.cs Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

A critical startup-failure path can leave a partially constructed window undisposed when configuration throws.

Get a fresh assessment by requesting another Copilot review.

Review details
  • Files reviewed: 16/16 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread src/Reactor/Hosting/ReactorApp.cs Resolved
Addresses round 15 of the Copilot review on #1205.

OpenWindowCore ran configure outside its cleanup region, so a throwing
pre-mount callback left a ReactorWindow that had already created its
native Window and AppWindow but was neither registered nor disposed —
invisible to ReactorApp.Windows and therefore to PrepareOpenWindowsForExit.

Pre-existing, but this PR gives it teeth: the new zero-surface finally
sees Windows.Count == 0 and exits, so a configure failure that the app
marks handled would tear the process down with that live window still
holding native resources. Move configure and RegisterWindow inside the
try. UnregisterWindow already no-ops when the window was never
registered, so the existing catch covers the earlier failure point too.

Verified the whole windowing fixture surface, not just the shutdown
arms — this is the path every window open takes.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved moderate cleanup/coverage issues and a critical compilation issue remain.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (3)

src/Reactor/Hosting/ReactorApp.cs:981

  • The new finally paths rely on ExitIfStartupOpenedNoSurface for the handled-startup-failure case, but every added process probe completes startup normally and no test sets ReactorApp.OnUnhandledException to return true. A regression that removed this cleanup would leave an owned dispatcher pumping after a zero-surface callback/mount failure while the current suite stayed green. Add a child-process arm that throws during each launch shape, handles the exception, and asserts the process exits rather than timing out.
    internal static void ExitIfStartupOpenedNoSurface()
    {
        if (Windows.Count != 0) return;

        var policy = ShutdownPolicy;
        if (policy == ShutdownPolicy.Explicit) return;
        if (policy == ShutdownPolicy.OnLastSurfaceClosed && TrayIconCount != 0) return;

        try { RequestEventLoopExit(); } catch { /* best effort */ }

src/Reactor/Hosting/ReactorApp.cs:738

  • Although this moves configure into a cleanup region, the catch still never closes the native window. ReactorWindow.Dispose() tears down managed handlers/hosts but does not close the native Window (the existing lifecycle fixture has to close it separately), so a configure or MountAndActivate exception leaves an unregistered native window alive—especially observable under ShutdownPolicy.Explicit, where the process continues. Close the window on this failure path before disposing it.
            // Idempotent when the failure happened before RegisterWindow.
            UnregisterWindow(window);
            try { window.Dispose(); } catch { /* best effort */ }

src/Reactor/Hosting/ReactorApp.cs:738

  • This new cleanup path is not covered by a live test: configure runs after ReactorWindow has created its native window, so a throw before registration depends on this catch to dispose that unregistered window. The current probes pass configure: null, and no test throws from an OpenWindow/Run configure callback, so removing or reordering this cleanup could leave a native window leak while the suite stays green. Add a selftest or process probe that throws from configure and verifies the window is not left registered and teardown still exits cleanly.
        catch (Exception)
        {
            // Idempotent when the failure happened before RegisterWindow.
            UnregisterWindow(window);
            try { window.Dispose(); } catch { /* best effort */ }
  • Files reviewed: 16/16 changed files
  • Comments generated: 1
  • Review effort level: Lite

Addresses round 16 of the Copilot review on #1205.

ReactorWindow.Dispose unsubscribes handlers and tears down the host but
never closes the native Window the ctor created, so the cleanup added
last commit still left a live untracked window behind — most visible
under Explicit, where the process keeps running. Close it before
disposing. Unregister runs first so the close cascade's own unregister is
the no-op, which keeps a failed open from reaching
EvaluateShutdownPolicy; the launch paths' zero-surface decision owns that.

Added --throw-in-startup, covering both a throwing startup callback and a
throwing legacy configure, with the exception marked handled.

One honest limitation, measured rather than assumed: an exception
propagating out of OnLaunched fast-fails the XAML runtime (0xC000027B)
even when OnUnhandledException returns true. So the hang those arms were
written to catch is not reachable that way today, and no assertion in
them can be attributed to the finally. They assert "does not hang" and
say so in a comment, rather than claiming coverage they do not have. The
legacy variant does genuinely drive the OpenWindowCore cleanup above.

Not changed: the claim that removing `using System.Runtime.InteropServices`
breaks SelfTestBatch. That file contains no DllImport, Marshal,
UnmanagedType or RuntimeInformation reference (0 matches, against 4 for
Stopwatch as a control) and the project builds in Debug and Release. The
P/Invokes named in the comment live in SelfTestRunner.cs, in the Host.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03
Addresses the github-code-quality findings on #1205. RequestEventLoopExit
caught everything around both exit attempts; filter to the WinRT faults
that are plausible there and let a real bug surface. The outer guard in
ExitIfStartupOpenedNoSurface goes away entirely — RequestEventLoopExit
already handles and logs its own failures, so it was catching nothing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Cleanup after a post-registration mount failure can trigger premature shutdown evaluation.

Get a fresh assessment by requesting another Copilot review.

Review details
  • Files reviewed: 16/16 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread src/Reactor/Hosting/ReactorApp.cs Resolved
Comment thread src/Reactor/Hosting/ReactorApp.cs Fixed

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Two unresolved findings in ReactorApp.cs affect exit fallback handling and failed-window cleanup.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

src/Reactor/Hosting/ReactorApp.cs:741

  • This cleanup removes a registered window before closing it, but UnregisterWindow calls EvaluateShutdownPolicy at line 885. If MountAndActivate fails after registration and this is the only surface, the default or OnLastSurfaceClosed policy therefore calls SafeExit while the failed native window is still in its pre-close state. PrepareOpenWindowsForExit can no longer see it, so a partially mounted TitleBar can be torn down through Application.Exit without PrepareTitleBarTreeForClose (the same unsafe path guarded for issue #537). Close/prepare and dispose the failed window before a registry removal can trigger shutdown, or add a cleanup path that suppresses policy evaluation for the failed open.
            UnregisterWindow(window);
  • Files reviewed: 16/16 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread src/Reactor/Hosting/ReactorApp.cs Resolved
Addresses the latest round of review on #1205.

MountAndActivate can throw after RegisterWindow, and UnregisterWindow
evaluates the shutdown policy. So a failed open of the elected primary
under OnPrimaryWindowClosed called SafeExit while the caller was still
unwinding — killing the app over an OpenWindow failure the caller may
well handle, and even with other windows still open. Add an
evaluateShutdownPolicy parameter and pass false from the failure path; a
failed open is not a surface close. The launch paths' zero-surface
decision still owns the lifetime call.

Restore the broad catches in RequestEventLoopExit, reversing the
narrowing from b7b18b3. Narrowing was wrong here, and the reasoning is
worth keeping: Application.Exit() tears windows down synchronously and
ReactorWindow.OnNativeClosed invokes user Closed callbacks without
catching them, so an arbitrary app exception can surface. Letting one
escape before the fallback runs leaves an OnExplicitShutdown loop pumping
with no way out — exactly what that method exists to prevent. Commented
so it does not get re-narrowed.

Cleanup catches in the failed-open path become catch (Exception) rather
than bare, which is what CodeQL wanted; broad is correct there because
losing the original exception would be worse than suppressing a cleanup
failure.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Two unresolved moderate startup failure paths affect process lifetime and require final human review.

Review details

Suppressed comments (2)

src/Reactor/Hosting/ReactorApp.cs:1368

  • This call is outside the try/finally, so if the dispatcher-mode write throws and the app's documented OnUnhandledException callback marks that exception handled, ExitIfStartupOpenedNoSurface() is never reached. A zero-surface Explicit launch can then leave Application.Start pumping indefinitely with no surface, even though the finally below is intended to prevent exactly that state. Move ownership into the protected launch sequence and make a handled ownership failure fail closed (or otherwise guarantee an event-loop exit).
            ReactorApp.TakeOwnershipOfDispatcherLifetime();

            try

src/Reactor/Hosting/ReactorApp.cs:1409

  • The legacy launch branch has the same failure window: both TakeOwnershipOfDispatcherLifetime() and the initial-spec construction run before the try/finally. If either exception is handled by OnUnhandledException, the zero-surface cleanup is skipped and the newly owned dispatcher can continue pumping without a window. Keep all pre-window launch work that can fail inside the protected region, and fail closed when ownership cannot be established.
        ReactorApp.TakeOwnershipOfDispatcherLifetime();

        var spec = ReactorApp.BuildInitialWindowSpec(opts);

        try
  • Files reviewed: 16/16 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Comment thread src/Reactor/Hosting/ReactorApp.cs Fixed
Comment thread src/Reactor/Hosting/ReactorApp.cs Fixed
Comment thread src/Reactor/Hosting/ReactorApp.cs Fixed
Addresses the remaining github-code-quality findings on #1205, without
undoing what the Copilot review asked for.

Those two reviewers want opposite things here: CodeQL flags the generic
catch, while the exit fallback specifically needs to survive an arbitrary
exception, because Application.Exit() runs user Closed callbacks that
Reactor does not wrap. Filtering on `ex is not OutOfMemoryException`
satisfies both and is the more defensible rule on its own terms:
suppressing OOM during best-effort cleanup hides a fatal condition and
lets the process limp on, which no caller wants.

Applied to the exit fallback and to the failed-open cleanup, which also
now logs what it suppressed instead of discarding it silently.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Two moderate coverage/cleanup findings remain, along with one documentation nit.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (2)

docs/_pipeline/templates/windows.md.dt:575

  • This absolute guarantee no longer matches the implementation: RequestEventLoopExit catches failures from both Application.Exit() and EnqueueEventLoopExit() and explicitly logs that the event loop may not terminate (src/Reactor/Hosting/ReactorApp.cs:1026-1055). Please qualify the guide text so it describes a clean-exit request plus the dispatcher fallback rather than promising that ReactorApp.Exit() always succeeds.
`OnPrimaryWindowClosed`, and `ReactorApp.Exit()` always works.

tests/Reactor.SelfTests/ShutdownPolicyProcessLifetimeTests.cs:223

  • The zero-surface process coverage does not exercise the OnLastSurfaceClosed + no-tray startup branch in ExitIfStartupOpenedNoSurface. The existing no-tray test opens and then closes a window, so it only exercises EvaluateShutdownPolicy; a regression that incorrectly treats OnLastSurfaceClosed as permitted at zero-surface startup would leave this path pumping forever without being detected. Add a sibling probe for RunProbe("OnLastSurfaceClosed", NoWindowFlag) that requires LOOP-EXITED and exit code 1.
    [TestMethod]
    public void Explicit_Keeps_Process_Alive_When_Startup_Opens_No_Surface()
    {
        var result = RunProbe("Explicit", NoWindowFlag);
  • Files reviewed: 16/16 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread src/Reactor/Hosting/ReactorApp.cs Resolved
Addresses the latest review comment on #1205. The evaluateShutdownPolicy:
false branch added last commit had no test that reached it: both throwing
arms fail in configure, before RegisterWindow, so the window was never
registered and never primary — the case the branch exists for.

Add --throw-in-mount. Its root factory throws inside MountAndActivate, so
the window has already been registered and elected primary; the callback
catches the failure and then opens a real window. With the branch, the
process survives and the survivor opens; without it, unregistering sees
"primary closed" under the default policy and calls SafeExit mid-unwind.

Verified by mutation: flipping the flag back to true reddens exactly this
arm and nothing else.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7fee1e26-bf89-44e2-afd2-679952c18c03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Unresolved moderate launch-path findings and noted test-coverage gaps remain.

Review details

Suppressed comments (4)

src/Reactor/Hosting/ReactorApp.cs:1407

  • The legacy launch path has the same gap: an exception from TakeOwnershipOfDispatcherLifetime() occurs before the try/finally, so a handled ownership failure bypasses the zero-surface exit. Move the ownership call into this try as well, keeping both launch shapes covered by the cleanup finally.
        ReactorApp.TakeOwnershipOfDispatcherLifetime();

src/Reactor/Hosting/ReactorApp.cs:749

  • The new native-close cleanup is not actually proven by the ThrowInMount probe: it only asserts that ReactorApp.Windows.Count becomes zero. Removing window.Close() would still pass because UnregisterWindow removes the failed entry before the count is printed, while leaving the native window untracked. Add an oracle for the native Window.Closed/HWND destruction (captured before the failing open) so this test fails when the cleanup is removed.
            try { window.Close(); } catch (Exception ex) when (ex is not OutOfMemoryException) { global::System.Diagnostics.Debug.WriteLine($"[Reactor] failed-open Close threw: {ex.Message}"); }

src/Reactor/Hosting/ReactorApp.cs:1368

  • This call is outside the existing try/finally, so an exception while setting DispatcherShutdownMode skips ExitIfStartupOpenedNoSurface. If an app's OnUnhandledException marks that startup exception handled, OnLaunched can return with zero surfaces without requesting event-loop exit; put the ownership call inside the try so the finally also covers this failure path.
            ReactorApp.TakeOwnershipOfDispatcherLifetime();

tests/Reactor.SelfTests/ShutdownPolicyProcessLifetimeTests.cs:252

  • The zero-surface OnLastSurfaceClosed case without a tray icon is a separate branch from the covered last-window-close case: ExitIfStartupOpenedNoSurface must exit when TrayIconCount == 0, while it must stay alive when a tray icon exists. This new test class covers zero-surface Explicit, zero-surface default, and zero-surface OnLastSurfaceClosed with a tray, but not zero-surface OnLastSurfaceClosed with no tray; a regression that incorrectly returns for all OnLastSurfaceClosed zero-surface startups would therefore pass. Add a process-probe test expecting LOOP-EXITED and exit code 1 for RunProbe("OnLastSurfaceClosed", NoWindowFlag).
    [TestMethod]
    public void OnPrimaryWindowClosed_Exits_When_Startup_Opens_No_Surface()
    {
        // Control for the two arms above: same zero-surface startup, opposite
  • Files reviewed: 16/16 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

…-policy-explicit

# Conflicts:
#	CHANGELOG.md
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) merged commit 72aa9fc into main Sep 15, 2026
30 checks passed
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) deleted the azchohfi-fix-shutdown-policy-explicit branch September 15, 2026 02:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] ShutdownPolicy.Explicit is ignored: closing the last window exits the process

2 participants