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
Desktop: start at login, hidden in the menu bar (#8033)
Nilayea67c53957d9
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsxindex 72bd056675e..44f10c62a5a 100644--- a/studio/frontend/src/app/provider.tsx+++ b/studio/frontend/src/app/provider.tsx@@ -68,6 +68,15 @@ function logicalPerCssPx(monitorScale: number): number {return Number.isFinite(ratio) && ratio > 1 ? ratio : 1;}+// Autostart passes --hidden: layout still applies, but the window stays in the tray.+let launchedHidden: Promise<boolean> | null = null;+function wasLaunchedHidden(): Promise<boolean> {+ launchedHidden ??= import("@tauri-apps/api/core")+ .then(({ invoke }) => invoke<boolean>("was_launched_hidden"))+ .catch(() => false);+ return launchedHidden;+}+async function showSetupWindow(isCurrent: WindowLayoutGuard): Promise<void> {const { getCurrentWindow, LogicalSize } = await import("@tauri-apps/api/window"@@ -84,6 +93,8 @@ async function showSetupWindow(isCurrent: WindowLayoutGuard): Promise<void> {if (!isCurrent()) return;await win.center();if (!isCurrent()) return;+ if (await wasLaunchedHidden()) return;+ if (!isCurrent()) return;await win.show();}@@ -184,7 +195,10 @@ async function applyAppWindowLayout(await win.center();}if (!isCurrent()) return;- await win.show();+ if (!(await wasLaunchedHidden())) {+ if (!isCurrent()) return;+ await win.show();+ }if (!isCurrent()) return;// Apply constraints after restore/show: doing so before plugin restore can emit// a Resized event and overwrite the plugin's cached saved size.@@ -203,6 +217,7 @@ async function showWindowFallback(): Promise<void> {const { getCurrentWindow } = await import("@tauri-apps/api/window");const win = getCurrentWindow();await win.setResizable(true);+ if (await wasLaunchedHidden()) return;await win.show();}@@ -532,10 +547,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {</>}>- <LlamaUpdateBanner- positioned={false}- enabled={!hidesTitlebarSidebar}- />+ <LlamaUpdateBanner positioned={false} enabled={!hidesTitlebarSidebar} /><DownloadManagerPanel positioned={false} /></TauriUpdateLayer>) : (diff --git a/studio/frontend/src/features/deep-links/deep-link-handler.tsx b/studio/frontend/src/features/deep-links/deep-link-handler.tsxindex 4ad52259db0..256aed8bc2d 100644--- a/studio/frontend/src/features/deep-links/deep-link-handler.tsx+++ b/studio/frontend/src/features/deep-links/deep-link-handler.tsx@@ -10,12 +10,10 @@ import { parseUnslothDeepLink } from "./parse-deep-link";const acceptIntent = createDeepLinkIntentGate(2_000);+// Via Rust so a hidden login start also gets its Dock icon restored.async function restoreMainWindow(): Promise<void> {- const { getCurrentWindow } = await import("@tauri-apps/api/window");- const window = getCurrentWindow();- await window.show();- await window.unminimize();- await window.setFocus();+ const { invoke } = await import("@tauri-apps/api/core");+ await invoke("reveal_main_window");}export function DeepLinkHandler() {diff --git a/studio/frontend/src/features/settings/api/launch-at-login.ts b/studio/frontend/src/features/settings/api/launch-at-login.tsnew file mode 100644index 00000000000..87b6a29ed5a--- /dev/null+++ b/studio/frontend/src/features/settings/api/launch-at-login.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 loadLaunchAtLogin(): Promise<boolean> {+ const { invoke } = await import("@tauri-apps/api/core");+ return invoke<boolean>("get_launch_at_login");+}++export async function updateLaunchAtLogin(enabled: boolean): Promise<boolean> {+ const { invoke } = await import("@tauri-apps/api/core");+ return invoke<boolean>("set_launch_at_login", { enabled });+}diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex a517bc4b856..115a98558e1 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -165,7 +165,12 @@ export function createSettingsSearchIndex(}return {...SETTINGS_SEARCH_INDEX,- general: [...SETTINGS_SEARCH_INDEX.general, "settings.about.updates"],+ general: [+ ...SETTINGS_SEARCH_INDEX.general,+ "settings.about.updates",+ "settings.general.startup.sectionTitle",+ "settings.general.startup.launchAtLogin",+ ],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 f8427b7320c..3e28cff31b1 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -56,6 +56,7 @@ import {loadUploadLimitSettings,updateUploadLimitSettings,} from "../api/upload-limit";+import { loadLaunchAtLogin, updateLaunchAtLogin } from "../api/launch-at-login";import { ChangePasswordDialog } from "../components/change-password-dialog";import {DesktopUpdateControl,@@ -189,6 +190,11 @@ 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 [embeddingModel, setEmbeddingModel] =useState<EmbeddingModelSettings | null>(null);const [draftEmbeddingModel, setDraftEmbeddingModel] = useState("");@@ -320,6 +326,44 @@ 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);@@ -580,6 +624,28 @@ export function GeneralTab() {</SettingsRow></SettingsSection>+ {isTauri ? (+ <SettingsSection title={t("settings.general.startup.sectionTitle")}>+ <SettingsRow+ label={t("settings.general.startup.launchAtLogin")}+ description={t("settings.general.startup.launchAtLoginDescription")}+ >+ <div className="flex flex-col items-end gap-1">+ <Switch+ checked={launchAtLogin ?? false}+ disabled={launchAtLogin === null || isSavingLaunchAtLogin}+ onCheckedChange={(enabled) => void saveLaunchAtLogin(enabled)}+ />+ {launchAtLoginError ? (+ <span className="max-w-[260px] text-right text-xs text-destructive">+ {launchAtLoginError}+ </span>+ ) : null}+ </div>+ </SettingsRow>+ </SettingsSection>+ ) : null}+<SettingsSection title={t("settings.general.notifications.sectionTitle")}><SettingsRowlabel={t("settings.general.notifications.showLlamaUpdates")}diff --git a/studio/frontend/src/hooks/use-tauri-update.ts b/studio/frontend/src/hooks/use-tauri-update.tsindex 229e5438bef..ec00dbc36d7 100644--- a/studio/frontend/src/hooks/use-tauri-update.ts+++ b/studio/frontend/src/hooks/use-tauri-update.ts@@ -386,8 +386,17 @@ export function useTauriUpdate(isExternalServer = false) {publishShellUpdateActive(false);}+ // relaunch() re-execs with the original argv, so flag the inherited --hidden as not a login+ // start. It only fails when there is a --hidden to suppress, so let it stop the restart.+ await invoke("mark_in_app_relaunch");const { relaunch } = await import("@tauri-apps/plugin-process");- await relaunch();+ try {+ await relaunch();+ } catch (relaunchError) {+ // No replacement process, so the marker would outlive it and unhide a later login start.+ await invoke("clear_in_app_relaunch").catch(() => {});+ throw relaunchError;+ }} catch (e) {console.error("Update failed:", e);const msg = String(e);diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex cd7aee6ad6b..82a8c763847 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -402,6 +402,14 @@ export const ar = {showLlamaUpdatesDescription:"التنبيه عند توفر إصدار أحدث من llama.cpp لتشغيل نماذج جديدة. أوقف التشغيل إذا كنت تُدرّب فقط.",},+ startup: {+ sectionTitle: "بدء التشغيل",+ launchAtLogin: "تشغيل Unsloth عند تسجيل الدخول",+ launchAtLoginDescription:+ "يبدأ Unsloth في الخلفية عند تسجيل الدخول، ويبقى في شريط القوائم أو علبة النظام حتى تفتحه.",+ loadError: "تعذر تحميل إعداد التشغيل عند تسجيل الدخول.",+ saveError: "تعذر تحديث إعداد التشغيل عند تسجيل الدخول.",+ },gettingStarted: "البدء",startOnboarding: "بدء الإعداد التمهيدي",startOnboardingDescription:diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex d42ce3354bb..fb4dfd758ce 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -419,6 +419,15 @@ export const de = {showLlamaUpdatesDescription:"Benachrichtigt, wenn ein neuerer llama.cpp-Build verfügbar ist, um neue Modelle auszuführen. Deaktivieren Sie dies, wenn Sie nur trainieren.",},+ startup: {+ sectionTitle: "Autostart",+ 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.",+ loadError: "Die Autostart-Einstellung konnte nicht geladen werden.",+ saveError:+ "Die Autostart-Einstellung konnte nicht aktualisiert werden.",+ },gettingStarted: "Erste Schritte",startOnboarding: "Einrichtung starten",startOnboardingDescription:diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex f0af4dc67fc..c7b7d037ac8 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -401,6 +401,14 @@ export const en = {showLlamaUpdatesDescription:"Notify when a newer llama.cpp build is available to run new models. Turn off if you only train.",},+ startup: {+ sectionTitle: "Startup",+ 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.",+ loadError: "Failed to load the launch at login setting.",+ saveError: "Failed to update the launch at login setting.",+ },gettingStarted: "Getting started",startOnboarding: "Start onboarding",startOnboardingDescription:diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 20bfc92eadf..cdf6b689163 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -415,6 +415,14 @@ export const es = {showLlamaUpdatesDescription:"Avisa cuando haya una compilación más reciente de llama.cpp para ejecutar nuevos modelos. Desactívalo si solo entrenas.",},+ startup: {+ sectionTitle: "Inicio",+ 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.",+ loadError: "No se pudo cargar el ajuste de inicio automático.",+ saveError: "No se pudo actualizar el ajuste de inicio automático.",+ },gettingStarted: "Primeros pasos",startOnboarding: "Iniciar la configuración inicial",startOnboardingDescription:diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 5d70202bdc1..81c168774c9 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -417,6 +417,16 @@ export const fr = {showLlamaUpdatesDescription:"Notifier lorsqu'une nouvelle version de llama.cpp est disponible pour exécuter de nouveaux modèles. Désactivez si vous ne faites que de l'entraînement.",},+ startup: {+ sectionTitle: "Démarrage",+ 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.",+ loadError:+ "Impossible de charger le réglage de lancement à la connexion.",+ saveError:+ "Impossible de mettre à jour le réglage de lancement à la connexion.",+ },gettingStarted: "Prise en main",startOnboarding: "Démarrer la prise en main",startOnboardingDescription:diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 15a5ef77fc5..427c8afe0eb 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -405,6 +405,14 @@ export const hi = {showLlamaUpdatesDescription:"नए मॉडल चलाने के लिए जब कोई नया llama.cpp बिल्ड उपलब्ध हो तो सूचित करें। यदि आप केवल ट्रेन करते हैं तो बंद कर दें।",},+ startup: {+ sectionTitle: "स्टार्टअप",+ launchAtLogin: "लॉगिन पर Unsloth चलाएं",+ launchAtLoginDescription:+ "लॉगिन करने पर Unsloth को बैकग्राउंड में शुरू करता है। इसे खोलने तक यह मेनू बार या सिस्टम ट्रे में रहता है।",+ loadError: "लॉगिन पर चलाने की सेटिंग लोड नहीं हो सकी।",+ saveError: "लॉगिन पर चलाने की सेटिंग अपडेट नहीं हो सकी।",+ },gettingStarted: "शुरुआत करें",startOnboarding: "ऑनबोर्डिंग शुरू करें",startOnboardingDescription:diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex c168befd529..9049790f71e 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -392,6 +392,15 @@ export const it = {showLlamaUpdatesDescription:"Avvisa quando è disponibile una build più recente di llama.cpp per eseguire nuovi modelli. Disattiva le notifiche se usi Unsloth solo per l'addestramento.",},+ startup: {+ sectionTitle: "Avvio",+ 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.",+ loadError: "Impossibile caricare l'impostazione di avvio all'accesso.",+ saveError:+ "Impossibile aggiornare l'impostazione di avvio all'accesso.",+ },gettingStarted: "Per iniziare",startOnboarding: "Avvia la configurazione guidata",startOnboardingDescription:diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 8f64f7edfc4..a58e305682c 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -393,6 +393,14 @@ export const ja = {showLlamaUpdates: "llama.cpp のアップデート通知",showLlamaUpdatesDescription: "新しいモデルを実行するための新しい llama.cpp ビルドが利用可能になったときに通知します。トレーニングのみを行う場合はオフにしてください。",},+ startup: {+ sectionTitle: "起動",+ launchAtLogin: "ログイン時に Unsloth を起動",+ launchAtLoginDescription:+ "ログイン時に Unsloth をバックグラウンドで起動します。開くまでメニューバーまたはシステムトレイに常駐します。",+ loadError: "ログイン時起動の設定を読み込めませんでした。",+ saveError: "ログイン時起動の設定を更新できませんでした。",+ },gettingStarted: "はじめに",startOnboarding: "オンボーディングを開始",startOnboardingDescription: "アカウントを変更せずにセットアップウィザードを再開します。",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex e099e740de9..5b694902ac9 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -399,6 +399,14 @@ export const ko = {showLlamaUpdatesDescription:"새 모델을 실행할 수 있는 최신 llama.cpp 빌드가 있으면 알립니다. 학습만 사용한다면 끄세요.",},+ startup: {+ sectionTitle: "시작",+ launchAtLogin: "로그인 시 Unsloth 실행",+ launchAtLoginDescription:+ "로그인하면 Unsloth를 백그라운드에서 시작합니다. 열기 전까지 메뉴 막대 또는 시스템 트레이에 남아 있습니다.",+ loadError: "로그인 시 실행 설정을 불러오지 못했습니다.",+ saveError: "로그인 시 실행 설정을 업데이트하지 못했습니다.",+ },gettingStarted: "시작하기",startOnboarding: "온보딩 시작",startOnboardingDescription:diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 69a1b1399b1..cdf7f0d3536 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -406,6 +406,16 @@ export const ptBR = {showLlamaUpdatesDescription:"Notifica quando uma versão mais recente do llama.cpp está disponível para executar novos modelos. Desative se você só treina modelos.",},+ startup: {+ sectionTitle: "Inicialização",+ 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.",+ loadError:+ "Não foi possível carregar a configuração de inicialização no login.",+ saveError:+ "Não foi possível atualizar a configuração de inicialização no login.",+ },gettingStarted: "Primeiros passos",startOnboarding: "Iniciar configuração",startOnboardingDescription:diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 94f5ff45c17..496b42f2e70 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -404,6 +404,14 @@ export const ru = {showLlamaUpdatesDescription:"Уведомлять о доступности новой сборки llama.cpp для запуска новых моделей. Отключите, если вы только обучаете модели.",},+ startup: {+ sectionTitle: "Автозапуск",+ launchAtLogin: "Запускать Unsloth при входе в систему",+ launchAtLoginDescription:+ "Запускает Unsloth в фоновом режиме при входе в систему. Приложение остаётся в строке меню или системном трее, пока вы его не откроете.",+ loadError: "Не удалось загрузить настройку автозапуска.",+ saveError: "Не удалось обновить настройку автозапуска.",+ },gettingStarted: "Начало работы",startOnboarding: "Запустить онбординг",startOnboardingDescription:diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 02673b62719..8c6dd4bd0dd 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -386,6 +386,14 @@ export const zhCN = {showLlamaUpdatesDescription:"当有可用于运行新模型的新版 llama.cpp 构建时通知你。如果只进行训练,可以关闭此项。",},+ startup: {+ sectionTitle: "启动",+ launchAtLogin: "登录时运行 Unsloth",+ launchAtLoginDescription:+ "登录系统时在后台启动 Unsloth。在你打开它之前,它会一直驻留在菜单栏或系统托盘中。",+ loadError: "无法加载登录时启动设置。",+ saveError: "无法更新登录时启动设置。",+ },gettingStarted: "入门",startOnboarding: "开始引导",startOnboardingDescription: "重新打开设置向导,不会更改你的账号。",diff --git a/studio/frontend/tests/settings-search.test.ts b/studio/frontend/tests/settings-search.test.tsindex fc658e7ea0e..f562eb88803 100644--- a/studio/frontend/tests/settings-search.test.ts+++ b/studio/frontend/tests/settings-search.test.ts@@ -21,3 +21,18 @@ test("browser update searches keep routing to About", () => {assert.ok(!index.general.includes(UPDATE_ENTRY));assert.ok(index.about.includes(UPDATE_ENTRY));});++const STARTUP_ENTRIES = [+ "settings.general.startup.sectionTitle",+ "settings.general.startup.launchAtLogin",+] as const;++test("startup entries are searchable on desktop only", () => {+ const desktop = createSettingsSearchIndex(true);+ const browser = createSettingsSearchIndex(false);++ for (const entry of STARTUP_ENTRIES) {+ assert.ok(desktop.general.includes(entry));+ assert.ok(!browser.general.includes(entry));+ }+});diff --git a/studio/src-tauri/Cargo.lock b/studio/src-tauri/Cargo.lockindex d0713d57ae4..3131e1471cf 100644--- a/studio/src-tauri/Cargo.lock+++ b/studio/src-tauri/Cargo.lock@@ -237,6 +237,17 @@ version = "1.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"+[[package]]+name = "auto-launch"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f012b8cc0c850f34117ec8252a44418f2e34a2cf501de89e29b241ae5f79471"+dependencies = [+ "dirs 4.0.0",+ "thiserror 1.0.69",+ "winreg 0.10.1",+]+[[package]]name = "autocfg"version = "1.5.0"@@ -898,13 +909,33 @@ dependencies = ["ctutils",]+[[package]]+name = "dirs"+version = "4.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059"+dependencies = [+ "dirs-sys 0.3.7",+]+[[package]]name = "dirs"version = "6.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"dependencies = [- "dirs-sys",+ "dirs-sys 0.5.0",+]++[[package]]+name = "dirs-sys"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6"+dependencies = [+ "libc",+ "redox_users 0.4.6",+ "winapi",][[package]]@@ -915,7 +946,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"dependencies = ["libc","option-ext",- "redox_users",+ "redox_users 0.5.2","windows-sys 0.61.2",]@@ -1071,7 +1102,7 @@ dependencies = ["rustc_version","toml 0.9.12+spec-1.1.0","vswhom",- "winreg",+ "winreg 0.55.0",][[package]]@@ -3691,6 +3722,17 @@ dependencies = ["bitflags 2.11.0",]+[[package]]+name = "redox_users"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"+dependencies = [+ "getrandom 0.2.17",+ "libredox",+ "thiserror 1.0.69",+]+[[package]]name = "redox_users"version = "0.5.2"@@ -4702,7 +4744,7 @@ dependencies = ["anyhow","bytes","cookie",- "dirs",+ "dirs 6.0.0","dunce","embed_plist","getrandom 0.3.4",@@ -4752,7 +4794,7 @@ checksum = "4aa1f9055fc23919a54e4e125052bed16ed04aef0487086e758fe01a67b451c7"dependencies = ["anyhow","cargo_toml",- "dirs",+ "dirs 6.0.0","glob","heck 0.5.0","json-patch",@@ -4823,6 +4865,20 @@ dependencies = ["walkdir",]+[[package]]+name = "tauri-plugin-autostart"+version = "2.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "459383cebc193cdd03d1ba4acc40f2c408a7abce419d64bdcd2d745bc2886f70"+dependencies = [+ "auto-launch",+ "serde",+ "serde_json",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.18",+]+[[package]]name = "tauri-plugin-clipboard-manager"version = "2.3.2"@@ -4975,7 +5031,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "806d9dac662c2e4594ff03c647a552f2c9bd544e7d0f683ec58f872f952ce4af"dependencies = ["base64 0.22.1",- "dirs",+ "dirs 6.0.0","flate2","futures-util","http",@@ -5543,7 +5599,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "15edbb0d80583e85ee8df283410038e17314df5cba30da2087a54a85216c0773"dependencies = ["crossbeam-channel",- "dirs",+ "dirs 6.0.0","libappindicator","muda","objc2",@@ -5663,7 +5719,7 @@ version = "2026.4.8"dependencies = ["arboard","base64 0.22.1",- "dirs",+ "dirs 6.0.0","elevated-command","fix-path-env","gdk",@@ -5685,6 +5741,7 @@ dependencies = ["simplelog","tauri","tauri-build",+ "tauri-plugin-autostart","tauri-plugin-clipboard-manager","tauri-plugin-deep-link","tauri-plugin-dialog",@@ -5699,6 +5756,7 @@ dependencies = ["tokio","windows 0.62.2","windows-sys 0.61.2",+ "winreg 0.10.1",][[package]]@@ -6698,6 +6756,15 @@ dependencies = ["memchr",]+[[package]]+name = "winreg"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"+dependencies = [+ "winapi",+]+[[package]]name = "winreg"version = "0.55.0"@@ -6830,7 +6897,7 @@ dependencies = ["block2","cookie","crossbeam-channel",- "dirs",+ "dirs 6.0.0","dom_query","dpi","dunce",diff --git a/studio/src-tauri/Cargo.toml b/studio/src-tauri/Cargo.tomlindex cbb8215f14c..24b5aabebdb 100644--- a/studio/src-tauri/Cargo.toml+++ b/studio/src-tauri/Cargo.toml@@ -14,6 +14,7 @@ edition = "2021"[dependencies]tauri = { version = "2", features = ["tray-icon"] }tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }+tauri-plugin-autostart = "2"tauri-plugin-deep-link = "2"tauri-plugin-process = "2"serde = { version = "1", features = ["derive"] }@@ -53,6 +54,7 @@ gtk = "0.18"elevated-command = "1.1.2"[target.'cfg(windows)'.dependencies]+winreg = "0.10"windows = { version = "0.62.2", features = ["Win32_System_Threading"] }windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_Console", "Win32_System_JobObjects", "Win32_System_Threading"] }diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex f3ea0c3e3b6..49d97fcc8fb 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -25,9 +25,11 @@ use process::new_backend_state;use simplelog::{CombinedLogger, Config, LevelFilter, SharedLogger, TermLogger, TerminalMode, WriteLogger,};+use std::ffi::OsStr;use std::fs;+use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::Once;+use std::sync::{Once, OnceLock};use tauri::menu::{MenuBuilder, MenuItemBuilder};use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};use tauri::{Emitter, Manager};@@ -38,6 +40,338 @@ use tauri_plugin_window_state::{AppHandleExt, StateFlags};/// Exactly one runs cleanup; the others block, so the process never exits mid-reap.static TERMINATION_CLEANUP: Once = Once::new();+const IN_APP_RELAUNCH_MARKER_FILE: &str = "in-app-relaunch-v1";++/// Resolved once, at setup, where the marker is consumed, so no later caller can flip the answer.+static LAUNCHED_HIDDEN: OnceLock<bool> = OnceLock::new();++/// Marks the next start as an in-app relaunch, whose inherited `--hidden` is not a login start.+#[tauri::command]+fn mark_in_app_relaunch(app: tauri::AppHandle) -> Result<(), String> {+ // Nothing to suppress without an inherited `--hidden`; the caller stops the restart on failure.+ if !argv_has_hidden_flag() {+ return Ok(());+ }+ let dir = in_app_relaunch_config_dir(&app)?;+ fs::create_dir_all(&dir).map_err(|error| {+ format!(+ "Failed to create app configuration directory {}: {error}",+ dir.display()+ )+ })?;+ write_in_app_relaunch_marker(&dir)+}++/// Undo the marker when its relaunch never happens, so an unrelated later start cannot consume it.+#[tauri::command]+fn clear_in_app_relaunch(app: tauri::AppHandle) -> Result<(), String> {+ let dir = in_app_relaunch_config_dir(&app)?;+ take_in_app_relaunch_marker(&dir);+ Ok(())+}++fn in_app_relaunch_config_dir(app: &tauri::AppHandle) -> Result<PathBuf, String> {+ app.path()+ .app_config_dir()+ .map_err(|error| format!("Could not determine app configuration directory: {error}"))+}++fn in_app_relaunch_marker_path(config_dir: &Path) -> PathBuf {+ config_dir.join(IN_APP_RELAUNCH_MARKER_FILE)+}++fn write_in_app_relaunch_marker(config_dir: &Path) -> Result<(), String> {+ let path = in_app_relaunch_marker_path(config_dir);+ fs::write(&path, b"relaunching\n").map_err(|error| {+ format!(+ "Failed to write in-app relaunch marker {}: {error}",+ path.display()+ )+ })+}++/// Consumes the marker. A failed removal can only show a would-be-hidden start, never the reverse.+fn take_in_app_relaunch_marker(config_dir: &Path) -> bool {+ let path = in_app_relaunch_marker_path(config_dir);+ if !path.exists() {+ return false;+ }+ if let Err(error) = fs::remove_file(&path) {+ warn!(+ "Could not remove the in-app relaunch marker {}: {error}",+ path.display()+ );+ }+ true+}++/// args_os, not args: args panics on non-Unicode argv, e.g. argv[0] under a non-UTF-8 path.+fn argv_has_hidden_flag() -> bool {+ std::env::args_os().any(|arg| arg == *OsStr::new("--hidden"))+}++fn resolve_launched_hidden(app: &tauri::AppHandle) -> bool {+ // Consume unconditionally, so a marker left by a relaunch that never happened cannot outlive it.+ let relaunched = in_app_relaunch_config_dir(app)+ .map(|dir| take_in_app_relaunch_marker(&dir))+ .unwrap_or(false);+ argv_has_hidden_flag() && !relaunched+}++/// True for a login autostart start (window stays in the tray); false for an in-app relaunch,+/// which inherits `--hidden` without being one.+#[tauri::command]+fn was_launched_hidden(app: tauri::AppHandle) -> bool {+ *LAUNCHED_HIDDEN.get_or_init(|| resolve_launched_hidden(&app))+}++#[tauri::command]+fn reveal_main_window(app: tauri::AppHandle) {+ show_main_window(&app);+}++#[tauri::command]+fn get_launch_at_login(app: tauri::AppHandle) -> Result<bool, String> {+ use tauri_plugin_autostart::ManagerExt;+ // is_enabled only checks the entry file exists, so a DE-disabled entry would read as on.+ if cfg!(target_os = "linux") && linux_autostart_disabled(&app) {+ return Ok(false);+ }+ app.autolaunch()+ .is_enabled()+ .map_err(|error| error.to_string())+}++#[tauri::command]+fn set_launch_at_login(app: tauri::AppHandle, enabled: bool) -> Result<bool, String> {+ use tauri_plugin_autostart::ManagerExt;+ let autolaunch = app.autolaunch();+ let result = if enabled {+ autolaunch.enable()+ } else {+ autolaunch.disable()+ };+ result.map_err(|error| error.to_string())?;+ if enabled {+ harden_autostart_entry(&app);+ }+ autolaunch+ .is_enabled()+ .map_err(|error| error.to_string())+}++fn harden_autostart_entry(app: &tauri::AppHandle) {+ if cfg!(target_os = "linux") {+ guard_linux_autostart_entry(app);+ }+ #[cfg(windows)]+ quote_windows_run_value(app);+ #[cfg(target_os = "macos")]+ rewrite_macos_launch_agent(app);+}++/// auto-launch writes the Run value unquoted, so a spaced path resolves to the wrong executable.+/// None when already quoted.+#[cfg_attr(not(windows), allow(dead_code))]+fn quoted_windows_run_command(value: &str) -> Option<String> {+ if value.starts_with('"') {+ return None;+ }+ let (path, args) = match value.strip_suffix(" --hidden") {+ Some(path) => (path, " --hidden"),+ None => (value, ""),+ };+ Some(format!("\"{path}\"{args}"))+}++#[cfg(windows)]+fn quote_windows_run_value(app: &tauri::AppHandle) {+ use winreg::enums::{HKEY_CURRENT_USER, KEY_QUERY_VALUE, KEY_SET_VALUE};+ use winreg::RegKey;++ let hkcu = RegKey::predef(HKEY_CURRENT_USER);+ let Ok(run) = hkcu.open_subkey_with_flags(+ r"Software\Microsoft\Windows\CurrentVersion\Run",+ KEY_QUERY_VALUE | KEY_SET_VALUE,+ ) else {+ return;+ };+ let name = &app.package_info().name;+ let Ok(value) = run.get_value::<String, _>(name) else {+ return;+ };+ if let Some(quoted) = quoted_windows_run_command(&value) {+ let _ = run.set_value(name, "ed);+ }+}++/// Exec is whitespace-delimited: quote a path holding reserved characters, escaping `"`, `` ` ``,+/// `$` and `\` inside, and double a literal `%` regardless, since it would start a field code.+fn exec_quoted(binary: &str) -> String {+ let binary = binary.replace('%', "%%");+ const RESERVED: &str = " \t\n\"'\\><~|&;$*?#()`";+ if !binary.chars().any(|c| RESERVED.contains(c)) {+ return binary;+ }+ let mut quoted = String::with_capacity(binary.len() + 2);+ quoted.push('"');+ for c in binary.chars() {+ // The string rule runs before the quoting rule, so the escaping backslash is itself+ // escaped; a single one is invalid and launchers drop the whole Exec.+ match c {+ '"' | '`' | '$' => {+ quoted.push_str("\\\\");+ quoted.push(c);+ }+ '\\' => quoted.push_str("\\\\\\\\"),+ _ => quoted.push(c),+ }+ }+ quoted.push('"');+ quoted+}++/// Quote auto-launch's unquoted Exec binary and add TryExec, which launchers skip when missing, so+/// a removed install goes inert without postrm touching user homes. TryExec stays unquoted.+fn hardened_autostart_entry(entry: &str) -> Option<String> {+ if entry.lines().any(|line| line.starts_with("TryExec=")) {+ return None;+ }+ let exec = entry.lines().find_map(|line| line.strip_prefix("Exec="))?;+ let (binary, args) = match exec.strip_suffix(" --hidden") {+ Some(binary) => (binary, " --hidden"),+ None => (exec, ""),+ };+ let hardened = entry+ .lines()+ .map(|line| {+ if line.starts_with("Exec=") {+ format!("Exec={}{}", exec_quoted(binary), args)+ } else {+ line.to_string()+ }+ })+ .collect::<Vec<_>>()+ .join("\n");+ // TryExec skips the quoting rule but is still a string, so backslashes still escape.+ Some(format!(+ "{hardened}\nTryExec={}",+ binary.replace('\\', "\\\\")+ ))+}++fn linux_autostart_entry_path(app: &tauri::AppHandle) -> Option<std::path::PathBuf> {+ // auto-launch hardcodes ~/.config regardless of XDG_CONFIG_HOME; mirror it or we miss the file.+ Some(+ dirs::home_dir()?+ .join(".config")+ .join("autostart")+ .join(format!("{}.desktop", app.package_info().name)),+ )+}++/// DE startup UIs disable an entry via Hidden=true or X-GNOME-Autostart-enabled=false, not deletion.+fn autostart_entry_disabled(entry: &str) -> bool {+ entry.lines().any(|line| {+ matches!(+ line.trim(),+ "Hidden=true" | "X-GNOME-Autostart-enabled=false"+ )+ })+}++fn linux_autostart_disabled(app: &tauri::AppHandle) -> bool {+ linux_autostart_entry_path(app)+ .and_then(|path| fs::read_to_string(path).ok())+ .is_some_and(|entry| autostart_entry_disabled(&entry))+}++fn guard_linux_autostart_entry(app: &tauri::AppHandle) {+ let Some(path) = linux_autostart_entry_path(app) else {+ return;+ };+ let Ok(entry) = fs::read_to_string(&path) else {+ return;+ };+ if let Some(hardened) = hardened_autostart_entry(&entry) {+ let _ = fs::write(&path, hardened);+ }+}++#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+fn xml_escaped(value: &str) -> String {+ value+ .replace('&', "&")+ .replace('<', "<")+ .replace('>', ">")+}++/// The plugin's template, but escaped: it interpolates the path unescaped, so a path with & or <+/// writes a malformed LaunchAgent.+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+fn macos_launch_agent_plist(label: &str, binary: &str) -> String {+ format!(+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\+ <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\+ <plist version=\"1.0\">\n\+ <dict>\n \+ <key>Label</key>\n \+ <string>{}</string>\n \+ <key>ProgramArguments</key>\n \+ <array>\n \+ <string>{}</string>\n \+ <string>--hidden</string>\n \+ </array>\n \+ <key>RunAtLoad</key>\n \+ <true/>\n\+ </dict>\n\+ </plist>",+ xml_escaped(label),+ xml_escaped(binary),+ )+}++#[cfg(target_os = "macos")]+fn rewrite_macos_launch_agent(app: &tauri::AppHandle) {+ let Some(home_dir) = dirs::home_dir() else {+ return;+ };+ let name = &app.package_info().name;+ let path = home_dir+ .join("Library")+ .join("LaunchAgents")+ .join(format!("{name}.plist"));+ if !path.exists() {+ return;+ }+ let Ok(binary) = std::env::current_exe() else {+ return;+ };+ let plist = macos_launch_agent_plist(name, &binary.display().to_string());+ let _ = fs::write(&path, plist);+}++/// A moved or re-downloaded AppImage leaves a stale path that `is_enabled` still accepts, so+/// repoint the entry at the current executable on every startup.+fn reconcile_autostart_entry(app: &tauri::AppHandle) {+ use tauri_plugin_autostart::ManagerExt;+ // A dev run would repoint the entry at target/debug.+ if cfg!(debug_assertions) {+ return;+ }+ // enable() would rewrite the file without the user's DE-set disabled marker.+ if cfg!(target_os = "linux") && linux_autostart_disabled(app) {+ return;+ }+ let autolaunch = app.autolaunch();+ if !autolaunch.is_enabled().unwrap_or(false) {+ return;+ }+ if autolaunch.enable().is_ok() {+ harden_autostart_entry(app);+ }+}+#[tauri::command]fn has_saved_window_state(app: tauri::AppHandle) -> bool {let Ok(dir) = app.path().app_config_dir() else {@@ -368,6 +702,9 @@ fn setup_unix_termination_signals(app: &tauri::App) -> Result<(), Box<dyn std::e}fn show_main_window(app: &tauri::AppHandle) {+ // Hidden login starts run as an accessory app (no Dock icon); restore the regular policy.+ #[cfg(target_os = "macos")]+ let _ = app.set_activation_policy(tauri::ActivationPolicy::Regular);if let Some(window) = app.get_webview_window("main") {let _ = window.show();let _ = window.unminimize();@@ -482,6 +819,10 @@ fn main() {show_main_window(app);})).plugin(tauri_plugin_deep_link::init())+ .plugin(tauri_plugin_autostart::init(+ tauri_plugin_autostart::MacosLauncher::LaunchAgent,+ Some(vec!["--hidden"]),+ )).plugin(tauri_plugin_process::init()).plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_notification::init())@@ -543,8 +884,23 @@ fn main() {native_intents::reveal_path_token,native_intents::open_path_token,has_saved_window_state,+ was_launched_hidden,+ mark_in_app_relaunch,+ clear_in_app_relaunch,+ reveal_main_window,+ get_launch_at_login,+ set_launch_at_login,]).setup(|app| {+ // Resolve here, before any window path can ask: this consumes the relaunch marker.+ let launched_hidden = was_launched_hidden(app.handle().clone());+ #[cfg(not(target_os = "macos"))]+ let _ = launched_hidden;+ #[cfg(target_os = "macos")]+ if launched_hidden {+ app.set_activation_policy(tauri::ActivationPolicy::Accessory);+ }+ reconcile_autostart_entry(app.handle());#[cfg(any(target_os = "linux", all(debug_assertions, windows)))]{use tauri_plugin_deep_link::DeepLinkExt;@@ -603,6 +959,36 @@ fn main() {mod tests {use super::*;+ /// args() panics on a non-Unicode argv[0], so the flag scan has to run over OsStr.+ #[test]+ fn hidden_flag_scan_tolerates_non_unicode_args() {+ use std::ffi::OsString;+ #[cfg(unix)]+ use std::os::unix::ffi::OsStringExt;++ #[cfg(unix)]+ let args: Vec<OsString> = vec![+ OsString::from_vec(b"/opt/\xff\xfe/Unsloth".to_vec()),+ OsString::from("--hidden"),+ ];+ #[cfg(not(unix))]+ let args: Vec<OsString> = vec![OsString::from("Unsloth.exe"), OsString::from("--hidden")];++ assert!(args.iter().any(|arg| arg == OsStr::new("--hidden")));+ assert!(!args[..1].iter().any(|arg| arg == OsStr::new("--hidden")));+ }++ #[test]+ fn relaunch_marker_is_consumed_by_the_next_start() {+ let dir = tempfile::tempdir().unwrap();+ assert!(!take_in_app_relaunch_marker(dir.path()));++ write_in_app_relaunch_marker(dir.path()).unwrap();+ assert!(take_in_app_relaunch_marker(dir.path()));+ assert!(!take_in_app_relaunch_marker(dir.path()));+ assert!(!in_app_relaunch_marker_path(dir.path()).exists());+ }+// One test, not three: `QUIT_IN_PROGRESS` is process-global and cargo tests run in parallel.#[test]fn quit_guard_admits_one_quit_and_always_re_arms() {@@ -632,6 +1018,121 @@ mod tests {);}+ #[test]+ fn autostart_hardening_appends_the_exec_binary_without_args() {+ let entry = "[Desktop Entry]\nType=Application\nExec=/usr/bin/unsloth-studio --hidden\nTerminal=false";+ let hardened = hardened_autostart_entry(entry).expect("guard must be added");+ assert!(hardened.starts_with(entry));+ assert!(hardened.ends_with("\nTryExec=/usr/bin/unsloth-studio"));+ }++ #[test]+ fn autostart_hardening_quotes_a_binary_path_with_spaces() {+ let entry = "[Desktop Entry]\nExec=/home/n/My Apps/Unsloth.AppImage --hidden\nTerminal=false";+ let hardened = hardened_autostart_entry(entry).expect("guard must be added");+ assert!(hardened.contains("Exec=\"/home/n/My Apps/Unsloth.AppImage\" --hidden\n"));+ // TryExec is a plain string field, so the path stays unquoted.+ assert!(hardened.ends_with("\nTryExec=/home/n/My Apps/Unsloth.AppImage"));+ }++ #[test]+ fn autostart_hardening_escapes_exec_reserved_characters() {+ let entry = "[Desktop Entry]\nExec=/opt/a\"b$c/app --hidden";+ let hardened = hardened_autostart_entry(entry).expect("guard must be added");+ // Doubled: the string escape rule is undone before the quoting rule.+ assert!(hardened.contains(r#"Exec="/opt/a\\"b\\$c/app" --hidden"#));+ }++ /// A single escaping backslash is an invalid escape, so launchers discard the whole Exec.+ #[test]+ fn autostart_hardening_doubles_the_escaping_backslash() {+ let entry = "[Desktop Entry]\nExec=/opt/a b`c$d/app --hidden";+ let hardened = hardened_autostart_entry(entry).expect("guard must be added");+ assert!(hardened.contains(r#"Exec="/opt/a b\\`c\\$d/app" --hidden"#));+ }++ #[test]+ fn autostart_hardening_escapes_a_literal_backslash_in_both_fields() {+ let entry = "[Desktop Entry]\nExec=/opt/a b\\c/app --hidden";+ let hardened = hardened_autostart_entry(entry).expect("guard must be added");+ // Four in Exec (string rule then quoting rule), two in the plain TryExec.+ assert!(hardened.contains(r#"Exec="/opt/a b\\\\c/app" --hidden"#));+ assert!(hardened.ends_with(r"TryExec=/opt/a b\\c/app"));+ }++ #[test]+ fn autostart_hardening_is_idempotent() {+ let entry = "[Desktop Entry]\nExec=/a --hidden\nTryExec=/a";+ assert!(hardened_autostart_entry(entry).is_none());+ }++ #[test]+ fn autostart_hardening_needs_an_exec_line() {+ assert!(hardened_autostart_entry("[Desktop Entry]\nType=Application").is_none());+ }++ #[test]+ fn exec_quoting_escapes_percent_field_codes() {+ let entry = "[Desktop Entry]\nExec=/home/n/Unsloth%20Studio.AppImage --hidden";+ let hardened = hardened_autostart_entry(entry).expect("guard must be added");+ assert!(hardened.contains("Exec=/home/n/Unsloth%%20Studio.AppImage --hidden\n"));+ // TryExec is a plain string field, so the raw path stays.+ assert!(hardened.ends_with("\nTryExec=/home/n/Unsloth%20Studio.AppImage"));+ }++ #[test]+ fn autostart_disabled_markers_are_detected() {+ assert!(autostart_entry_disabled("[Desktop Entry]\nHidden=true"));+ assert!(autostart_entry_disabled(+ "[Desktop Entry]\nX-GNOME-Autostart-enabled=false"+ ));+ assert!(!autostart_entry_disabled("[Desktop Entry]\nExec=/a --hidden"));+ }++ #[test]+ fn macos_plist_escapes_xml_metacharacters() {+ let plist = macos_launch_agent_plist(+ "Unsloth",+ "/Applications/AI & ML/Unsloth.app/Contents/MacOS/unsloth-studio",+ );+ assert!(plist.contains(+ "<string>/Applications/AI & ML/Unsloth.app/Contents/MacOS/unsloth-studio</string>"+ ));+ assert!(plist.contains("<string>--hidden</string>"));+ assert!(plist.contains("<key>RunAtLoad</key>"));+ }++ #[test]+ fn windows_run_command_quotes_a_spaced_path() {+ let quoted =+ quoted_windows_run_command(r"C:\Users\Jane Doe\AppData\Local\Unsloth\Unsloth.exe --hidden");+ assert_eq!(+ quoted.as_deref(),+ Some(r#""C:\Users\Jane Doe\AppData\Local\Unsloth\Unsloth.exe" --hidden"#),+ );+ }++ #[test]+ fn windows_run_command_leaves_quoted_values_alone() {+ assert!(quoted_windows_run_command(r#""C:\Unsloth\Unsloth.exe" --hidden"#).is_none());+ }++ #[test]+ fn windows_run_command_quotes_a_bare_path() {+ assert_eq!(+ quoted_windows_run_command(r"C:\Unsloth\Unsloth.exe").as_deref(),+ Some(r#""C:\Unsloth\Unsloth.exe""#),+ );+ }++ #[test]+ fn autostart_hardening_keeps_foreign_args_untouched() {+ let entry = "[Desktop Entry]\nExec=/plain/app";+ let hardened = hardened_autostart_entry(entry).expect("guard must be added");+ assert!(hardened.contains("Exec=/plain/app\n"));+ assert!(hardened.ends_with("\nTryExec=/plain/app"));+ }+fn renderer_activity(state: &RendererActivityState) -> (bool, bool) {let activity = state.lock().expect("the activity mutex must not be poisoned");(activity.downloads, activity.shell_update)