Window close confirmation

On this page

Use DesktopWindowOptions.ConfirmCloseAsync when closing a native window can discard application state. The application owns the decision and its UI; Desktop owns native interception and window lifetime. No viewmodel or CommunityToolkit adapter is involved.

In a Runic Application Views app, set GuardClose on the RunicWindow<T> instead, so the departure guards of its navigation regions decide; see Guard the Window close. A Window that has both asks its own guard first, then ConfirmCloseAsync.

await using var window = await surface.OpenWindowAsync(new DesktopWindowOptions
{
    Browser = BrowserKind.Embedded,
    ConfirmCloseAsync = async cancellationToken =>
    {
        // An application-specific function owned by the presentation's state layer.
        using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        timeout.CancelAfter(TimeSpan.FromMinutes(10));
        var answer = await surface.ExecuteJavaScriptAsync(
            "return await window.confirmUnsavedChanges?.() === true;", timeout.Token);
        return answer == "true";
    },
});

// Application close buttons should use the same policy as the title-bar close button.
bool closed = await window.RequestCloseAsync(cancellationToken);

The application supplies ConfirmCloseAsync and owns the confirmation UI and its policy. Keep the decision tied to current application state; disconnected or unknown state should keep the window open. A native close callback must stay responsive while the confirmation is pending.

Since SDK 0.11.0, a confirmation that must follow the platform's button order and keys, or that runs while the page cannot answer, can ask with a native message box (IWindowPlatformServices.MessageBoxes; see desktop services). DesktopWindow.Closed is raised once after the window closed, whatever closed it, such as the user, RequestCloseAsync, CloseAsync or disposal; a handler that throws is logged as event 3013. HideAsync and SetVisibleAsync(false) hide an embedded window without closing it, so they ask no confirmation, and the hidden window's page keeps running. A GTK 4 window closed natively now completes WaitForCloseAsync and surface disposal.

Contract #

  • The native close event is suppressed immediately. The callback runs on the thread pool, so the OS event loop and bridge remain responsive while it awaits a dialog. Marshal any native UI work to its owning thread; JavaScript calls already use the authenticated presentation channel.
  • true approves destruction; false, an exception or cancellation keeps the window open. Failures produce a redacted trace message. A later close request retries.
  • Concurrent native and RequestCloseAsync attempts share the pending decision. Cancelling one request's caller token stops that caller's wait; it does not cancel another caller's decision. Forced shutdown cancels the callback's lifetime token.
  • There is no automatic prompt deadline. A user may leave a confirmation unanswered. Bound external calls yourself: the reference's script call has a ten-minute timeout.
  • CloseAsync, surface/host disposal and application shutdown bypass confirmation. They can release resources even if a callback ignores cancellation. A late approval cannot close a subsequently opened replacement window.
  • Bridge invocation completion and domain-task completion are separate. A cancelled ReactiveUI invocation can finish before its accepted workflow finishes recovery. Retain and await application-owned work during asynchronous disposal; see operations and cancellation.
  • This intercepts ordinary user close requests. It does not promise interception of OS session termination, process killing, crashes, or power loss. Durable drafts require a separate persistence policy.
  • Since SDK 0.15.0, a Windows window whose WebView2 starts slowly shows a loading surface first (see the early first window). Closing it then closes it without asking the callback, because no page has loaded: OpenWindowAsync returns the window closed and no fallback opens.
  • Since SDK 0.12.0, quitting on macOS asks too: Command and Q, Quit in the Dock, a script's quit event and logging out ask DesktopHostOptions.ConfirmQuitAsync, then each window's callback in turn, before ShutdownRequested is cancelled and the remaining windows close without asking. A refusal keeps the application running and cancels the logout. Before, Command and Q only asked each window, and the Dock, scripts and logout skipped the callbacks. See quitting on macOS.

Owned Windows #

Since SDK 0.16.0, a window can belong to another. DesktopWindowOptions.Owner and Modality = DesktopWindowModality.Window open a window that the owner owns and that blocks the owner until it closes, as a dialog does. Runic Windows use RunicWindowOptions.Owner and Modality; see Owned and window-modal Windows and the Runic.Desktop README.

  • A close that the owner's ConfirmCloseAsync or GuardClose decides (the user's, or RequestCloseAsync) and a quit first ask the windows it owns, innermost first and the last opened first. One that refuses keeps the owner open; a window-modal one that agrees closes before the owner is asked.
  • CloseAsync, DisposeAsync and the close of an owner without a confirmation close the owned windows without asking. A pending OpenForResultAsync then returns no result.
  • Owned windows hide and show with their owner (SetVisibleAsync).
  • A blocked owner ignores the user's and the window manager's close on every platform, so its own confirmation never shows behind its modal window.
  • On macOS a window-modal window is a sheet, which has no title-bar close button and which Esc does not close: its page needs a Cancel button.

To test a Window's close decision, open it headless with RunicWindowTestHost.CreateWindowAsync<TWindow>(services). RequestUserCloseAsync() closes it as the user does and returns whether its guard let it close:

await using var shell = await RunicWindowTestHost.CreateWindowAsync<ShellWindow>(services);

