From f3d59d28e4126f65559952edca49f48d6e573ece Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 04:51:31 +0700 Subject: [PATCH 1/6] test(windows): roll back right after cancelling the close prompt --- .../tests/TablePro.App.UITests/AppSession.cs | 8 +++--- .../TablePro.App.UITests/TabWindowTests.cs | 27 +++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/windows/tests/TablePro.App.UITests/AppSession.cs b/windows/tests/TablePro.App.UITests/AppSession.cs index 0047d89207..f2b4f6e692 100644 --- a/windows/tests/TablePro.App.UITests/AppSession.cs +++ b/windows/tests/TablePro.App.UITests/AppSession.cs @@ -268,11 +268,13 @@ public void Check(AutomationElement row, bool isChecked = true) row.Click(); } - // The ContentDialog template names its primary button PrimaryButton. - public void PressDialogButton() + // The ContentDialog template names its primary button PrimaryButton; a name tells it from a dialog still closing. + public void PressDialogButton(string? name = null) { var button = Retry.WhileNull( - () => Window.FindFirstDescendant(condition => condition.ByAutomationId("PrimaryButton")), + () => Window.FindFirstDescendant(condition => name is null + ? condition.ByAutomationId("PrimaryButton") + : condition.ByAutomationId("PrimaryButton").And(condition.ByName(name))), Wait, throwOnTimeout: false).Result ?? throw Failure("No dialog opened.", screen: true); diff --git a/windows/tests/TablePro.App.UITests/TabWindowTests.cs b/windows/tests/TablePro.App.UITests/TabWindowTests.cs index 2c31e43dc4..407654b48e 100644 --- a/windows/tests/TablePro.App.UITests/TabWindowTests.cs +++ b/windows/tests/TablePro.App.UITests/TabWindowTests.cs @@ -245,6 +245,33 @@ public void CancellingCloseSelectsTheConnectionWhoseTransactionWasShown(string t app.PressDialogButton(); } + // The cancelled prompt is still playing its closing transition when Roll back asks. + [Theory] + [MemberData(nameof(Themes))] + public void RollBackRightAfterCancellingCloseStillAsks(string theme) + { + var folder = AppSession.NewDataFolder(theme); + var state = new + { + connections = new[] + { + new { filePath = AppSession.SampleDatabase(folder), name = "First", engineId = "sqlite", + tabs = new[] { new { kind = "Query", title = "Query 1", sql = "BEGIN" } } }, + }, + front = 0, + }; + File.WriteAllText(Path.Combine(folder, "session.json"), JsonSerializer.Serialize(state)); + using var app = AppSession.Relaunch(folder, theme); + app.Find("SqlEditor"); + app.Chord(() => app.TryFind("CommitButton") is { IsOffscreen: false }, VirtualKeyShort.CONTROL, VirtualKeyShort.ENTER); + app.Chord(() => app.TryFind("PrimaryButton") is not null, VirtualKeyShort.ALT, VirtualKeyShort.F4); + app.CloseDialog(); + app.Find("RollBackButton").AsButton().Invoke(); + app.PressDialogButton("Roll back"); + Assert.True(Retry.WhileFalse(() => app.TryFind("CommitButton") is null or { IsOffscreen: true }, + AppSession.Wait, throwOnTimeout: false).Success); + } + private static void OpenTrack(AppSession app) { app.Click(app.Find("SampleCard"), () => app.TryFind("Rail_Chinook (Sample)") is not null); From 8983dc4c420e990c1684ceebe1deca2fb3672630 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 04:51:32 +0700 Subject: [PATCH 2/6] fix(windows): ask a question that comes while the last answer's dialog closes --- .../TablePro.App/Services/WindowDialogs.cs | 44 +++++++++++++++++-- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/windows/src/TablePro.App/Services/WindowDialogs.cs b/windows/src/TablePro.App/Services/WindowDialogs.cs index cce88df929..b628fb02b6 100644 --- a/windows/src/TablePro.App/Services/WindowDialogs.cs +++ b/windows/src/TablePro.App/Services/WindowDialogs.cs @@ -8,8 +8,11 @@ namespace TablePro.App.Services; internal static class WindowDialogs { private static readonly HashSet OpenRoots = []; + private static int _closing; private static TaskCompletionSource? _free; + private static TaskCompletionSource? _closed; + // An answered dialog still plays its closing transition, but no longer counts as open. public static bool IsOpen(XamlRoot? root) => root is not null && OpenRoots.Contains(root); // A dialog nobody asked for just then, as a link from another launch, waits for the window and any open dialog. @@ -50,14 +53,33 @@ void OnLoaded(object sender, RoutedEventArgs args) public static async Task ShowAsync(ContentDialog dialog, FrameworkElement owner) { + // A question asked during the last answer's closing transition, as a click right after Cancel, waits for it. + while (OpenRoots.Count == 0 && _closing > 0) + { + await (_closed ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).Task + .ConfigureAwait(true); + } + if (owner.XamlRoot is not { } root || OpenRoots.Count > 0) { return ContentDialogResult.None; } OpenRoots.Add(root); + var answered = false; + void OnClosing(ContentDialog sender, ContentDialogClosingEventArgs args) + { + if (!args.Cancel && !answered) + { + answered = true; + _closing++; + Release(root); + } + } + // Closing or moving the owner must dismiss its prompt before that root is gone. void OnUnloaded(object sender, RoutedEventArgs args) => dialog.Hide(); + dialog.Closing += OnClosing; owner.Unloaded += OnUnloaded; try { @@ -71,13 +93,27 @@ public static async Task ShowAsync(ContentDialog dialog, Fr } finally { + dialog.Closing -= OnClosing; owner.Unloaded -= OnUnloaded; - OpenRoots.Remove(root); - if (OpenRoots.Count == 0 && _free is { } free) + if (!answered) { - _free = null; - free.TrySetResult(); + Release(root); } + else if (--_closing == 0 && _closed is { } closed) + { + _closed = null; + closed.TrySetResult(); + } + } + } + + private static void Release(XamlRoot root) + { + OpenRoots.Remove(root); + if (OpenRoots.Count == 0 && _free is { } free) + { + _free = null; + free.TrySetResult(); } } } From 0b04d99c6ee7b5534b9a6939980aad0289c2232e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 04:53:02 +0700 Subject: [PATCH 3/6] docs(windows): record the dialog rule's closing transition --- windows/docs/decisions/0004-app-shell.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/windows/docs/decisions/0004-app-shell.md b/windows/docs/decisions/0004-app-shell.md index 77528d429b..abe170a263 100644 --- a/windows/docs/decisions/0004-app-shell.md +++ b/windows/docs/decisions/0004-app-shell.md @@ -122,7 +122,7 @@ On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL - Table tabs page as macOS pages a table: a page is the default page size long (Settings, Pagination: 100, 500, 1,000, 5,000 or 10,000 rows, 1,000 unless changed, as macOS); First, Previous, Next and Last sit in the tab's `CommandBar`, and its one status words the page as the macOS status bar does, with the run's time: "1,001-2,000 of 3,503 rows · 15 ms", or "Rows 1,001-2,000 · 15 ms" until the count lands. A table that fits one page keeps "Rows: 347 · 12 ms". The core writes each page (`table_query` takes an offset, over `build_page`'s `PagePosition::Offset`) and counts the table (`table_row_count`, `build_count` as the Linux pager counts), in the background after the first full page; until the count lands, Next stays while pages come back full. Before it counts, it reads the engine's estimate (`table_row_estimate`, over `Connection::table_estimate`, as the Linux pager does), and decides as macOS does: an exact count the engine keeps is the total; under the threshold (Settings, Pagination, Count rows if estimate less than: 1,000, 10,000, 100,000, 1,000,000 or Always count, 100,000 unless changed, as macOS), or with no estimate, the server counts; from the threshold on nothing is counted, the status says "1-1,000 of about 2,000,000 rows" (no total under a filter), and Count rows in the command bar counts on request. Last page, Go to page and All rows wait for an exact count. A sort or a refresh goes back to the first page, and a refresh counts again. An engine that pages on the server (Cassandra) cannot seek by offset, so it has only its first page, as on macOS, and the core refuses another (`ffi.page_unsupported`). - Rows per page: a "1,000 rows" button before First page opens the macOS sizes, 5, 10, 20, 100, 500 and 1,000, as `RadioMenuFlyoutItem`s, then All rows..., which asks first and needs the count, and Custom..., up to 1,000,000. A new size keeps the page that holds the first row shown, as macOS does. The size belongs to the tab: `session.json` keeps it with the tab's page, and Reopen closed tab brings both back. - Go to page: between Previous and Next, "Page 3 of 36" opens a flyout with a `NumberBox` from 1 to the page count, as macOS asks in a popover. It is offered once the table is counted, as on macOS, and the box keeps a typed number inside that range (`InvalidInputOverwritten`). -- An open transaction: each run's `Finished` event carries the transaction the editor's connection is left in (the core's `RunSummary.transaction_state`). The tab that holds one shows a Warning `InfoBar` above its results, "Transaction open", with Roll back, which asks first, and Commit, hidden on a read-only connection; a failed one is an Error bar with Roll back only. Both send COMMIT or ROLLBACK as typed SQL, EXEC or DISCARD for a key-value engine, as the Linux app does. Over the tabs, a bar names another tab that holds one, with Show; macOS shows its bar above every tab of the connection, and here the owning tab carries the actions, since the transaction lives on that tab's own connection. Closing a tab that holds one asks first, since closing rolls it back. Window close and Exit confirm every affected held transaction before closing any tabs; cancelling keeps them open. Then one dialog lists every query tab still running, as macOS asks before it quits, and says closing rolls back a transaction a run has open; a table tab loading a page is not asked about. Exit then hides the windows and closes every connection, each tab stopping its run, for up to 5 seconds before the process ends. While any tab holds a transaction or unsaved changes, the primary window registers a reason with `ShutdownBlockReasonCreate` ("Table changes are not saved.", "A transaction is open.") and answers `WM_QUERYENDSESSION` with FALSE once it has written the session file: a sign-out or a restart then lists TablePro with its reason and the user can cancel and save, and a Restart Manager request, as from an installer, is cancelled ([Application Shutdown Changes in Windows Vista](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms700677(v=vs.85)); Restart Manager, [Guidelines for Applications](https://learn.microsoft.com/en-us/windows/win32/rstmgr/guidelines-for-applications)). A running query does not hold it, since stopping it is the default. A forced end cannot be held: "Sign out anyway" (`ENDSESSION_CRITICAL`) goes on to `WM_ENDSESSION`, which writes the session file again, and a forced Restart Manager close, as an update that closes the app by force, ends the process with no `WM_ENDSESSION`. Either way the server rolls the transaction back, and the session file already holds the work, as Restart Manager's guidelines ask: each table tab's pending changes, with the open cell editor's text as if it were kept (each change of that text starts the 2-second write too), a data row named by its primary key's values, each with the kind the core read it as so a BLOB and a text that read alike stay apart, and a cell by its column's name (a table with no primary key keeps none, since nothing finds its rows again), and each tab that held a transaction (`SavedEdits`, `SessionTab`). The app registers with `RegisterApplicationRestart` at startup (`RESTART_NO_CRASH | RESTART_NO_HANG`, no arguments), so Restart Manager starts it again after an update or a restart, and the new process claims the data folder as any launch does. A launch whose session holds such work reopens those connections and tabs even with Reopen at startup off (`SessionState.Recovered`). A table tab puts its changes back as pending once a page is read, each on the row its key finds there; a key two rows of the page share finds neither. What the page cannot take (a row not on it, a column gone, a value refused, every change while the table is locked) waits on the tab, and each later page read tries it again, so going to the row's page brings it back; a new row goes back whole or waits whole, since each try adds it again. An InfoBar over the rows says how many wait, with Discard, which drops only those and asks nothing more, and closes once none are left. Before a save sends its first statement, the session file is written at once with that tab's changes marked uncertain (`SavedRowEdit.Uncertain`), a write the file refuses being logged and the save going on; the change-triggered write that follows the save's answer clears the mark. Changes from a save whose outcome was unknown keep it too. The server may hold changes so marked already, so once any goes back, the tab is in the state an unknown outcome leaves it in, Save refused with "The last save may have been written" until a reload or Discard changes, and the bar says so. A query tab that held a transaction shows an InfoBar that it was open when TablePro last closed and the server rolled it back; the words name no cause, since a crash or a kill keeps the same work from the write before it. Only the session's own writes carry the work: the last write of a close or Exit leaves out what its questions covered, and a reconnect, a tab window's close and Reopen closed tab never carry it, so an answered change does not come back. Changes still waiting on a tab, and a connection not opened since, keep theirs in every write, Exit's last one too, since nothing has asked about them. Disconnect, Reconnect and connecting an edited connection ask about held transactions the same way first, in the primary and in a tab window, but not about a running query, which they stop, and Reconnect and an edited connection bring the tabs back with their text on the new session. Cancelling that connect keeps the connection with Retry, so the tabs still come back. A window with a dialog already open waits for it to be dismissed before accepting a close request. WinUI opens one `ContentDialog` per thread, even across windows, so a question asked while another window shows one is declined, as Cancel would decline it (`WindowDialogs`). +- An open transaction: each run's `Finished` event carries the transaction the editor's connection is left in (the core's `RunSummary.transaction_state`). The tab that holds one shows a Warning `InfoBar` above its results, "Transaction open", with Roll back, which asks first, and Commit, hidden on a read-only connection; a failed one is an Error bar with Roll back only. Both send COMMIT or ROLLBACK as typed SQL, EXEC or DISCARD for a key-value engine, as the Linux app does. Over the tabs, a bar names another tab that holds one, with Show; macOS shows its bar above every tab of the connection, and here the owning tab carries the actions, since the transaction lives on that tab's own connection. Closing a tab that holds one asks first, since closing rolls it back. Window close and Exit confirm every affected held transaction before closing any tabs; cancelling keeps them open. Then one dialog lists every query tab still running, as macOS asks before it quits, and says closing rolls back a transaction a run has open; a table tab loading a page is not asked about. Exit then hides the windows and closes every connection, each tab stopping its run, for up to 5 seconds before the process ends. While any tab holds a transaction or unsaved changes, the primary window registers a reason with `ShutdownBlockReasonCreate` ("Table changes are not saved.", "A transaction is open.") and answers `WM_QUERYENDSESSION` with FALSE once it has written the session file: a sign-out or a restart then lists TablePro with its reason and the user can cancel and save, and a Restart Manager request, as from an installer, is cancelled ([Application Shutdown Changes in Windows Vista](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms700677(v=vs.85)); Restart Manager, [Guidelines for Applications](https://learn.microsoft.com/en-us/windows/win32/rstmgr/guidelines-for-applications)). A running query does not hold it, since stopping it is the default. A forced end cannot be held: "Sign out anyway" (`ENDSESSION_CRITICAL`) goes on to `WM_ENDSESSION`, which writes the session file again, and a forced Restart Manager close, as an update that closes the app by force, ends the process with no `WM_ENDSESSION`. Either way the server rolls the transaction back, and the session file already holds the work, as Restart Manager's guidelines ask: each table tab's pending changes, with the open cell editor's text as if it were kept (each change of that text starts the 2-second write too), a data row named by its primary key's values, each with the kind the core read it as so a BLOB and a text that read alike stay apart, and a cell by its column's name (a table with no primary key keeps none, since nothing finds its rows again), and each tab that held a transaction (`SavedEdits`, `SessionTab`). The app registers with `RegisterApplicationRestart` at startup (`RESTART_NO_CRASH | RESTART_NO_HANG`, no arguments), so Restart Manager starts it again after an update or a restart, and the new process claims the data folder as any launch does. A launch whose session holds such work reopens those connections and tabs even with Reopen at startup off (`SessionState.Recovered`). A table tab puts its changes back as pending once a page is read, each on the row its key finds there; a key two rows of the page share finds neither. What the page cannot take (a row not on it, a column gone, a value refused, every change while the table is locked) waits on the tab, and each later page read tries it again, so going to the row's page brings it back; a new row goes back whole or waits whole, since each try adds it again. An InfoBar over the rows says how many wait, with Discard, which drops only those and asks nothing more, and closes once none are left. Before a save sends its first statement, the session file is written at once with that tab's changes marked uncertain (`SavedRowEdit.Uncertain`), a write the file refuses being logged and the save going on; the change-triggered write that follows the save's answer clears the mark. Changes from a save whose outcome was unknown keep it too. The server may hold changes so marked already, so once any goes back, the tab is in the state an unknown outcome leaves it in, Save refused with "The last save may have been written" until a reload or Discard changes, and the bar says so. A query tab that held a transaction shows an InfoBar that it was open when TablePro last closed and the server rolled it back; the words name no cause, since a crash or a kill keeps the same work from the write before it. Only the session's own writes carry the work: the last write of a close or Exit leaves out what its questions covered, and a reconnect, a tab window's close and Reopen closed tab never carry it, so an answered change does not come back. Changes still waiting on a tab, and a connection not opened since, keep theirs in every write, Exit's last one too, since nothing has asked about them. Disconnect, Reconnect and connecting an edited connection ask about held transactions the same way first, in the primary and in a tab window, but not about a running query, which they stop, and Reconnect and an edited connection bring the tabs back with their text on the new session. Cancelling that connect keeps the connection with Retry, so the tabs still come back. A window with a dialog already open waits for it to be dismissed before accepting a close request. WinUI opens one `ContentDialog` per thread, even across windows, so a question asked while another window shows one is declined, as Cancel would decline it (`WindowDialogs`). A dialog stops counting as open once it is answered, though WinUI plays its closing transition before `ShowAsync` returns, and a question asked during that transition, as Roll back clicked right after Cancel, waits for it to end. - Safe Mode: before a typed run the core judges each statement at the connection's level (`DatabaseSession.gate_run`, over `SafeModeLevel::gate`, as the Linux editor judges its batches). Confirm writes asks before any write, and Off before a DROP, a TRUNCATE, or a DELETE or UPDATE with no WHERE. The question is a `ContentDialog` that lists each statement in full, with Cancel as the default. Read only keeps the whole run back, since the editor sends the text it runs whole: the selection, the whole text, or with Run statement the one statement. The driver splits that text with the session's own settings, so when the whole text reads stricter than every statement, the question shows the whole text. A MySQL script with DELIMITER lines is judged statement by statement, since the driver sends its statements apart. A level saved while the connection is open applies at once to its sessions in every window (`set_safe_mode`), as on Linux, and a connect still under way starts over when the save changed a field it reads or a secret, since the core read the saved connection as it began; a change to or from Read only takes a new connection, so those sessions reconnect once their held transactions are confirmed. A session that keeps its connection shows "Changes apply the next time you connect", as Linux says it, and one that cannot take Read only asks before every write until then. Statements are judged by the connection's own engine, also while its link is down and a tab's own connection still runs (`Session::grammar`). Commit, Roll back and a sort's rerun are not asked about. Closing a tab stops its run and waits for it to end before its connection closes. - Lifecycle: running, closing, paging, sorting, a lost editor, the session share and connecting are plain types in `src/TablePro.App.Model` (`QueryTab`, `TableTab`, `WorkspaceTabs`, `ConnectionLife`, `SessionShare`) over `ITabSession`, `ITabEditor` and `ITabRun`, with the core's adapters beside them. The views draw and ask through small view interfaces (`IQueryTabView`, `ITableTabView`, `IResultsView`, `IWorkspaceTabsView`, `IConnectionView`), so the model tests run them with fakes. - A table tab edits its page's rows, keeps the changes pending until Save, and asks before a reload or a close would lose them ([0006](0006-editing-table-rows.md)). @@ -174,6 +174,7 @@ Facts the CI runs on `windows-2025` and `windows-11-arm` established, which the - The Toolkit's `GridSplitter` in an `Auto` column of its own resized nothing; on the left edge of the star column after the pane, as its page lays it out, it resizes the pane. - FlaUI moves the pointer with `SetCursorPos`, which WinUI does not take as a pointer moving with the button down, so neither a tree drag nor the splitter moved. The UI tests drag through `SendInput`. - A closed `InfoBar` stays in the UI Automation tree with its content folded away, so the tests read whether a bar shows from its buttons. +- On `windows-11-arm`, an answered `ContentDialog` returned from `ShowAsync` 210 to 350 ms after its `Closing` event (run 43643257678). `WindowDialogs` counted it as open until then, so a Roll back invoked within that time was declined as Cancel would decline it, and `CancellingCloseSelectsTheConnectionWhoseTransactionWasShown` failed in runs 43447041133 and 43537927072. A dialog now stops counting at `Closing`, and the next question waits for the transition. - A grid given a new set as the set started had no rows until the first ones arrived, and a client that had asked for a cell before then read its name after: WinUI reports an empty name as none, so FlaUI threw `PropertyNotSupportedException` (x64, once in run 41566360608). The pane now hands the grid a set once it has rows, and a cell peer outside the grid's current data reads as empty, off screen and with no bounds, and takes no selection. - On `windows-11-arm`, a rebuilt library tree folded rows the page had opened, in a pass of the tree's own after the page's, and the folds read as the user's. The page opens the rows again at low priority and records no fold until then. - On `windows-2025` the app died three times in run 41581443963 (0xC0000005 in `UpdateLayout`), each in one of those low-priority passes. The page now skips a pass once its window has closed. A passing run cannot show whether it still happens: the test platform prints the app's error output only when a test fails. From af9c9db68464b93e3aa36b293d6622e31e6168a9 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 04:57:29 +0700 Subject: [PATCH 4/6] fix(windows): keep a link's question queued and a cancelled credential prompt unshown while a dialog closes --- .../Services/CredentialDialogs.cs | 2 +- .../TablePro.App/Services/WindowDialogs.cs | 29 +++++++++++++++---- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/windows/src/TablePro.App/Services/CredentialDialogs.cs b/windows/src/TablePro.App/Services/CredentialDialogs.cs index 63faac7ede..269dee9cce 100644 --- a/windows/src/TablePro.App/Services/CredentialDialogs.cs +++ b/windows/src/TablePro.App/Services/CredentialDialogs.cs @@ -137,7 +137,7 @@ internal async Task RecoverHostKeyAsync( DefaultButton = trust ? ContentDialogButton.Close : ContentDialogButton.Primary, }; AutomationProperties.SetAutomationId(dialog, "CredentialDialog"); - var shown = WindowDialogs.ShowAsync(dialog, owner); + var shown = WindowDialogs.ShowAsync(dialog, owner, cancellationToken); using var registration = cancellationToken.Register(() => owner.DispatcherQueue.TryEnqueue(dialog.Hide)); var result = await shown; cancellationToken.ThrowIfCancellationRequested(); diff --git a/windows/src/TablePro.App/Services/WindowDialogs.cs b/windows/src/TablePro.App/Services/WindowDialogs.cs index b628fb02b6..266acface9 100644 --- a/windows/src/TablePro.App/Services/WindowDialogs.cs +++ b/windows/src/TablePro.App/Services/WindowDialogs.cs @@ -31,9 +31,13 @@ public static async Task ShowWhenFreeAsync(ContentDialog di await (_free ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).Task .ConfigureAwait(true); } + else if (_closing > 0) + { + await ClosedAsync().ConfigureAwait(true); + } else { - return await ShowAsync(dialog, owner).ConfigureAwait(true); + return await ShowNowAsync(dialog, owner).ConfigureAwait(true); } } } @@ -51,15 +55,30 @@ void OnLoaded(object sender, RoutedEventArgs args) return loaded.Task; } - public static async Task ShowAsync(ContentDialog dialog, FrameworkElement owner) + private static Task ClosedAsync() => + (_closed ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).Task; + + // A question asked during the last answer's closing transition, as a click right after Cancel, waits for it. + public static async Task ShowAsync( + ContentDialog dialog, FrameworkElement owner, CancellationToken cancellationToken = default) { - // A question asked during the last answer's closing transition, as a click right after Cancel, waits for it. while (OpenRoots.Count == 0 && _closing > 0) { - await (_closed ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).Task - .ConfigureAwait(true); + try + { + await ClosedAsync().WaitAsync(cancellationToken).ConfigureAwait(true); + } + catch (OperationCanceledException) + { + return ContentDialogResult.None; + } } + return await ShowNowAsync(dialog, owner).ConfigureAwait(true); + } + + private static async Task ShowNowAsync(ContentDialog dialog, FrameworkElement owner) + { if (owner.XamlRoot is not { } root || OpenRoots.Count > 0) { return ContentDialogResult.None; From 71bf0cc6a64ae71a45150374f8855655e0f4dd6e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 05:00:31 +0700 Subject: [PATCH 5/6] fix(windows): keep a question asked during a closing transition until it is shown or cancelled --- .../TablePro.App/Services/WindowDialogs.cs | 64 +++++++++++-------- 1 file changed, 36 insertions(+), 28 deletions(-) diff --git a/windows/src/TablePro.App/Services/WindowDialogs.cs b/windows/src/TablePro.App/Services/WindowDialogs.cs index 266acface9..e9ef20250f 100644 --- a/windows/src/TablePro.App/Services/WindowDialogs.cs +++ b/windows/src/TablePro.App/Services/WindowDialogs.cs @@ -8,11 +8,12 @@ namespace TablePro.App.Services; internal static class WindowDialogs { private static readonly HashSet OpenRoots = []; + // Answered dialogs still playing their closing transition, and questions asked during one. private static int _closing; - private static TaskCompletionSource? _free; - private static TaskCompletionSource? _closed; + private static int _waiting; + private static TaskCompletionSource? _changed; - // An answered dialog still plays its closing transition, but no longer counts as open. + // An answered dialog no longer counts as open, though it still plays its closing transition. public static bool IsOpen(XamlRoot? root) => root is not null && OpenRoots.Contains(root); // A dialog nobody asked for just then, as a link from another launch, waits for the window and any open dialog. @@ -26,14 +27,9 @@ public static async Task ShowWhenFreeAsync(ContentDialog di { await LoadedAsync(owner).ConfigureAwait(true); } - else if (OpenRoots.Count > 0) + else if (OpenRoots.Count > 0 || _closing > 0 || _waiting > 0) { - await (_free ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).Task - .ConfigureAwait(true); - } - else if (_closing > 0) - { - await ClosedAsync().ConfigureAwait(true); + await ChangedAsync().ConfigureAwait(true); } else { @@ -55,26 +51,34 @@ void OnLoaded(object sender, RoutedEventArgs args) return loaded.Task; } - private static Task ClosedAsync() => - (_closed ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).Task; - - // A question asked during the last answer's closing transition, as a click right after Cancel, waits for it. + // A question asked during the last answer's closing transition, as a click right after Cancel, waits its turn. public static async Task ShowAsync( ContentDialog dialog, FrameworkElement owner, CancellationToken cancellationToken = default) { - while (OpenRoots.Count == 0 && _closing > 0) + if (OpenRoots.Count == 0 && _closing > 0) { + _waiting++; try { - await ClosedAsync().WaitAsync(cancellationToken).ConfigureAwait(true); + while (OpenRoots.Count > 0 || _closing > 0) + { + await ChangedAsync().WaitAsync(cancellationToken).ConfigureAwait(true); + } } catch (OperationCanceledException) { return ContentDialogResult.None; } + finally + { + _waiting--; + Changed(); + } } - return await ShowNowAsync(dialog, owner).ConfigureAwait(true); + return cancellationToken.IsCancellationRequested + ? ContentDialogResult.None + : await ShowNowAsync(dialog, owner).ConfigureAwait(true); } private static async Task ShowNowAsync(ContentDialog dialog, FrameworkElement owner) @@ -92,7 +96,8 @@ void OnClosing(ContentDialog sender, ContentDialogClosingEventArgs args) { answered = true; _closing++; - Release(root); + OpenRoots.Remove(root); + Changed(); } } @@ -114,25 +119,28 @@ void OnClosing(ContentDialog sender, ContentDialogClosingEventArgs args) { dialog.Closing -= OnClosing; owner.Unloaded -= OnUnloaded; - if (!answered) + if (answered) { - Release(root); + _closing--; } - else if (--_closing == 0 && _closed is { } closed) + else { - _closed = null; - closed.TrySetResult(); + OpenRoots.Remove(root); } + + Changed(); } } - private static void Release(XamlRoot root) + private static Task ChangedAsync() => + (_changed ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).Task; + + private static void Changed() { - OpenRoots.Remove(root); - if (OpenRoots.Count == 0 && _free is { } free) + if (_changed is { } changed) { - _free = null; - free.TrySetResult(); + _changed = null; + changed.TrySetResult(); } } } From 32cb238cb3f76cdad9852bc3ebb177d1992ef11c Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 05:32:32 +0700 Subject: [PATCH 6/6] docs(windows): record the runs that reproduce and clear the dialog race --- windows/docs/decisions/0004-app-shell.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/windows/docs/decisions/0004-app-shell.md b/windows/docs/decisions/0004-app-shell.md index abe170a263..27b3e43e9c 100644 --- a/windows/docs/decisions/0004-app-shell.md +++ b/windows/docs/decisions/0004-app-shell.md @@ -174,7 +174,7 @@ Facts the CI runs on `windows-2025` and `windows-11-arm` established, which the - The Toolkit's `GridSplitter` in an `Auto` column of its own resized nothing; on the left edge of the star column after the pane, as its page lays it out, it resizes the pane. - FlaUI moves the pointer with `SetCursorPos`, which WinUI does not take as a pointer moving with the button down, so neither a tree drag nor the splitter moved. The UI tests drag through `SendInput`. - A closed `InfoBar` stays in the UI Automation tree with its content folded away, so the tests read whether a bar shows from its buttons. -- On `windows-11-arm`, an answered `ContentDialog` returned from `ShowAsync` 210 to 350 ms after its `Closing` event (run 43643257678). `WindowDialogs` counted it as open until then, so a Roll back invoked within that time was declined as Cancel would decline it, and `CancellingCloseSelectsTheConnectionWhoseTransactionWasShown` failed in runs 43447041133 and 43537927072. A dialog now stops counting at `Closing`, and the next question waits for the transition. +- On `windows-11-arm`, an answered `ContentDialog` returned from `ShowAsync` 210 to 350 ms after its `Closing` event (run 43643257678). `WindowDialogs` counted it as open until then, so a Roll back invoked within that time was declined as Cancel would decline it, and `CancellingCloseSelectsTheConnectionWhoseTransactionWasShown` failed in runs 43447041133 and 43537927072. Roll back invoked right after Cancel was declined in 20 of 20 tries (run 43645046133). A dialog now stops counting at `Closing`, and the next question waits for the transition: the same tries and the original test's steps passed 40 of 40 on `main` and on the branch of #4285 (runs 43645911845 and 43645919130). - A grid given a new set as the set started had no rows until the first ones arrived, and a client that had asked for a cell before then read its name after: WinUI reports an empty name as none, so FlaUI threw `PropertyNotSupportedException` (x64, once in run 41566360608). The pane now hands the grid a set once it has rows, and a cell peer outside the grid's current data reads as empty, off screen and with no bounds, and takes no selection. - On `windows-11-arm`, a rebuilt library tree folded rows the page had opened, in a pass of the tree's own after the page's, and the folds read as the user's. The page opens the rows again at low priority and records no fold until then. - On `windows-2025` the app died three times in run 41581443963 (0xC0000005 in `UpdateLayout`), each in one of those low-priority passes. The page now skips a pass once its window has closed. A passing run cannot show whether it still happens: the test platform prints the app's error output only when a test fails.