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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep running when the main window closes (#8675)
Wasim Yousef Saide95fd2bea5f1
diff --git a/studio/frontend/src/features/settings/api/close-to-tray.ts b/studio/frontend/src/features/settings/api/close-to-tray.tsnew file mode 100644index 00000000000..2c3728579c4--- /dev/null+++ b/studio/frontend/src/features/settings/api/close-to-tray.ts@@ -0,0 +1,12 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export async function loadCloseToTray(): Promise<boolean | null> {+ const { invoke } = await import("@tauri-apps/api/core");+ return invoke<boolean | null>("get_close_to_tray");+}++export async function updateCloseToTray(enabled: boolean): Promise<boolean> {+ const { invoke } = await import("@tauri-apps/api/core");+ return invoke<boolean>("set_close_to_tray", { enabled });+}diff --git a/studio/frontend/src/features/settings/hooks/use-desktop-boolean-setting.ts b/studio/frontend/src/features/settings/hooks/use-desktop-boolean-setting.tsnew file mode 100644index 00000000000..3abf39d5587--- /dev/null+++ b/studio/frontend/src/features/settings/hooks/use-desktop-boolean-setting.ts@@ -0,0 +1,61 @@+// 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 { useCallback, useEffect, useState } from "react";++interface DesktopBooleanSettingOptions {+ enabled: boolean;+ load: () => Promise<boolean | null>;+ save: (enabled: boolean) => Promise<boolean>;+ loadError: string;+ saveError: string;+}++export function useDesktopBooleanSetting({+ enabled,+ load,+ save,+ loadError,+ saveError,+}: DesktopBooleanSettingOptions) {+ const [value, setValue] = useState<boolean | null>(null);+ const [supported, setSupported] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ if (!enabled) return;+ let cancelled = false;+ void load()+ .then((loaded) => {+ if (cancelled) return;+ setValue(loaded);+ setSupported(loaded !== null);+ setError(null);+ })+ .catch((cause) => {+ if (cancelled) return;+ setError(cause instanceof Error ? cause.message : loadError);+ });+ return () => {+ cancelled = true;+ };+ }, [enabled, load, loadError]);++ const update = useCallback(+ async (next: boolean) => {+ setSaving(true);+ setError(null);+ try {+ setValue(await save(next));+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : saveError);+ } finally {+ setSaving(false);+ }+ },+ [save, saveError],+ );++ return { value, supported, error, saving, update };+}diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsxindex 5e5ef9e6451..e090c508aff 100644--- a/studio/frontend/src/features/settings/settings-dialog.tsx+++ b/studio/frontend/src/features/settings/settings-dialog.tsx@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { FloatingMonitor } from "@/components/floating-monitor";+import { getClientPlatform } from "@/components/tauri/window-titlebar";import {Dialog,DialogContent,@@ -119,7 +120,15 @@ const TABS: TabDef[] = [{ id: "about", labelKey: "settings.tabs.about", icon: HelpCircleIcon },];-const SETTINGS_SEARCH_INDEX = createSettingsSearchIndex(isTauri);+const clientPlatform = getClientPlatform();+const SETTINGS_SEARCH_INDEX = createSettingsSearchIndex({+ desktop: isTauri,+ closeToTray:+ isTauri &&+ (clientPlatform.startsWith("win") ||+ clientPlatform.includes("windows") ||+ clientPlatform.includes("linux")),+});function renderTab(tab: SettingsTab) {switch (tab) {diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex b57c22e2eb6..3ef1d8df162 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -159,9 +159,13 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {],};-export function createSettingsSearchIndex(- desktop: boolean,-): Record<SettingsTab, TranslationKey[]> {+export function createSettingsSearchIndex({+ desktop,+ closeToTray,+}: {+ desktop: boolean;+ closeToTray: boolean;+}): Record<SettingsTab, TranslationKey[]> {if (!desktop) {return SETTINGS_SEARCH_INDEX;}@@ -172,6 +176,7 @@ export function createSettingsSearchIndex("settings.about.updates","settings.general.startup.sectionTitle","settings.general.startup.launchAtLogin",+ ...(closeToTray ? (["settings.general.startup.closeToTray"] as const) : []),],about: SETTINGS_SEARCH_INDEX.about.filter((key) => key !== "settings.about.updates",diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex 5a963895d20..b9fd31178a4 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -60,6 +60,7 @@ import {loadUploadLimitSettings,updateUploadLimitSettings,} from "../api/upload-limit";+import { loadCloseToTray, updateCloseToTray } from "../api/close-to-tray";import { loadLaunchAtLogin, updateLaunchAtLogin } from "../api/launch-at-login";import { ChangePasswordDialog } from "../components/change-password-dialog";import {@@ -71,6 +72,7 @@ import { LanguageSelect } from "../components/language-select";import { SettingsRow } from "../components/settings-row";import { SettingsSection } from "../components/settings-section";import { StudioVersionSection } from "../components/studio-version-section";+import { useDesktopBooleanSetting } from "../hooks/use-desktop-boolean-setting";import { SETTINGS_PANEL_PREFS_STORAGE_KEY } from "../stores/settings-panel-prefs-store";// Keys cleared by "Reset all local preferences". NEVER include auth/session keys here -- that@@ -190,11 +192,20 @@ export function GeneralTab() {const [isSavingPreviewSharing, setIsSavingPreviewSharing] = useState(false);const [revokePreviewOpen, setRevokePreviewOpen] = useState(false);const [isRevokingPreview, setIsRevokingPreview] = useState(false);- const [launchAtLogin, setLaunchAtLogin] = useState<boolean | null>(null);- const [launchAtLoginError, setLaunchAtLoginError] = useState<string | null>(- null,- );- const [isSavingLaunchAtLogin, setIsSavingLaunchAtLogin] = useState(false);+ const launchAtLoginSetting = useDesktopBooleanSetting({+ enabled: isTauri,+ load: loadLaunchAtLogin,+ save: updateLaunchAtLogin,+ loadError: t("settings.general.startup.loadError"),+ saveError: t("settings.general.startup.saveError"),+ });+ const closeToTraySetting = useDesktopBooleanSetting({+ enabled: isTauri,+ load: loadCloseToTray,+ save: updateCloseToTray,+ loadError: t("settings.general.startup.loadError"),+ saveError: t("settings.general.startup.closeToTraySaveError"),+ });const [embeddingModel, setEmbeddingModel] =useState<EmbeddingModelSettings | null>(null);const [draftEmbeddingModel, setDraftEmbeddingModel] = useState("");@@ -326,44 +337,6 @@ export function GeneralTab() {};}, [t]);- useEffect(() => {- if (!isTauri) return;- let cancelled = false;- void loadLaunchAtLogin()- .then((enabled) => {- if (cancelled) return;- setLaunchAtLogin(enabled);- setLaunchAtLoginError(null);- })- .catch((error) => {- if (cancelled) return;- setLaunchAtLoginError(- error instanceof Error- ? error.message- : t("settings.general.startup.loadError"),- );- });- return () => {- cancelled = true;- };- }, [t]);-- const saveLaunchAtLogin = async (enabled: boolean) => {- setIsSavingLaunchAtLogin(true);- setLaunchAtLoginError(null);- try {- setLaunchAtLogin(await updateLaunchAtLogin(enabled));- } catch (error) {- setLaunchAtLoginError(- error instanceof Error- ? error.message- : t("settings.general.startup.saveError"),- );- } finally {- setIsSavingLaunchAtLogin(false);- }- };-const saveHelperPrecache = async (enabled: boolean) => {setIsSavingHelperPrecache(true);setHelperPrecacheError(null);@@ -636,17 +609,41 @@ export function GeneralTab() {><div className="flex flex-col items-end gap-1"><Switch- checked={launchAtLogin ?? false}- disabled={launchAtLogin === null || isSavingLaunchAtLogin}- onCheckedChange={(enabled) => void saveLaunchAtLogin(enabled)}+ checked={launchAtLoginSetting.value ?? false}+ disabled={+ launchAtLoginSetting.value === null || launchAtLoginSetting.saving+ }+ onCheckedChange={(enabled) => void launchAtLoginSetting.update(enabled)}/>- {launchAtLoginError ? (+ {launchAtLoginSetting.error ? (<span className="max-w-[260px] text-right text-xs text-destructive">- {launchAtLoginError}+ {launchAtLoginSetting.error}</span>) : null}</div></SettingsRow>++ {closeToTraySetting.supported ? (+ <SettingsRow+ label={t("settings.general.startup.closeToTray")}+ description={t("settings.general.startup.closeToTrayDescription")}+ >+ <div className="flex flex-col items-end gap-1">+ <Switch+ checked={closeToTraySetting.value ?? false}+ disabled={+ closeToTraySetting.value === null || closeToTraySetting.saving+ }+ onCheckedChange={(enabled) => void closeToTraySetting.update(enabled)}+ />+ {closeToTraySetting.error ? (+ <span className="max-w-[260px] text-right text-xs text-destructive">+ {closeToTraySetting.error}+ </span>+ ) : null}+ </div>+ </SettingsRow>+ ) : null}</SettingsSection>) : null}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex f1f453d69b4..9a4908c74e3 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -419,6 +419,11 @@ export const ar = {launchAtLogin: "تشغيل Unsloth عند تسجيل الدخول",launchAtLoginDescription:"يبدأ Unsloth في الخلفية عند تسجيل الدخول، ويبقى في شريط القوائم أو علبة النظام حتى تفتحه.",++ closeToTray: "الإغلاق إلى علبة النظام",+ closeToTrayDescription:+ "إبقاء Unsloth وخادمه قيد التشغيل في الخلفية عند إغلاق النافذة الرئيسية.",+ closeToTraySaveError: "تعذّر تحديث إعداد الإغلاق إلى علبة النظام.",loadError: "تعذر تحميل إعداد التشغيل عند تسجيل الدخول.",saveError: "تعذر تحديث إعداد التشغيل عند تسجيل الدخول.",},diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex c641de2b263..b6af971ce83 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -436,6 +436,12 @@ export const de = {launchAtLogin: "Unsloth bei der Anmeldung starten",launchAtLoginDescription:"Startet Unsloth im Hintergrund, wenn Sie sich anmelden. Es bleibt in der Menüleiste bzw. im Infobereich, bis Sie es öffnen.",++ closeToTray: "In den Infobereich schließen",+ closeToTrayDescription:+ "Unsloth und seinen Server im Hintergrund weiterlaufen lassen, wenn Sie das Hauptfenster schließen.",+ closeToTraySaveError:+ "Die Einstellung zum Schließen in den Infobereich konnte nicht aktualisiert werden.",loadError: "Die Autostart-Einstellung konnte nicht geladen werden.",saveError:"Die Autostart-Einstellung konnte nicht aktualisiert werden.",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex c90fb91e820..10efc2d4aa8 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -419,6 +419,11 @@ export const en = {launchAtLogin: "Run Unsloth at login",launchAtLoginDescription:"Start Unsloth in the background when you log in. It stays in the menu bar or system tray until you open it.",++ closeToTray: "Close to system tray",+ closeToTrayDescription:+ "Keep Unsloth and its server running in the background when you close the main window.",+ closeToTraySaveError: "Failed to update the close to system tray setting.",loadError: "Failed to load the launch at login setting.",saveError: "Failed to update the launch at login setting.",},diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex e8fc2af7e54..dbeeb689c02 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -432,6 +432,12 @@ export const es = {launchAtLogin: "Ejecutar Unsloth al iniciar sesión",launchAtLoginDescription:"Inicia Unsloth en segundo plano cuando inicias sesión. Permanece en la barra de menús o en la bandeja del sistema hasta que lo abras.",++ closeToTray: "Cerrar en la bandeja del sistema",+ closeToTrayDescription:+ "Mantén Unsloth y su servidor ejecutándose en segundo plano al cerrar la ventana principal.",+ closeToTraySaveError:+ "No se pudo actualizar el ajuste de cierre en la bandeja del sistema.",loadError: "No se pudo cargar el ajuste de inicio automático.",saveError: "No se pudo actualizar el ajuste de inicio automático.",},diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 908a53d8e26..90a421fe873 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -434,6 +434,12 @@ export const fr = {launchAtLogin: "Lancer Unsloth à la connexion",launchAtLoginDescription:"Démarre Unsloth en arrière-plan lorsque vous vous connectez. Il reste dans la barre de menus ou la zone de notification jusqu'à ce que vous l'ouvriez.",++ closeToTray: "Fermer dans la zone de notification",+ closeToTrayDescription:+ "Laisser Unsloth et son serveur fonctionner en arrière-plan lorsque vous fermez la fenêtre principale.",+ closeToTraySaveError:+ "Impossible de mettre à jour le réglage de fermeture dans la zone de notification.",loadError:"Impossible de charger le réglage de lancement à la connexion.",saveError:diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex d80acacb844..6fd1905b36a 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -422,6 +422,11 @@ export const hi = {launchAtLogin: "लॉगिन पर Unsloth चलाएं",launchAtLoginDescription:"लॉगिन करने पर Unsloth को बैकग्राउंड में शुरू करता है। इसे खोलने तक यह मेनू बार या सिस्टम ट्रे में रहता है।",++ closeToTray: "सिस्टम ट्रे में बंद करें",+ closeToTrayDescription:+ "मुख्य विंडो बंद करने पर Unsloth और उसके सर्वर को बैकग्राउंड में चलते रहने दें।",+ closeToTraySaveError: "सिस्टम ट्रे में बंद करने की सेटिंग अपडेट नहीं हो सकी।",loadError: "लॉगिन पर चलाने की सेटिंग लोड नहीं हो सकी।",saveError: "लॉगिन पर चलाने की सेटिंग अपडेट नहीं हो सकी।",},diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex b057956fe13..8e6508fa0e8 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -406,6 +406,12 @@ export const it = {launchAtLogin: "Avvia Unsloth all'accesso",launchAtLoginDescription:"Avvia Unsloth in background quando accedi. Rimane nella barra dei menu o nell'area di notifica finché non lo apri.",++ closeToTray: "Chiudi nell'area di notifica",+ closeToTrayDescription:+ "Mantieni Unsloth e il suo server in esecuzione in background quando chiudi la finestra principale.",+ closeToTraySaveError:+ "Impossibile aggiornare l'impostazione di chiusura nell'area di notifica.",loadError: "Impossibile caricare l'impostazione di avvio all'accesso.",saveError:"Impossibile aggiornare l'impostazione di avvio all'accesso.",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 82f997bcbe4..dc3fcebf896 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -409,6 +409,11 @@ export const ja = {launchAtLogin: "ログイン時に Unsloth を起動",launchAtLoginDescription:"ログイン時に Unsloth をバックグラウンドで起動します。開くまでメニューバーまたはシステムトレイに常駐します。",++ closeToTray: "システムトレイに格納して閉じる",+ closeToTrayDescription:+ "メインウィンドウを閉じても、Unsloth とサーバーをバックグラウンドで実行し続けます。",+ closeToTraySaveError: "システムトレイに格納する設定を更新できませんでした。",loadError: "ログイン時起動の設定を読み込めませんでした。",saveError: "ログイン時起動の設定を更新できませんでした。",},diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex cd751b15a0b..2f123b6c842 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -416,6 +416,11 @@ export const ko = {launchAtLogin: "로그인 시 Unsloth 실행",launchAtLoginDescription:"로그인하면 Unsloth를 백그라운드에서 시작합니다. 열기 전까지 메뉴 막대 또는 시스템 트레이에 남아 있습니다.",++ closeToTray: "시스템 트레이로 닫기",+ closeToTrayDescription:+ "기본 창을 닫아도 Unsloth와 서버가 백그라운드에서 계속 실행되도록 합니다.",+ closeToTraySaveError: "시스템 트레이로 닫기 설정을 업데이트하지 못했습니다.",loadError: "로그인 시 실행 설정을 불러오지 못했습니다.",saveError: "로그인 시 실행 설정을 업데이트하지 못했습니다.",},diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 07ac46fc884..af7befbcd73 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -423,6 +423,12 @@ export const ptBR = {launchAtLogin: "Executar o Unsloth ao fazer login",launchAtLoginDescription:"Inicia o Unsloth em segundo plano quando você faz login. Ele permanece na barra de menus ou na bandeja do sistema até você abri-lo.",++ closeToTray: "Fechar para a bandeja do sistema",+ closeToTrayDescription:+ "Mantém o Unsloth e seu servidor em execução em segundo plano ao fechar a janela principal.",+ closeToTraySaveError:+ "Não foi possível atualizar a configuração de fechar para a bandeja do sistema.",loadError:"Não foi possível carregar a configuração de inicialização no login.",saveError:diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex e885c3f01f7..4693486c328 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -421,6 +421,12 @@ export const ru = {launchAtLogin: "Запускать Unsloth при входе в систему",launchAtLoginDescription:"Запускает Unsloth в фоновом режиме при входе в систему. Приложение остаётся в строке меню или системном трее, пока вы его не откроете.",++ closeToTray: "Закрывать в системный трей",+ closeToTrayDescription:+ "Оставлять Unsloth и его сервер работающими в фоне при закрытии главного окна.",+ closeToTraySaveError:+ "Не удалось обновить настройку закрытия в системный трей.",loadError: "Не удалось загрузить настройку автозапуска.",saveError: "Не удалось обновить настройку автозапуска.",},diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 81e2f47b7a2..8e2c3ec0e56 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -403,6 +403,11 @@ export const zhCN = {launchAtLogin: "登录时运行 Unsloth",launchAtLoginDescription:"登录系统时在后台启动 Unsloth。在你打开它之前,它会一直驻留在菜单栏或系统托盘中。",++ closeToTray: "关闭到系统托盘",+ closeToTrayDescription:+ "关闭主窗口时,让 Unsloth 及其服务器继续在后台运行。",+ closeToTraySaveError: "无法更新关闭到系统托盘设置。",loadError: "无法加载登录时启动设置。",saveError: "无法更新登录时启动设置。",},diff --git a/studio/frontend/tests/settings-search.test.ts b/studio/frontend/tests/settings-search.test.tsindex 5b4164e657c..d433cd06b6f 100644--- a/studio/frontend/tests/settings-search.test.ts+++ b/studio/frontend/tests/settings-search.test.ts@@ -13,14 +13,14 @@ import { en } from "../src/i18n/locales/en.ts";const UPDATE_ENTRY = "settings.about.updates";test("desktop update searches route to General", () => {- const index = createSettingsSearchIndex(true);+ const index = createSettingsSearchIndex({ desktop: true, closeToTray: true });assert.ok(index.general.includes(UPDATE_ENTRY));assert.ok(!index.about.includes(UPDATE_ENTRY));});test("browser update searches keep routing to About", () => {- const index = createSettingsSearchIndex(false);+ const index = createSettingsSearchIndex({ desktop: false, closeToTray: false });assert.ok(!index.general.includes(UPDATE_ENTRY));assert.ok(index.about.includes(UPDATE_ENTRY));@@ -29,7 +29,7 @@ test("browser update searches keep routing to About", () => {// The words a user types for this feature are not substrings of any of its// labels, so without keywords the rows it is named after were unfindable.test("model memory rows are reachable by the terms the feature is about", () => {- const index = createSettingsSearchIndex(false);+ const index = createSettingsSearchIndex({ desktop: false, closeToTray: false });const rows = ["settings.resources.modelMemory.title","settings.resources.modelMemory.keepResident",@@ -53,17 +53,28 @@ test("model memory rows are reachable by the terms the feature is about", () =>}});-const STARTUP_ENTRIES = [+const DESKTOP_STARTUP_ENTRIES = ["settings.general.startup.sectionTitle","settings.general.startup.launchAtLogin",] as const;+const CLOSE_TO_TRAY_ENTRY = "settings.general.startup.closeToTray";-test("startup entries are searchable on desktop only", () => {- const desktop = createSettingsSearchIndex(true);- const browser = createSettingsSearchIndex(false);+test("desktop startup entries are absent from browser search", () => {+ const desktop = createSettingsSearchIndex({ desktop: true, closeToTray: true });+ const browser = createSettingsSearchIndex({ desktop: false, closeToTray: false });- for (const entry of STARTUP_ENTRIES) {+ for (const entry of DESKTOP_STARTUP_ENTRIES) {assert.ok(desktop.general.includes(entry));assert.ok(!browser.general.includes(entry));}});++test("close to tray is searchable only on supported desktops", () => {+ const supported = createSettingsSearchIndex({ desktop: true, closeToTray: true });+ const mac = createSettingsSearchIndex({ desktop: true, closeToTray: false });+ const browser = createSettingsSearchIndex({ desktop: false, closeToTray: false });++ assert.ok(supported.general.includes(CLOSE_TO_TRAY_ENTRY));+ assert.ok(!mac.general.includes(CLOSE_TO_TRAY_ENTRY));+ assert.ok(!browser.general.includes(CLOSE_TO_TRAY_ENTRY));+});diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex dc86906b7bc..f849c5f1efd 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -39,13 +39,23 @@ use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}use tauri::{Emitter, Manager};use tauri_plugin_window_state::{AppHandleExt, StateFlags};-/// Serializes the exit paths that reap the backend: `request_quit` (tray "Quit" and,-/// outside macOS, the close button), the Unix signal listener, and `RunEvent::Exit`.+/// Serializes the exit paths that reap the backend: `request_quit` (tray "Quit" and a+/// Windows/Linux close button when close-to-tray is disabled), the Unix signal listener, and+/// `RunEvent::Exit`./// Exactly one runs cleanup; the others block, so the process never exits mid-reap.static TERMINATION_CLEANUP: Mutex<bool> = Mutex::new(false);const IN_APP_RELAUNCH_MARKER_FILE: &str = "in-app-relaunch-v1";+const CLOSE_TO_TRAY_PREFERENCE_FILE: &str = "close-to-tray-v1";++struct CloseToTrayState(AtomicBool);++fn new_close_to_tray_state() -> CloseToTrayState {+ // Closing keeps its historical quit behavior until the user explicitly opts in.+ CloseToTrayState(AtomicBool::new(false))+}+/// Resolved once, at setup, where the marker is consumed, so no later caller can flip the answer.static LAUNCHED_HIDDEN: OnceLock<bool> = OnceLock::new();@@ -134,6 +144,103 @@ fn reveal_main_window(app: tauri::AppHandle) {show_main_window(&app);}+fn close_to_tray_preference_path(config_dir: &Path) -> PathBuf {+ config_dir.join(CLOSE_TO_TRAY_PREFERENCE_FILE)+}++fn read_close_to_tray_preference(config_dir: &Path) -> bool {+ let path = close_to_tray_preference_path(config_dir);+ match fs::read_to_string(&path) {+ Ok(value) => match value.trim().parse::<bool>() {+ Ok(enabled) => enabled,+ Err(error) => {+ warn!(+ "Ignoring invalid close-to-tray preference {}: {error}",+ path.display()+ );+ false+ }+ },+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,+ Err(error) => {+ warn!(+ "Could not read close-to-tray preference {}: {error}",+ path.display()+ );+ false+ }+ }+}++fn write_close_to_tray_preference(config_dir: &Path, enabled: bool) -> Result<(), String> {+ fs::create_dir_all(config_dir).map_err(|error| {+ format!(+ "Failed to create app configuration directory {}: {error}",+ config_dir.display()+ )+ })?;+ let path = close_to_tray_preference_path(config_dir);+ fs::write(&path, format!("{enabled}\n")).map_err(|error| {+ format!(+ "Failed to save close-to-tray preference {}: {error}",+ path.display()+ )+ })+}++fn initialize_close_to_tray(app: &tauri::AppHandle) {+ let enabled = app+ .path()+ .app_config_dir()+ .map(|dir| read_close_to_tray_preference(&dir))+ .unwrap_or_else(|error| {+ warn!("Could not determine app configuration directory: {error}");+ false+ });+ app.state::<CloseToTrayState>()+ .0+ .store(enabled, Ordering::SeqCst);+}++#[tauri::command]+fn get_close_to_tray(state: tauri::State<'_, CloseToTrayState>) -> Option<bool> {+ cfg!(any(target_os = "windows", target_os = "linux")).then(|| state.0.load(Ordering::SeqCst))+}++#[tauri::command]+fn set_close_to_tray(+ app: tauri::AppHandle,+ state: tauri::State<'_, CloseToTrayState>,+ enabled: bool,+) -> Result<bool, String> {+ if !cfg!(any(target_os = "windows", target_os = "linux")) {+ return Err("Close to system tray is only configurable on Windows and Linux".to_string());+ }+ let config_dir = app+ .path()+ .app_config_dir()+ .map_err(|error| format!("Could not determine app configuration directory: {error}"))?;+ write_close_to_tray_preference(&config_dir, enabled)?;+ state.0.store(enabled, Ordering::SeqCst);+ Ok(enabled)+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+enum MainWindowCloseAction {+ Hide,+ Quit,+}++fn main_window_close_action(close_to_tray: bool) -> MainWindowCloseAction {+ if cfg!(target_os = "macos")+ || (cfg!(any(target_os = "windows", target_os = "linux")) && close_to_tray)+ {+ MainWindowCloseAction::Hide+ } else {+ MainWindowCloseAction::Quit+ }+}+#[tauri::command]fn get_launch_at_login(app: tauri::AppHandle) -> Result<bool, String> {use tauri_plugin_autostart::ManagerExt;@@ -1180,9 +1287,9 @@ where},|| {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 only. macOS and an enabled Windows/Linux close-to-tray+ // preference bypass request_quit; Linux quits and tray quits do not use+ // the 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"),@@ -1519,6 +1626,7 @@ fn main() {.manage(new_backend_state()).manage(process::new_shutdown_flag()).manage(update::new_update_state())+ .manage(new_close_to_tray_state()).manage(native_file_dialogs::ChatImportRegistry::default()).invoke_handler(tauri::generate_handler![set_training_active,@@ -1572,6 +1680,8 @@ fn main() {mark_in_app_relaunch,clear_in_app_relaunch,reveal_main_window,+ get_close_to_tray,+ set_close_to_tray,get_launch_at_login,set_launch_at_login,])@@ -1584,6 +1694,8 @@ fn main() {if launched_hidden {app.set_activation_policy(tauri::ActivationPolicy::Accessory);}++ initialize_close_to_tray(app.handle());reconcile_autostart_entry(app.handle());// Recover legacy desktop installs before the first preflight.if let Err(error) = desktop_backend_owner::ensure_installed_studio_root_id() {@@ -1621,13 +1733,13 @@ fn main() {if let tauri::WindowEvent::CloseRequested { api, .. } = event {// Never close directly: the only window, so closing exits before the reap.api.prevent_close();- if cfg!(target_os = "macos") {- // Closing a window leaves the app in the Dock; Reopen restores it.- let _ = window.hide();- } else {- // Elsewhere the close button means quit, not hiding what the user- // believes they just closed.- request_quit(window.app_handle());+ let close_to_tray = window.state::<CloseToTrayState>().0.load(Ordering::SeqCst);+ match main_window_close_action(close_to_tray) {+ MainWindowCloseAction::Hide => {+ // The tray's Open action and a second app launch restore the window.+ let _ = window.hide();+ }+ MainWindowCloseAction::Quit => request_quit(window.app_handle()),}}})@@ -1731,6 +1843,46 @@ mod tests {assert!(!in_app_relaunch_marker_path(dir.path()).exists());}+ #[test]+ fn close_to_tray_preference_defaults_off_and_round_trips() {+ let dir = tempfile::tempdir().unwrap();++ assert!(!read_close_to_tray_preference(dir.path()));+ write_close_to_tray_preference(dir.path(), false).unwrap();+ assert!(!read_close_to_tray_preference(dir.path()));+ write_close_to_tray_preference(dir.path(), true).unwrap();+ assert!(read_close_to_tray_preference(dir.path()));+ }++ #[test]+ fn invalid_close_to_tray_preference_falls_back_to_disabled() {+ let dir = tempfile::tempdir().unwrap();+ fs::write(close_to_tray_preference_path(dir.path()), b"maybe\n").unwrap();++ assert!(!read_close_to_tray_preference(dir.path()));+ }++ #[test]+ fn enabled_close_to_tray_hides_the_main_window_on_supported_desktops() {+ let expected = if cfg!(any(+ target_os = "windows",+ target_os = "linux",+ target_os = "macos"+ )) {+ MainWindowCloseAction::Hide+ } else {+ MainWindowCloseAction::Quit+ };+ assert_eq!(main_window_close_action(true), expected);++ let disabled_expected = if cfg!(target_os = "macos") {+ MainWindowCloseAction::Hide+ } else {+ MainWindowCloseAction::Quit+ };+ assert_eq!(main_window_close_action(false), disabled_expected);+ }+#[cfg(target_os = "linux")]const BID: &str = "ai.unsloth.studio";@@ -1985,9 +2137,8 @@ mod tests {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"+ "window-close and tray paths can bypass the overlay entirely, and a tray quit with no \+ window on screen must not emit it");}