Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Desktop: show a closing overlay while the backend shuts down (#8151)

Daniel Han68eefd3ccfc1
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index 0d1e08e5472..c8c5ddfea88 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -2,7 +2,10 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { LlamaUpdateBanner } from "@/components/llama-update-banner";
-import { StartupScreen } from "@/components/tauri/startup-screen";
+import {
+ ClosingScreen,
+ StartupScreen,
+} from "@/components/tauri/startup-screen";
import { UpdateBanner } from "@/components/tauri/update-banner";
import { UpdateScreen } from "@/components/tauri/update-screen";
import {
@@ -519,6 +522,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
progressDetail,
startupMessage,
elevationPackages,
+ closing,
startInstall,
retry,
retryInstall,
@@ -699,7 +703,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
const startupStatus = status === "running" ? "starting" : status;
const startupProgressDetail = progressDetail;
- const content = showApp ? (
+ const shell = showApp ? (
<TauriUpdateLayer
isExternalServer={isExternalServer}
appContent={
@@ -731,6 +735,16 @@ function TauriWrapper({ children }: { children: ReactNode }) {
/>
);
+ // Over the shell, not instead of it: ClosingScreen covers the app and the update layer
+ // alike, and a declined quit puts the user back where they were rather than remounting
+ // the tree under them.
+ const content = (
+ <>
+ {shell}
+ {closing && <ClosingScreen />}
+ </>
+ );
+
const chromeVars = (
<DesktopChromeVarsEffect
usesCustomTitlebar={usesCustomTitlebar}
diff --git a/studio/frontend/src/components/tauri/closing-signal.ts b/studio/frontend/src/components/tauri/closing-signal.ts
new file mode 100644
index 00000000000..b7202a7bae7
--- /dev/null
+++ b/studio/frontend/src/components/tauri/closing-signal.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Rust asks for the closing overlay with this, from the quit thread in main.rs, once the
+ * quit confirmations have passed and only the backend reap is left. Windows is the only
+ * platform that asks: macOS closes to the tray, and the Linux reap never showed the freeze
+ * this covers. Nothing here is platform-aware, so an overlay is whatever Rust asks for.
+ */
+export const APP_CLOSING_EVENT = "app-closing";
+
+/** And takes it back down with this, for a quit that never reaches the exit. */
+export const APP_CLOSING_CANCELLED_EVENT = "app-closing-cancelled";
+
+// Module state rather than React state: the events arrive on the backend hook and the
+// overlay renders from the provider. A webview reload resets it, which fails open: no
+// quit survives the reload either.
+let closing = false;
+const listeners = new Set<(closing: boolean) => void>();
+
+function setAppClosing(next: boolean): void {
+ if (closing === next) {
+ return;
+ }
+ closing = next;
+ // Over a copy: a listener that subscribes or throws mid-notify must not decide which
+ // of the others hear about the quit.
+ for (const listener of [...listeners]) {
+ listener(next);
+ }
+}
+
+export function isAppClosing(): boolean {
+ return closing;
+}
+
+/** Paint the overlay. Idempotent, so a re-emitted app-closing costs no re-render. */
+export function markAppClosing(): void {
+ setAppClosing(true);
+}
+
+/** The quit never reached the exit, so the app stays and the overlay has to go. */
+export function clearAppClosing(): void {
+ setAppClosing(false);
+}
+
+export function subscribeAppClosing(
+ listener: (closing: boolean) => void,
+): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
diff --git a/studio/frontend/src/components/tauri/startup-screen.tsx b/studio/frontend/src/components/tauri/startup-screen.tsx
index 9d6842f18fb..6f398a20303 100644
--- a/studio/frontend/src/components/tauri/startup-screen.tsx
+++ b/studio/frontend/src/components/tauri/startup-screen.tsx
@@ -11,7 +11,7 @@ import { Spinner } from "@/components/ui/spinner";
import type { BackendStatus } from "@/hooks/use-tauri-backend";
import type { CopySupportDiagnosticsResult } from "@/lib/tauri-diagnostics";
import { AnimatePresence, motion } from "motion/react";
-import { useEffect, useState } from "react";
+import { type ReactNode, useEffect, useState } from "react";
interface StartupScreenProps {
status: BackendStatus;
@@ -267,6 +267,23 @@ function RepairingContent({
);
}
+function ClosingContent() {
+ return (
+ <div className="flex h-full w-full flex-col items-center">
+ <div className="flex flex-1 items-center">
+ <Logo />
+ </div>
+ <div className="mb-10 flex w-full flex-col items-center gap-2">
+ <Spinner className="size-6 text-primary" />
+ <p className="text-sm font-bold text-foreground" aria-live="polite">
+ Closing Unsloth Desktop...
+ </p>
+ <p className="text-sm text-muted-foreground">Shutting down the backend.</p>
+ </div>
+ </div>
+ );
+}
+
function InstallErrorContent({
error,
onRetryInstall,
@@ -480,22 +497,57 @@ export function StartupScreen({
}
}
+ return (
+ <StartupSurface>
+ <AnimatePresence mode="wait">
+ <motion.div
+ key={status}
+ className="flex h-full w-full flex-col items-center justify-center text-center"
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: 0.2, ease: EASE_OUT_QUART }}
+ >
+ {renderContent()}
+ </motion.div>
+ </AnimatePresence>
+ </StartupSurface>
+ );
+}
+
+/** The chrome both full-window screens sit in, so they agree on insets and scrolling. */
+function StartupSurface({ children }: { children: ReactNode }) {
return (
<div className="box-border flex h-full w-full flex-col items-center overflow-y-auto bg-background pb-6 pt-[var(--studio-startup-top-inset,0px)]">
<div className="flex min-h-0 flex-1 w-full max-w-md items-center justify-center px-6">
- <AnimatePresence mode="wait">
- <motion.div
- key={status}
- className="flex h-full w-full flex-col items-center justify-center text-center"
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- transition={{ duration: 0.2, ease: EASE_OUT_QUART }}
- >
- {renderContent()}
- </motion.div>
- </AnimatePresence>
+ {children}
</div>
</div>
);
}
+
+/**
+ * Shown from the moment a quit is requested until the process is gone. Separate from
+ * StartupScreen because a quit can come from the running app, where no backend status
+ * applies, and unanimated because it has to be on screen for the very next paint.
+ *
+ * A layer over the app rather than a replacement for it: a declined quit has to hand the
+ * user back the tree they had, in-flight generations and unsaved drafts included. The
+ * z-index clears the titlebar and the download stack, the last of which is 9998.
+ */
+export function ClosingScreen() {
+ return (
+ // pointer-events-auto, not the inherited default: Radix parks pointer-events:none on
+ // <body> while any modal layer is open, and a quit raised from the window controls,
+ // the tray or Alt+F4 never closes that layer. Inheriting it would make the overlay
+ // click-through onto the dialog it is hiding, so clicks meant for a screen that says
+ // the app is closing would land on buttons the user can no longer see.
+ <div className="pointer-events-auto fixed inset-0 z-[9999]">
+ <StartupSurface>
+ <div className="flex h-full w-full flex-col items-center justify-center text-center">
+ <ClosingContent />
+ </div>
+ </StartupSurface>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/components/tauri/window-titlebar.tsx b/studio/frontend/src/components/tauri/window-titlebar.tsx
index a5d0d56c7f9..e8960556a36 100644
--- a/studio/frontend/src/components/tauri/window-titlebar.tsx
+++ b/studio/frontend/src/components/tauri/window-titlebar.tsx
@@ -435,6 +435,11 @@ export function WindowTitlebar({
</WindowControlButton>
<WindowControlButton
label="Close window"
+ // No optimistic overlay here. Rust raises it only once the quit confirmations
+ // have passed, and one of those can be a dialog asking whether to keep
+ // training: painting "Closing Unsloth Desktop..." behind that question would
+ // answer it before the user does. The wait this covers is the reap, and Rust's
+ // app-closing arrives well ahead of that.
onClick={() => runWindowAction((appWindow) => appWindow.close())}
className="hover:bg-destructive/10 hover:text-destructive focus-visible:ring-destructive/70 dark:hover:bg-destructive/20"
>
diff --git a/studio/frontend/src/hooks/use-tauri-backend.ts b/studio/frontend/src/hooks/use-tauri-backend.ts
index 8d76103a489..3f099a2c6dd 100644
--- a/studio/frontend/src/hooks/use-tauri-backend.ts
+++ b/studio/frontend/src/hooks/use-tauri-backend.ts
@@ -1,7 +1,13 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { useEffect, useState, useCallback, useRef } from "react";
+import {
+ useEffect,
+ useState,
+ useCallback,
+ useRef,
+ useSyncExternalStore,
+} from "react";
import { isTauri, setApiBase } from "@/lib/api-base";
import {
copySupportDiagnostics,
@@ -11,6 +17,14 @@ import {
clearTauriAuthFailure,
getTauriAuthFailure,
} from "@/features/auth";
+import {
+ APP_CLOSING_CANCELLED_EVENT,
+ APP_CLOSING_EVENT,
+ clearAppClosing,
+ isAppClosing,
+ markAppClosing,
+ subscribeAppClosing,
+} from "@/components/tauri/closing-signal";
import {
INITIAL_STARTUP_MESSAGE,
SERVER_STARTUP_MESSAGE,
@@ -139,6 +153,9 @@ export function useTauriBackend() {
const authFailureRef = useRef<string | null>(getTauriAuthFailure());
const elevationResumeRef = useRef<"install" | "repair" | null>(null);
const [tauriEventsReady, setTauriEventsReady] = useState(!isTauri);
+ // Read through rather than mirrored into state: the app-closing listener is registered
+ // inside the long event effect below, which cannot reach a setState from this render.
+ const closing = useSyncExternalStore(subscribeAppClosing, isAppClosing);
function setBackendStatus(nextStatus: BackendStatus) {
if (authFailureRef.current) return;
@@ -603,6 +620,16 @@ export function useTauriBackend() {
setStartupMessage((current) => startupMessageFromLog(current, e.payload));
});
+ // Reaping the backend blocks Rust's quit thread for up to ~15s. Cover the window
+ // for that, or it reads as a freeze.
+ register<void>(APP_CLOSING_EVENT, () => {
+ markAppClosing();
+ });
+
+ register<void>(APP_CLOSING_CANCELLED_EVENT, () => {
+ clearAppClosing();
+ });
+
register<void>("tray-toggle-server", () => {
if (statusRef.current === "running") {
stopServer();
@@ -647,7 +674,7 @@ export function useTauriBackend() {
}, []);
return {
- status, logs, error, isExternalServer,
+ status, logs, error, isExternalServer, closing,
currentStepIndex, progressDetail, startupMessage, elevationPackages,
startServer, stopServer, startInstall,
retry, retryInstall, approveElevation, copyDiagnostics,
diff --git a/studio/frontend/tests/desktop-closing-overlay.test.ts b/studio/frontend/tests/desktop-closing-overlay.test.ts
new file mode 100644
index 00000000000..45b24b458f9
--- /dev/null
+++ b/studio/frontend/tests/desktop-closing-overlay.test.ts
@@ -0,0 +1,217 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+// The overlay itself is JSX, which cannot be imported here. So: drive the store the
+// app-closing events write to, then assert the three call sites read and write it.
+import {
+ APP_CLOSING_CANCELLED_EVENT,
+ APP_CLOSING_EVENT,
+ clearAppClosing,
+ isAppClosing,
+ markAppClosing,
+ subscribeAppClosing,
+} from "../src/components/tauri/closing-signal.ts";
+
+function source(path: string): Promise<string> {
+ return readFile(new URL(`../src/${path}`, import.meta.url), "utf8");
+}
+
+/** The ClosingContent body, up to whatever component is declared after it. */
+function closingContent(screen: string): string {
+ const start = screen.indexOf("function ClosingContent()");
+ if (start < 0) {
+ throw new Error("ClosingContent is gone");
+ }
+ return screen.slice(start, screen.indexOf("\nfunction ", start + 1));
+}
+
+test("app-closing raises the overlay and app-closing-cancelled clears it", () => {
+ const seen: boolean[] = [];
+ const unsubscribe = subscribeAppClosing((closing) => seen.push(closing));
+
+ assert.equal(isAppClosing(), false);
+ markAppClosing();
+ assert.equal(isAppClosing(), true, "a requested quit left the app on screen");
+ clearAppClosing();
+ assert.equal(isAppClosing(), false, "a declined quit left the overlay up");
+
+ assert.deepEqual(
+ seen,
+ [true, false],
+ "the provider was not told to re-render",
+ );
+ unsubscribe();
+});
+
+test("a re-emitted app-closing does not re-render the overlay", () => {
+ const seen: boolean[] = [];
+ const unsubscribe = subscribeAppClosing((closing) => seen.push(closing));
+
+ markAppClosing();
+ markAppClosing();
+ assert.deepEqual(seen, [true]);
+
+ clearAppClosing();
+ unsubscribe();
+});
+
+test("an unsubscribed listener stops hearing about quits", () => {
+ const seen: boolean[] = [];
+ subscribeAppClosing((closing) => seen.push(closing))();
+
+ markAppClosing();
+ clearAppClosing();
+ assert.deepEqual(seen, []);
+});
+
+test("the backend hook routes both quit events into the store", async () => {
+ const hook = await source("hooks/use-tauri-backend.ts");
+
+ assert.match(
+ hook,
+ /register<void>\(APP_CLOSING_EVENT,\s*\(\) => \{\s*markAppClosing\(\);/,
+ "app-closing no longer raises the overlay",
+ );
+ assert.match(
+ hook,
+ /register<void>\(APP_CLOSING_CANCELLED_EVENT,\s*\(\) => \{\s*clearAppClosing\(\);/,
+ "a cancelled quit would strand the overlay over a running app",
+ );
+ // Subscribed, not mirrored into state: the listener lives inside the long event effect,
+ // which has no way back to a setState from the render that registered it.
+ assert.match(
+ hook,
+ /const closing = useSyncExternalStore\(subscribeAppClosing, isAppClosing\);/,
+ );
+ assert.match(
+ hook,
+ /isExternalServer, closing,/,
+ "the hook stopped returning the flag",
+ );
+});
+
+test("the overlay covers the app instead of replacing it", async () => {
+ const provider = await source("app/provider.tsx");
+
+ // Unmounting the app subtree would cancel in-flight generations and drop debounced
+ // drafts, and a declined quit has to give all of that back.
+ assert.match(provider, /\{shell\}\s*\{closing && <ClosingScreen \/>\}/);
+ assert.doesNotMatch(
+ provider,
+ /closing \? \(/,
+ "the overlay is back to replacing the app it should be covering",
+ );
+
+ const screen = await source("components/tauri/startup-screen.tsx");
+ const closingScreen = screen.slice(
+ screen.indexOf("export function ClosingScreen()"),
+ );
+ assert.match(
+ closingScreen,
+ /className="[^"]*fixed inset-0 z-\[9999\]"/,
+ "a covering overlay has to outrank the titlebar and the download stack",
+ );
+});
+
+test("the overlay survives a modal's body pointer-events lockout", async () => {
+ const screen = await source("components/tauri/startup-screen.tsx");
+ const closingScreen = screen.slice(
+ screen.indexOf("export function ClosingScreen()"),
+ );
+
+ // Radix parks pointer-events:none on <body> for as long as any modal layer is open,
+ // and pointer-events inherits. A quit raised from the titlebar controls, the tray or
+ // Alt+F4 never closes that layer, so without an explicit auto the overlay is
+ // click-through onto the dialog it is hiding, and clicks meant for a screen that says
+ // the app is closing land on buttons the user can no longer see.
+ assert.match(
+ closingScreen,
+ /className="pointer-events-auto /,
+ "an open dialog would take the clicks aimed at the overlay covering it",
+ );
+});
+
+test("the close button leaves the overlay to Rust", async () => {
+ const titlebar = await source("components/tauri/window-titlebar.tsx");
+
+ // Raising it here would put it behind the quit confirmations, one of which asks whether
+ // to keep training. Rust raises it only once those have passed.
+ assert.doesNotMatch(
+ titlebar,
+ /markAppClosing/,
+ "the close button is raising the overlay before the quit is committed",
+ );
+ assert.match(titlebar, /onClick=\{\(\) => runWindowAction\(\(appWindow\) =>\s*appWindow\.close\(\)\)\}/);
+});
+
+test("the overlay is presentation only, with no way out of a wedged reap", async () => {
+ const signal = await source("components/tauri/closing-signal.ts");
+ const screen = await source("components/tauri/startup-screen.tsx");
+ const body = closingContent(screen);
+
+ // A wedged teardown has no escape, and did not have one before this overlay either: a
+ // second close press, Alt+F4 and the taskbar all land on request_quit, which begin_quit
+ // has already turned into a silent no-op for the life of the reap. The overlay does not
+ // take an escape away, it explains the freeze that was already there.
+ assert.doesNotMatch(
+ signal,
+ /force_quit|forceQuit/,
+ "a force quit command is process management this overlay does not need",
+ );
+ assert.doesNotMatch(body, /Force quit/);
+ // No timer either: nothing in the overlay changes with time, so nothing may schedule
+ // work that outlives a declined quit.
+ assert.doesNotMatch(body, /setTimeout|useState/);
+});
+
+test("a quit with no window on screen raises no overlay", async () => {
+ const rust = await readFile(
+ new URL("../../src-tauri/src/main.rs", import.meta.url),
+ "utf8",
+ );
+
+ // Tray Quit reaches request_quit without going through the main window, and an autostart
+ // launch passes --hidden, whose window is built "visible": false and never shown. The
+ // overlay explains a frozen window, so with no window on screen there is nothing to say.
+ assert.match(
+ rust,
+ /fn quit_raises_the_overlay\(/,
+ "the overlay is raised without asking whether anything is on screen",
+ );
+ assert.match(
+ rust,
+ /app\.get_webview_window\("main"\)\s*\.map\(\|window\| window\.is_visible\(\)/,
+ );
+});
+
+test("the overlay names the wait it is covering", async () => {
+ const screen = await source("components/tauri/startup-screen.tsx");
+ const body = closingContent(screen);
+
+ assert.match(body, /Closing Unsloth Desktop\.\.\./);
+ assert.match(body, /Shutting down the backend\./);
+ // A still screen reads as the freeze it is there to explain.
+ assert.match(body, /<Spinner className="size-6 text-primary" \/>/);
+});
+
+test("both sides agree on the event names", async () => {
+ const rust = await readFile(
+ new URL("../../src-tauri/src/main.rs", import.meta.url),
+ "utf8",
+ );
+
+ assert.match(
+ rust,
+ new RegExp(`const APP_CLOSING_EVENT: &str = "${APP_CLOSING_EVENT}";`),
+ );
+ assert.match(
+ rust,
+ new RegExp(
+ `const APP_CLOSING_CANCELLED_EVENT: &str = "${APP_CLOSING_CANCELLED_EVENT}";`,
+ ),
+ );
+});
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index bd8dad5d804..599c581a953 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -802,6 +802,122 @@ fn begin_quit() -> Option<QuitGuard> {
(!QUIT_IN_PROGRESS.swap(true, Ordering::SeqCst)).then_some(QuitGuard)
}
+/// Asks the renderer for the closing overlay. Reaping the backend takes up to ~18s on
+/// Windows, which is the only platform that asks for it: `stop_spawned_backend` spends up
+/// to 2 liveness requests and 2 shutdown requests at `LOCAL_HTTP_TIMEOUT` (2s each), then
+/// waits twice for the child to exit (5s each) either side of the CTRL_BREAK. Without this
+/// the window just sits there looking frozen for all of it. See `request_quit`.
+const APP_CLOSING_EVENT: &str = "app-closing";
+
+/// Takes that overlay back down, for the quits that never reach the exit.
+const APP_CLOSING_CANCELLED_EVENT: &str = "app-closing-cancelled";
+
+/// Raises the overlay, and retracts it again unless `keep` is called. A guard rather than
+/// paired emits so that every way out of the reap takes it back down, early returns and
+/// unwinds alike, because the app is still there afterwards and an overlay left up would
+/// cover it with no way back. Nothing under `cleanup_child_processes` panics today: its one
+/// `.expect` reads a `ShutdownFlag` managed on the line after the `BackendState` that gates
+/// it, and everything below recovers poisoned locks instead of unwrapping them. So the
+/// unwind arm is cheap insurance against a future reap, not a live case.
+struct ClosingOverlay<E: Fn(&str)> {
+ emit: E,
+ retract: bool,
+}
+
+impl<E: Fn(&str)> ClosingOverlay<E> {
+ fn raise(emit: E) -> Self {
+ emit(APP_CLOSING_EVENT);
+ Self {
+ emit,
+ retract: true,
+ }
+ }
+
+ /// The process is on its way out, so the overlay stays up for the rest of its life.
+ fn keep(mut self) {
+ self.retract = false;
+ }
+}
+
+impl<E: Fn(&str)> Drop for ClosingOverlay<E> {
+ fn drop(&mut self) {
+ if self.retract {
+ (self.emit)(APP_CLOSING_CANCELLED_EVENT);
+ }
+ }
+}
+
+/// Whether this quit has a window worth covering.
+///
+/// Windows only, for the reason `request_quit` gives. Past that the question is whether
+/// there is anything on screen to explain. The tray's Quit reaches `request_quit` without
+/// going through the main window at all, and an autostart launch passes `--hidden`, whose
+/// window is built `"visible": false` and never shown, so the overlay would paint into a
+/// window nobody can see. Showing the window first was the other option and it is worse: a
+/// window that pops open because you asked the app to go away is a surprise, and there is
+/// no frozen window to explain when none is on screen.
+///
+/// A minimized window does count as visible, and that is the answer we want rather than an
+/// accident: Tauri's `is_visible` is `IsWindowVisible`, which reports the `WS_VISIBLE`
+/// style bit, and minimizing does not clear it. The user can restore part way through the
+/// reap, and the frozen window this exists to explain is exactly what they must not find.
+///
+/// The visibility read is injected rather than taken off an `AppHandle`, which cannot be
+/// built in a test, and it is asked for only on Windows: the getter blocks on a round trip
+/// to the event loop, and nothing off Windows raises an overlay to spend it on.
+///
+/// `None` means there is no main window, which is nothing to cover. A visibility that
+/// cannot be read raises the overlay anyway: an emit into a hidden window costs nothing,
+/// and an unexplained frozen window is the whole failure being fixed.
+fn quit_raises_the_overlay(
+ windows: bool,
+ main_window_visible: impl FnOnce() -> Option<Result<bool, String>>,
+) -> bool {
+ if !windows {
+ return false;
+ }
+ match main_window_visible() {
+ None => false,
+ Some(Ok(visible)) => visible,
+ Some(Err(error)) => {
+ warn!("Could not read the main window visibility ({error}); covering the quit anyway");
+ true
+ }
+ }
+}
+
+/// Confirm, cover the window, reap. Returns whether the caller should now exit.
+///
+/// Split out with its blocking parts injected because the order is the whole point and an
+/// `AppHandle` cannot be built in a test. `cover` comes in the same way rather than off a
+/// `cfg!`, so both platforms stay covered by tests on whichever one is running them.
+///
+/// The overlay goes up after the confirmations, never before: each one can put a "Keep
+/// training?" dialog on screen, and an overlay behind it would announce the opposite of
+/// what it is asking. It still lands before the reap, which is the whole of the wait.
+fn quit_sequence(
+ confirm: impl Fn() -> bool,
+ cover: impl FnOnce() -> bool,
+ reap: impl FnOnce(),
+ emit: impl Fn(&str),
+) -> bool {
+ if !confirm() {
+ return false;
+ }
+ // Asked after the confirmations rather than alongside them: a dialog sits on screen for
+ // as long as the user takes to answer it, and the window state that decides this is the
+ // one the reap is about to block. A declined quit never asks, which also keeps the
+ // blocking visibility read off the path that stays in the app.
+ //
+ // `None` is the whole no-op: nothing raised, so nothing to retract on the way out.
+ let overlay = cover().then(|| ClosingOverlay::raise(emit));
+ reap();
+ if let Some(overlay) = overlay {
+ overlay.keep();
+ }
+ true
+}
+
/// Confirm, reap the backend, then exit. Off the caller's thread because the confirmations
/// block, and never exit first: that would orphan the backend tree.
fn request_quit(app: &tauri::AppHandle) {
@@ -815,23 +931,38 @@ fn request_quit(app: &tauri::AppHandle) {
.name("request-quit".to_string())
.spawn(move || {
let _guard = guard;
- if !confirm_quit_during_install(&app) {
- return;
- }
- if !confirm_quit_during_update(&app) {
- return;
- }
- if !confirm_quit_during_shell_update(&app) {
- return;
- }
- if !confirm_quit_during_training(&app) {
- return;
- }
- if !confirm_quit_during_downloads(&app) {
- return;
+ // Driven from here rather than the CloseRequested arm so the tray Quit is
+ // covered on the same terms as the close button.
+ let quitting = quit_sequence(
+ || {
+ confirm_quit_during_install(&app)
+ && confirm_quit_during_update(&app)
+ && confirm_quit_during_shell_update(&app)
+ && confirm_quit_during_training(&app)
+ && confirm_quit_during_downloads(&app)
+ },
+ || {
+ quit_raises_the_overlay(
+ // Windows only. macOS never reaches here from the close button,
+ // which hides to the tray, and on Linux the button already quit
+ // without an overlay: the freeze this covers was reported on
+ // Windows, where stop_backend spends its liveness, shutdown and
+ // CTRL_BREAK budgets in series.
+ cfg!(target_os = "windows"),
+ || {
+ app.get_webview_window("main")
+ .map(|window| window.is_visible().map_err(|e| e.to_string()))
+ },
+ )
+ },
+ || cleanup_child_processes(&app),
+ |event| {
+ let _ = app.emit(event, ());
+ },
+ );
+ if quitting {
+ app.exit(0);
}
- cleanup_child_processes(&app);
- app.exit(0);
});
if let Err(error) = spawned {
warn!("Could not spawn the quit thread: {error}");
@@ -1120,9 +1251,12 @@ fn main() {
} => show_main_window(app),
tauri::RunEvent::Exit => {
// Safety net for framework-driven exits. When another path already owns
- // cleanup, this blocks the main event-loop thread until that path is
- // done: worst case roughly 15s, waiting on the graceful-then-force stop
- // of the installer (5s), the updater (5s) and the backend (5s).
+ // cleanup, this blocks the main event-loop thread until that path is done.
+ // Worst case is roughly 15s on Unix, waiting on the graceful-then-force
+ // stop of the installer (5s), the updater (5s) and the backend (5s), and
+ // roughly 18s on Windows, where those first two graceful waits are
+ // `#[cfg(unix)]` and go straight to the force kill, but the backend spends
+ // its liveness, shutdown and CTRL_BREAK budgets in series instead.
cleanup_child_processes(app);
}
_ => {}
@@ -1343,6 +1477,182 @@ mod tests {
);
}
+ #[test]
+ fn a_quit_that_reaches_exit_covers_the_reap() {
+ let events = std::cell::RefCell::new(Vec::new());
+
+ let quitting = quit_sequence(
+ || true,
+ || true,
+ || events.borrow_mut().push("reap".to_string()),
+ |event| events.borrow_mut().push(event.to_string()),
+ );
+
+ assert!(quitting);
+ // The reap blocks for up to ~15s, so an overlay emitted after it paints too late
+ // to cover anything.
+ assert_eq!(events.into_inner(), ["app-closing", "reap"]);
+ }
+
+ #[test]
+ fn a_quit_with_nothing_to_cover_reaps_without_asking_for_an_overlay() {
+ let events = std::cell::RefCell::new(Vec::new());
+
+ let quitting = quit_sequence(
+ || true,
+ || false,
+ || events.borrow_mut().push("reap".to_string()),
+ |event| events.borrow_mut().push(event.to_string()),
+ );
+
+ assert!(quitting, "the overlay is presentation, not part of quitting");
+ assert_eq!(
+ events.into_inner(),
+ ["reap"],
+ "macOS closes to the tray and Linux quit without an overlay before this \
+ existed, so neither may see the event at all, and neither may a tray quit \
+ with no window on screen"
+ );
+ }
+
+ #[test]
+ fn a_declined_quit_never_raises_the_overlay() {
+ let events = std::cell::RefCell::new(Vec::new());
+
+ let quitting = quit_sequence(
+ || false,
+ || true,
+ || events.borrow_mut().push("reap".to_string()),
+ |event| events.borrow_mut().push(event.to_string()),
+ );
+
+ assert!(!quitting, "a declined confirmation must not reach the exit");
+ assert!(
+ events.into_inner().is_empty(),
+ "the confirmations are dialogs, and an overlay behind one would claim the app \
+ is closing while it asks whether to keep going"
+ );
+ }
+
+ // The visibility read blocks on a round trip to the event loop, and the window state
+ // that decides the overlay is the one the reap will block, not the one from before a
+ // dialog the user sat on for a minute.
+ #[test]
+ fn a_declined_quit_never_asks_whether_the_window_is_visible() {
+ let asked = std::cell::Cell::new(false);
+
+ let quitting = quit_sequence(
+ || false,
+ || {
+ asked.set(true);
+ true
+ },
+ || panic!("a declined quit must not reap"),
+ |_| panic!("a declined quit must not emit"),
+ );
+
+ assert!(!quitting);
+ assert!(
+ !asked.get(),
+ "the window question is only worth asking once the quit is committed"
+ );
+ }
+
+ #[test]
+ fn a_panicking_reap_takes_the_overlay_back_down() {
+ let events = std::cell::RefCell::new(Vec::new());
+
+ let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ quit_sequence(
+ || true,
+ || true,
+ || panic!("the reap panicked"),
+ |event| events.borrow_mut().push(event.to_string()),
+ )
+ }));
+
+ assert!(unwound.is_err());
+ assert_eq!(
+ events.into_inner(),
+ ["app-closing", "app-closing-cancelled"],
+ "a panicking reap leaves the app up, so the overlay cannot cover it"
+ );
+ }
+
+ #[test]
+ fn a_panicking_reap_with_nothing_to_cover_stays_silent() {
+ let events = std::cell::RefCell::new(Vec::new());
+
+ let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ quit_sequence(
+ || true,
+ || false,
+ || panic!("the reap panicked"),
+ |event| events.borrow_mut().push(event.to_string()),
+ )
+ }));
+
+ assert!(unwound.is_err());
+ assert!(
+ events.into_inner().is_empty(),
+ "nothing was raised, so the unwind has nothing to retract: a cancel here would \
+ be the guard half-armed"
+ );
+ }
+
+ // The tray's Quit reaches request_quit without going through the main window, and an
+ // autostart launch passes --hidden, whose window is built "visible": false and never
+ // shown. An overlay there paints into a window nobody can see.
+ #[test]
+ fn a_quit_with_the_window_hidden_raises_no_overlay() {
+ assert!(
+ !quit_raises_the_overlay(true, || Some(Ok(false))),
+ "there is no frozen window to explain when no window is on screen"
+ );
+ }
+
+ // Not an accident of the API: Tauri's is_visible is IsWindowVisible, which reports the
+ // WS_VISIBLE style bit, and minimizing does not clear it. Restoring part way through
+ // the reap has to find the overlay rather than the freeze it explains.
+ #[test]
+ fn a_minimized_window_still_gets_the_overlay() {
+ assert!(quit_raises_the_overlay(true, || Some(Ok(true))));
+ }
+
+ #[test]
+ fn a_quit_with_no_main_window_at_all_raises_no_overlay() {
+ assert!(
+ !quit_raises_the_overlay(true, || None),
+ "a window that does not exist cannot be looking frozen"
+ );
+ }
+
+ #[test]
+ fn an_unreadable_window_visibility_still_gets_the_overlay() {
+ assert!(
+ quit_raises_the_overlay(true, || Some(Err("no window handle".to_string()))),
+ "an emit into a hidden window costs nothing, and an unexplained frozen window \
+ is the failure this exists to fix"
+ );
+ }
+
+ #[test]
+ fn the_window_visibility_is_never_read_off_windows() {
+ let asked = std::cell::Cell::new(false);
+
+ let raised = quit_raises_the_overlay(false, || {
+ asked.set(true);
+ Some(Ok(true))
+ });
+
+ assert!(!raised, "only Windows shows the freeze this covers");
+ assert!(
+ !asked.get(),
+ "the getter blocks on a round trip to the event loop, and nothing off Windows \
+ raises an overlay to spend it on"
+ );
+ }
+
#[test]
fn autostart_hardening_appends_the_exec_binary_without_args() {
let entry = "[Desktop Entry]\nType=Application\nExec=/usr/bin/unsloth-studio --hidden\nTerminal=false";