// A guarded editor keeps unsaved changes.
(await shell.Root<ShellViewModel>().ExecuteAsync(vm => vm.OpenDocumentCommand, "\"notes.md\"")).ThrowIfFailed();
var editor = shell.OpenedWindows.Single();
Assert.Equal("notes.md", editor.Key);
Assert.False(await editor.RequestUserCloseAsync());

On a blocked Window RequestUserCloseAsync() throws InvalidOperationException, as the desktop ignores that close; see Real Windows in tests.

Platform and custom-host support #

Presentation Interception Forced destruction
Windows WebView2 WM_CLOSE (also used by the existing WebView2 close notification) DestroyWindow on the owning UI thread
Linux GTK 3 / WebKitGTK delete-event returns true while the decision runs gtk_widget_destroy on the GTK dispatcher
Linux GTK 4 / WebKitGTK 6 close-request returns true while the decision runs Window destruction on the GTK 4 dispatcher
macOS WKWebView windowShouldClose: returns false while the decision runs NSWindow.close on the main thread
Installed browser No native close confirmation capability Existing browser lifecycle

The native hooks follow the platform contracts for Windows close requests, GTK delete-event, and AppKit windowShouldClose.

Configured confirmation requires the embedded WebView: an explicitly selected browser is rejected with close-confirmation-unavailable, and a browser fallback (EmbeddedThenBrowser or, since SDK 0.15.0, DesktopWindowOptions.Fallbacks) opens without it and reports the same code as a warning. Rejecting unsupported configuration avoids silently dropping a data-loss guard. DesktopWindowCapabilities.CloseConfirmation reflects the actual embedded host.

Custom window hosts (stable since SDK 0.10.0; see custom window hosts) remain source compatible: IDesktopWindowHost.SupportsCloseConfirmation defaults to false. To opt in, return true and honor DesktopWindowHostOptions.CloseRequested: when it is set, suppress the native user close event and invoke the callback instead. Keep CloseAsync unconditional and raise Closed after native destruction. An opted-out host is rejected before opening when the application supplies a confirmation policy. Since SDK 0.16.0, a host that reports DesktopWindowCapabilities.Ownership receives a window's owner in DesktopWindowHostOptions.OwnerHandle and its Modality.

AppKit still requires a main-thread entry point and event pumping. The dedicated Desktop smoke test provides that runner. The higher-level asynchronous DesktopApplicationHost does not yet provide it, so the customer reference's native mode currently targets Windows/Linux; browser mode remains available on macOS.

CS-WebUI (preview) #

Since SDK 0.23.0 (with CsWebUi 2.5.0-beta.4.10), a Window with GuardClose in a UseWebView window of Runic.Application.Views.CsWebUi on Windows (WebView2) or Linux (WebKitGTK) stays open while its CanCloseAsync decides the close button, Alt+F4 or the window manager's close, as on Runic Desktop, and RequestCloseAsync asks the same guard. A close drain (RunicWindowOptions.CloseDrain, or RunicCsWebUiHostOptions.CloseDrain for every Window) keeps such a window open, with its page connected and receiving closing with draining: true, until the Window's work has ended. Serve-only mode drains too, on both hosts: the end of serving is the Window's close.

A browser window, a macOS WebView and a ShowWindow window still cannot keep a window open: a guarded Window opens unguarded and logs WindowCloseGuardUnavailable (event 1053), and a drain closes at once with WindowCloseDrainUnavailable (event 1055). See closing a window.

Verification #

The Runic.Desktop.Tests managed suite covers confirmation policy, shared requests, cancellation, forced shutdown, stale window references, surface reuse, custom-host opt-in and unsupported browser policies.

Runic.Desktop.WebViewSmoke sends actual native close requests: WM_CLOSE, gtk_window_close scheduled on the GTK thread, or AppKit performClose: on the main thread. It checks bridge responsiveness during the pending decision, veto, retry and approved destruction. Root CI runs this smoke on Linux x64, Windows x64 and macOS Apple Silicon. Local execution evidence is retained with the native smoke outputs; adding CI coverage is not evidence that a remote platform run has passed.

The GTK 4 provider's native smoke also exercises close veto/retry on its own dispatcher. Select the native backend you ship when verifying your application's close and cleanup behavior.

Presentation-owned native work #

DesktopWindow.SupportsNativeDispatch, CheckNativeAccess() and InvokeNativeAsync(Action<nint>, CancellationToken) expose the verified native owner boundary. The callback receives an HWND on Windows, GtkWindow on Linux or NSWindow on macOS; these identities are not interchangeable. Queued cancellation prevents invocation. Once a callback starts, its completion is observed even if the caller cancels. Never retain the handle beyond the owning presentation or send it to JavaScript.

Runic's hosts create the native file dialogs, launchers and clipboard of each window. For an embedded Desktop window you open yourself, create them with DesktopPlatformServices.ForWindow(new DesktopNativeOwner(window)) (see platform services); the application owns the service lifetime and disposes services while the native event loop remains active. On macOS use DesktopEventLoop.Run(Func<Task>) when composing asynchronous cleanup around Desktop directly so AppKit stays on its main thread until disposal completes. Applications built on Views get the same from RunicDesktopHost.Run.