Skip to content

Add DockFloatingCloseReason discriminator to floating-window close event (#417) - #642

Merged
Alexandre Zollinger Chohfi (azchohfi) merged 7 commits into
mainfrom
azchohfi-dock-floating-close-reason
Jun 25, 2026
Merged

Alexandre Zollinger Chohfi (azchohfi) merged 7 commits into
mainfrom
azchohfi-dock-floating-close-reason

Conversation

@azchohfi

@azchohfi Alexandre Zollinger Chohfi (azchohfi) commented Jun 23, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #417.

Problem

DockManager.OnFloatingWindowClosed fired on every Window.Closed of a docking floating window — including the synthetic close Reactor triggers right after a cross-window dock-back. A consumer could not distinguish:

  1. the content actually went away (release resources) from
  2. the pane was dock-backed into another host (content alive, must not release).

Both surfaced as one event with the same payload, causing real bugs where consumers dispose per-document state / live resources (SwapChainPanel, Win2D, file handles) out from under a still-mounted, redocked page.

Fix (Option #1 from the issue)

Adds a reason discriminator to the event args:

public enum DockFloatingCloseReason { ContentClosed = 0, MigratedToHost, MigratedToFloat }

public sealed class DockFloatingWindowClosedEventArgs
{
    public DockableContent? Content { get; init; }
    public required DockFloatingCloseReason Reason { get; init; }   // new
}

Consumers now write if (e.Reason == DockFloatingCloseReason.ContentClosed) ReleaseResources(); and the ambiguity is gone.

Why ContentClosed, not UserClosed

The real discriminator is content-gone-vs-migrated-and-alive, not who initiated the close: the zero value also covers app-driven Close() and host-unmount, and UserClosed would have collided semantically with the unrelated WindowCloseReason.UserClosed. ContentClosed names the outcome and pairs cleanly with MigratedToHost / MigratedToFloat.

How the reason is threaded

WinUI's Window.Closed carries no payload, so the reason (+ the migrated pane) is stashed on the window holder (DockFloatingTracker.SetPendingClose) right before the synthetic Close(), and read once in the Closed handler (TakePendingClose). Nothing stashed ⇒ ContentClosed. A shared DockFloatingWindow.StashReasonAndClose(window, pane, reason) helper centralizes stash-then-(deferred)-close so every synthetic dock-back path goes through one seam and a future close site can't silently regress to reporting ContentClosed for a migrated pane.

Dock-back paths covered

Every manager-tracked-window auto-close that follows a pane reinsertion now stashes MigratedToHost/MigratedToFloat:

  • existing float's last-tab cross-window dock-back (the original raise-site path);
  • immediate tear-off → host target, docked source (DockHostNativeComponent.FinalizeImmediateDrop confirmedTarget branch);
  • immediate tear-off → host target, floating source (DockFloatingWindow.BeginFloatingTearOff confirm closure);
  • source-window emptied into the dragged preview reports MigratedToFloat (RemoveLocal).

Audited all 7 Close() sites under src/Reactor/Docking; the remaining ones are genuinely content-gone (user closing the last tab, host unmount tearing down its own floats, the Ctrl+Tab navigator popup) and correctly report ContentClosed.

Multi-pane subtlety

A multi-pane float that loses one tab to a dock-back leaves DockDragSession.Consumed == true process-wide, even though a later close of its surviving tabs is genuine. MigratedReasonFor(pane) scopes the migrated reason to the specific consumed pane via a DockDragSession.LastConsumedPane snapshot (ReferenceEquals check, reset on Begin) — surviving tabs still report ContentClosed.

The same multi-pane churn also has to report the right Content, not just the right Reason: the Closed handler's Content fallback is the Open()-time pane, which goes stale once a sibling has migrated in/out of the float. The RemoveLocal empty-branch therefore stashes the actual closing pane for every reason (not only migrations), so a genuine last-tab ContentClosed close can never report an already-migrated, still-alive sibling.

required is deliberate

Reason is required by design (considered decision, not an oversight — please don't re-litigate): there is exactly one internal raise site, so the boilerplate concern is moot, and required guarantees we can never silently default a migration to the wrong reason. Reactor raises this event; consumers handle rather than construct it.

PendingClose stash storage

The pending-close stash stays in its own Dictionary<object, PendingClose> rather than being hung off the existing ReactorWindow-keyed Entry registry. The object key is the headless-test seam: the stash round-trip is unit-tested with a plain new object() because a WinUI-backed ReactorWindow isn't constructible in a headless xUnit run, and an Entry only exists for a registered window. A comment at the field documents this.

Tests

  • Unit (DockFloatingCloseReasonTests, LifecycleEventTests): MarkConsumed pane tracking, Begin reset, End-preserves-Consumed, MigratedReasonFor (all cases incl. the multi-pane subtlety), pending-close stash round-trip / default / clear, and a new clear-on-Unregister stale-stash test.
  • Producer-path selftests that drive the real dock-back and assert MigratedToHost (+ pane identity) — T08b (docked-source immediate tear-off → host) and T12b (floating-source tear-off → host, now also pinning the MigratedToFloat source leg and asserting exactly two migration closes), plus T12c (multi-pane last-tab close after a sibling migrated out asserts the event carries the real closing pane, not the stale Open()-time one) and the original real-window stash round-trip fixture (FloatCov_Close_ThreadsCloseReason).
  • [Collection("DockingGlobals")] on both unit classes touching process-static DockDragSession.Current.
  • Full Reactor.Tests suite green (9684 passed on the main-merged tree); Reactor.AppTests.Host builds + the new/affected selftests pass (ARM64).

Docs

  • Spec 045 §5.3.5 documents the discriminator, the ContentClosed naming rationale, and the covered dock-back paths.
  • The raise-site doc comment documents the Reason field.
  • CHANGELOG.md [Unreleased]/Added entry.
  • Both reactor.api.txt copies regenerated.

Known issue (not introduced here)

Running the full tear-off selftest batch in one process hits a WinUI multi-window teardown access violation (0xC0000005) — each fixture passes individually. This is the general multi-window dispose-ordering AV tracked in #647, not introduced by this PR.

Re-verified after #537 (PR #646) merged into main: the batch still crashes with the same 0xC0000005 signature at the same stock T04 → T05 tear-off boundary (fixtures this PR does not touch). #537 fixed a distinct TitleBar heap corruption (0xC0000374) that only affects windows rendering a Microsoft.UI.Xaml.Controls.TitleBar with ExtendsContentIntoTitleBar = false; the dock floating window deliberately does neither (it sets ExtendsContentIntoTitleBar = true and skips that control), so #537 is structurally inapplicable here. The test-side double-close guards in the migration fixtures fix a separate, specific double-Close() this PR introduced; the general framework hardening (idempotent Close()/Dispose()) belongs in #647.

Co-authored-by: Copilot [email protected]

…ent (#417)

DockManager.OnFloatingWindowClosed previously fired on every floating-window
Window.Closed, including the synthetic close Reactor triggers after a
cross-window dock-back. Consumers could not distinguish a genuine user close
(release resources) from a pane migration (content still mounted, must NOT
release).

Adds enum DockFloatingCloseReason { UserClosed, MigratedToHost, MigratedToFloat }
and a required Reason on DockFloatingWindowClosedEventArgs, threaded through the
close path. The migrated reason is scoped to the specific consumed pane via
DockDragSession.LastConsumedPane so a multi-pane float that lost one tab to a
dock-back still reports UserClosed for its surviving tabs' genuine close.

Co-authored-by: Copilot <[email protected]>
…1/M6

H1: thread MigratedToHost through the two remaining dock-back close sites
(DockHostNativeComponent.FinalizeImmediateDrop confirmedTarget branch and
DockFloatingWindow.BeginFloatingTearOff confirm closure) via a new shared
StashReasonAndClose helper, so OnFloatingWindowClosed reports the truthful
reason for a pane reinserted into a host instead of the default. Add two
producer-path selftests (T08b docked-source, T12b floating-source) that drive
the real dock-back and assert MigratedToHost.

M3: rename the zero enum value UserClosed -> ContentClosed (named for the
outcome: content gone; covers app-driven Close()/host-unmount; avoids colliding
with WindowCloseReason.UserClosed). Update all call sites, tests, spec 045
5.3.5, doc comments, and both reactor.api.txt copies.

M2: keep the separate object-keyed _pendingClose map (moving it onto the
ReactorWindow-keyed Entry registry would break the headless unit-test seam);
add a comment explaining why.

M6: add a clear-on-Unregister stash-cleanup unit test + ClearPendingCloseCore.

M1: add CHANGELOG [Unreleased]/Added entry.

M4: rejected per coordinator - Reason stays required.

Co-authored-by: Copilot <[email protected]>

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.

Pull request overview

This PR resolves the ambiguity in DockManager.OnFloatingWindowClosed by threading a close “reason” through WinUI Window.Closed, allowing consumers to distinguish a true content close (safe to dispose resources) from synthetic closes caused by pane migration (dock-back / re-tear-out where content remains alive).

Changes:

  • Introduces DockFloatingCloseReason and adds required DockFloatingCloseReason Reason to DockFloatingWindowClosedEventArgs.
  • Threads the reason end-to-end by stashing pending close info in DockFloatingTracker and consuming it in the window.Closed handler; adds a shared StashReasonAndClose helper.
  • Adds unit + selftest coverage for pane-scoped migration tracking (DockDragSession.LastConsumedPane / LastConsumedToFloat) and for the pending-close stash round-trip, and updates docs/changelog/api references.

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated no comments.

Show a summary per file
File Description
tests/Reactor.Tests/Docking/Native/DockFloatingCloseReasonTests.cs New unit coverage for pane-scoped migration reasoning and pending-close stash behavior.
tests/Reactor.Tests/Docking/Native/DockDragSessionTests.cs Serializes tests that touch process-static docking session state via DockingGlobals.
tests/Reactor.Tests/Docking/LifecycleEventTests.cs Verifies new Reason surface + enum default value contract.
tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs Registers new selftest fixtures in both the name list and constructor switch.
tests/Reactor.AppTests.Host/SelfTest/Fixtures/NativeDockingTearOffFixture.cs Adds producer-path selftests asserting MigratedToHost for immediate tear-off and float→host dock-back variants.
tests/Reactor.AppTests.Host/SelfTest/Fixtures/NativeDockingCoverageFloatingFixture.cs Adds end-to-end selftest for SetPendingClose → Window.Closed → args threading.
src/Reactor/Docking/Native/DockHostNativeComponent.cs Uses the centralized stash-then-close helper for the immediate-drop close seam.
src/Reactor/Docking/Native/DockFloatingWindow.cs Implements reason stashing/consumption, pane-scoped MigratedReasonFor, and pending-close storage/clearing in DockFloatingTracker.
src/Reactor/Docking/Native/DockDragSession.cs Extends consumed tracking to record the specific pane + whether it migrated to a float.
src/Reactor/Docking/LifecycleEvents.cs Adds the public discriminator enum and the required event-args property with documentation.
skills/reactor.api.txt Updates API reference surface for the new enum and event-args member.
plugins/reactor/skills/reactor-dsl/references/reactor.api.txt Mirrors the API reference update for the plugin copy.
docs/specs/045-docking-windows-design.md Documents the discriminator and threading rationale in spec 045 §5.3.5.
CHANGELOG.md Adds an Unreleased entry describing the new Reason discriminator and behavior change.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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.

Pull request overview

Copilot reviewed 14 out of 14 changed files in this pull request and generated 1 comment.

…tash comment

The T08b/T12b migration fixtures drive the real dock-back, which auto-closes
the preview/source floating window via StashReasonAndClose. Their finally then
called Close() again on the same window -- a double-close that raises the
probability of the known multi-window teardown access violation (#537 class).
Because all selftest fixtures run in a single Host process, that corruption can
surface as an unrelated later fixture (OptionalEchoStrandRegression) emitting no
TAP checks, which is what broke CI. Subscribe to each window's Closed event and
skip the redundant finally close.

Also reworded the M6 clear-on-Unregister test comment: production Unregister
drops the stash directly via _pendingClose.Remove(window); ClearPendingCloseCore
is the headless seam exercising that same removal (PR review feedback).

Co-authored-by: Copilot <[email protected]>
… producer coverage

H1 (high): the multi-pane floating window.Closed handler falls back to the
Open()-time pane (pending.Content ?? pane) for its Content. That fallback
goes stale once a pane has migrated into/out of a multi-pane float, so a
genuine last-tab ContentClosed close could report an already-migrated sibling
that is still alive in another host -- the exact #417 ambiguity resurfacing
through Content. Fix: the willEmpty branch now stashes (reason, pane) for
EVERY close reason, not just migrations, so the handler always reports the
real closing pane. Kept the inline synchronous Close() to preserve the
float->float drag-complete interleaving.

M3: add producer-path selftest T12c driving the real
onTabClosing -> RemoveLocal -> willEmpty path: open float [A], dock B in
([A,B]), close A ([B]), then close the genuine last tab B; assert the event
reports Content=B (not stale A) with Reason=ContentClosed. Adds an internal
router test seam (DockFloatingPaneRouter.AppendToWindowForTest) to build a
real multi-pane float deterministically without the OS-cursor hit-test.
Single real window, no tear-off preview, so no multi-window teardown AV risk.

M2: extend T12b to pin BOTH migration legs -- assert the source float emits
MigratedToFloat carrying pane a, and exactly two migration closes fire
(source emptied into preview, then preview docked back), nothing spurious.

Verified: T12c fails on a negative-control (guard re-added) and passes with
the fix; T12b/T08b/FloatCov selftests green; 630 Docking unit tests pass.
M1 (object-keyed pending-close map) intentionally unchanged per prior triage.

Co-authored-by: Copilot <[email protected]>

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.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 1 comment.

Addresses the #642 review comment on DockDragSession.MarkConsumed: when a
host drop-confirm path calls the no-arg MarkConsumed() after the drag
session was already ended/cancelled (the call sites guard session?.End()
as nullable, so DockDragSession.Current can be null), the old code set
Consumed=true with LastConsumedPane=null. Downstream, MigratedReasonFor
skipped its identity guard on a null consumed-pane and reported a
migration for ANY pane's next close until the following Begin -- the same
#417 ambiguity resurfacing through a poisoned global.

Two-part fix:
- Source guard: MarkConsumed resolves pane ?? Current?.Source and no-ops
  when both are null, so Consumed is never persisted without a concrete
  pane.
- Consumer hardening (defense-in-depth): MigratedReasonFor treats a null
  LastConsumedPane as 'matches no pane' (ContentClosed), so the seam stays
  correct regardless of how Consumed was set.

Adds MarkConsumed_NoActiveSession_DoesNotPersistConsumedState regression
test. All 631 Docking unit tests pass.

Co-authored-by: Copilot <[email protected]>

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.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated no new comments.

@azchohfi
Alexandre Zollinger Chohfi (azchohfi) merged commit cbf6795 into main Jun 25, 2026
19 checks passed
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) deleted the azchohfi-dock-floating-close-reason branch June 25, 2026 22:18
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.

Docking: OnFloatingWindowClosed can't be distinguished from cross-window dock-back

2 participants