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
Restore persisted Studio resource monitor (#10237)
Wasim Yousef Said99a83f6a6de1
diff --git a/studio/frontend/smoke-settings-main.tsx b/studio/frontend/smoke-settings-main.tsxindex 92a050dbd0d..a58e641d2a6 100644--- a/studio/frontend/smoke-settings-main.tsx+++ b/studio/frontend/smoke-settings-main.tsx@@ -6,7 +6,9 @@import { TooltipProvider } from "@/components/ui/tooltip";/* eslint-disable no-restricted-imports -- a harness entry point, not app code. */-import { SettingsDialog } from "@/features/settings/settings-dialog";+import { SettingsDialogMount } from "@/features/settings/settings-dialog-mount";+import { useMonitorOverlayStore } from "@/features/settings/stores/monitor-overlay-store";+import {type SettingsTab,useSettingsDialogStore,@@ -20,7 +22,7 @@ import {createRoute,createRouter,} from "@tanstack/react-router";-import { Component, StrictMode, type ReactNode } from "react";+import { Component, type ReactNode, StrictMode } from "react";import { createRoot } from "react-dom/client";import "./src/index.css";@@ -31,6 +33,8 @@ declare global {open: (tab?: string) => void;openArchived: (shelf: string) => void;close: () => void;++ setMonitor: (open: boolean) => void;setTab: (tab: string) => void;state: () => {open: boolean;@@ -75,12 +79,19 @@ window.__settingsSmoke = {},// The archive toasts' deep-open: straight to Data, on the shelf they name.openArchived: (shelf: string) => {- if (shelf === "chats") store.getState().openArchivedChats();- else store.getState().openArchivedMedia(shelf as "images" | "videos");+ if (shelf === "chats") {+ store.getState().openArchivedChats();+ } else {+ store.getState().openArchivedMedia(shelf as "images" | "videos");+ }},close: () => {store.getState().closeDialog();},++ setMonitor: (open: boolean) => {+ useMonitorOverlayStore.getState().setIsOpen(open);+ },setTab: (tab: string) => {store.getState().setActiveTab(tab as SettingsTab);},@@ -100,7 +111,7 @@ function Harness() {<TooltipProvider><div data-testid="harness-root"><Boundary>- <SettingsDialog />+ <SettingsDialogMount active /></Boundary></div></TooltipProvider>@@ -120,7 +131,9 @@ const harnessRouter = createRouter({});const rootElement = document.getElementById("root");-if (!rootElement) throw new Error("Root element not found");+if (!rootElement) {+ throw new Error("Root element not found");+}const root = createRoot(rootElement);const strict = !new URLSearchParams(window.location.search).has("nostrict");diff --git a/studio/frontend/src/features/settings/settings-dialog-mount.tsx b/studio/frontend/src/features/settings/settings-dialog-mount.tsxindex 399c37c3dde..4dd1f72073e 100644--- a/studio/frontend/src/features/settings/settings-dialog-mount.tsx+++ b/studio/frontend/src/features/settings/settings-dialog-mount.tsx@@ -15,7 +15,6 @@ import {useState,} from "react";import { isImeComposing } from "./hooks/use-shortcut";-import { useMonitorOverlayStore } from "./stores/monitor-overlay-store";import { useSettingsDialogStore } from "./stores/settings-dialog-store";@@ -24,6 +23,11 @@ const SettingsDialog = lazy(() =>default: module.SettingsDialog,})),);+const FloatingMonitor = lazy(() =>+ import("@/components/floating-monitor").then((module) => ({+ default: module.FloatingMonitor,+ })),+);function restoreSettingsOpener(opener: HTMLElement | null,@@ -87,46 +91,70 @@ function SettingsDialogLoading({ active }: { active: boolean }) {export function SettingsDialogMount({ active }: { active: boolean }) {const t = useT();-const closeDialog = useSettingsDialogStore((state) => state.closeDialog);-const opener = useSettingsDialogStore((state) => state.opener);const openerFallback = useSettingsDialogStore((state) => state.openerFallback,);- const open = useSettingsDialogStore((state) => state.open);+ const settingsOpen = useSettingsDialogStore((state) => state.open);const monitorOpen = useMonitorOverlayStore((state) => state.isOpen);-const setMonitorOpen = useMonitorOverlayStore((state) => state.setIsOpen);- const [mounted, setMounted] = useState(open || monitorOpen);+ const [settingsMounted, setSettingsMounted] = useState(settingsOpen);+ const [monitorMounted, setMonitorMounted] = useState(monitorOpen);useEffect(() => {- if (open || monitorOpen) setMounted(true);- }, [open, monitorOpen]);+ if (settingsOpen) setSettingsMounted(true);+ }, [settingsOpen]);+ useEffect(() => {+ if (monitorOpen) setMonitorMounted(true);+ }, [monitorOpen]);- if (!active || !mounted) return null;+ if (!active || !(settingsMounted || monitorMounted)) return null;return (- <LazyImportBoundary- fallback={- open || monitorOpen ? (- <LazyImportFailure- message={t("settings.dialog.panelFailed")}- reloadLabel={t("settings.dialog.panelReload")}- dismissLabel={t("common.close")}- onDismiss={() => {- closeDialog();- setMonitorOpen(false);- restoreSettingsOpener(opener, openerFallback);- }}- testId="settings-dialog-load-failure"- className="fixed top-1/2 left-1/2 z-[100] max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-popover p-5 text-popover-foreground shadow-xl"- />- ) : null- }- >- <Suspense fallback={<SettingsDialogLoading active={open} />}>- <SettingsDialog />- </Suspense>- </LazyImportBoundary>+ <>+ {settingsMounted && (+ <LazyImportBoundary+ fallback={+ settingsOpen ? (+ <LazyImportFailure+ message={t("settings.dialog.panelFailed")}+ reloadLabel={t("settings.dialog.panelReload")}+ dismissLabel={t("common.close")}+ onDismiss={() => {+ closeDialog();+ restoreSettingsOpener(opener, openerFallback);+ }}+ testId="settings-dialog-load-failure"+ className="fixed top-1/2 left-1/2 z-[100] max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-popover p-5 text-popover-foreground shadow-xl"+ />+ ) : null+ }+ >+ <Suspense fallback={<SettingsDialogLoading active={settingsOpen} />}>+ <SettingsDialog />+ </Suspense>+ </LazyImportBoundary>+ )}+ {monitorMounted && (+ <LazyImportBoundary+ fallback={+ monitorOpen ? (+ <LazyImportFailure+ message={t("settings.dialog.panelFailed")}+ reloadLabel={t("settings.dialog.panelReload")}+ dismissLabel={t("common.close")}+ onDismiss={() => setMonitorOpen(false)}+ testId="floating-monitor-load-failure"+ className="fixed top-16 right-4 z-[100] max-w-xs rounded-xl border border-border bg-popover p-4 text-popover-foreground shadow-lg"+ />+ ) : null+ }+ >+ <Suspense fallback={null}>+ <FloatingMonitor />+ </Suspense>+ </LazyImportBoundary>+ )}+ </>);}diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsxindex 09ba442a11f..5a98bf9f305 100644--- a/studio/frontend/src/features/settings/settings-dialog.tsx+++ b/studio/frontend/src/features/settings/settings-dialog.tsx@@ -1,7 +1,6 @@// 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 { FloatingMonitor } from "@/components/floating-monitor";import { getClientPlatform } from "@/components/tauri/window-titlebar";import { Button } from "@/components/ui/button";import {@@ -58,28 +57,36 @@ import {// Statically imported, every panel ran before first paint even though the dialog// starts closed. Load each on first view instead; this map also drives the prefetch.const TAB_LOADERS = {- general: () => import("./tabs/general-tab").then((m) => ({ default: m.GeneralTab })),- profile: () => import("./tabs/profile-tab").then((m) => ({ default: m.ProfileTab })),+ general: () =>+ import("./tabs/general-tab").then((m) => ({ default: m.GeneralTab })),+ profile: () =>+ import("./tabs/profile-tab").then((m) => ({ default: m.ProfileTab })),appearance: () =>import("./tabs/appearance-tab").then((m) => ({ default: m.AppearanceTab })),resources: () =>import("./tabs/resources-tab").then((m) => ({ default: m.ResourcesTab })),chat: () => import("./tabs/chat-tab").then((m) => ({ default: m.ChatTab })),- voice: () => import("./tabs/voice-tab").then((m) => ({ default: m.VoiceTab })),+ voice: () =>+ import("./tabs/voice-tab").then((m) => ({ default: m.VoiceTab })),connections: () =>- import("./tabs/connections-tab").then((m) => ({ default: m.ConnectionsTab })),+ import("./tabs/connections-tab").then((m) => ({+ default: m.ConnectionsTab,+ })),data: () => import("./tabs/data-tab").then((m) => ({ default: m.DataTab })),"keyboard-shortcuts": () =>import("./tabs/keyboard-shortcuts-tab").then((m) => ({default: m.KeyboardShortcutsTab,})),- "api-keys": () => import("./tabs/api-keys-tab").then((m) => ({ default: m.ApiKeysTab })),+ "api-keys": () =>+ import("./tabs/api-keys-tab").then((m) => ({ default: m.ApiKeysTab })),"remote-lan": () =>import("./tabs/remote-lan-tab").then((m) => ({ default: m.RemoteLanTab })),- agents: () => import("./tabs/agents-tab").then((m) => ({ default: m.AgentsTab })),+ agents: () =>+ import("./tabs/agents-tab").then((m) => ({ default: m.AgentsTab })),debugging: () =>import("./tabs/debugging-tab").then((m) => ({ default: m.DebuggingTab })),- about: () => import("./tabs/about-tab").then((m) => ({ default: m.AboutTab })),+ about: () =>+ import("./tabs/about-tab").then((m) => ({ default: m.AboutTab })),} satisfies Record<SettingsTab, () => Promise<{ default: FC }>>;function lazyTabs<T extends Record<string, () => Promise<{ default: FC }>>>(@@ -134,7 +141,9 @@ class SettingsPanelBoundary extends Component<}render() {- if (!this.state.failed) return this.props.children;+ if (!this.state.failed) {+ return this.props.children;+ }return (<div className="flex min-h-40 flex-1 flex-col items-center justify-center gap-3 text-center"><p className="text-muted-foreground text-sm">{this.props.message}</p>@@ -261,7 +270,9 @@ export function SettingsDialog() {// Once opened, pull the other panels in on idle so a tab click never waits on the// network. Nothing runs while closed, which is its state for the whole launch.useEffect(() => {- if (!open) return;+ if (!open) {+ return;+ }return scheduleIdleTask(() => {for (const load of Object.values(TAB_LOADERS)) {// Warming a panel nobody asked for must not surface as an unhandled rejection;@@ -273,12 +284,16 @@ export function SettingsDialog() {const results = useMemo(() => {const q = query.trim().toLowerCase();- if (!q) return null;+ if (!q) {+ return null;+ }return TABS.map((tab) => {const tabLabel = t(tab.labelKey);const entries = SETTINGS_SEARCH_INDEX[tab.id].filter((key) => {- if (t(key).toLowerCase().includes(q)) return true;+ if (t(key).toLowerCase().includes(q)) {+ return true;+ }const keywordsKey = SETTINGS_SEARCH_KEYWORDS[key];return keywordsKey ? t(keywordsKey).toLowerCase().includes(q) : false;})@@ -310,12 +325,18 @@ export function SettingsDialog() {// renders deferred and some sections load their data lazily, so observe the// panel until the requested row exists instead of imposing a render deadline.useEffect(() => {- if (!pendingScroll) return;+ if (!pendingScroll) {+ return;+ }// Wait until the destination tab is mounted before matching, so a same-named// row in the previous tab (for example "Storage") is not scrolled to instead.- if (panelTab !== pendingScroll.tab) return;+ if (panelTab !== pendingScroll.tab) {+ return;+ }const root = mainScrollRef.current;- if (!root) return;+ if (!root) {+ return;+ }const attempt = (): boolean => {const target = [...root.querySelectorAll<HTMLElement>("[data-settings-label]"),@@ -333,11 +354,15 @@ export function SettingsDialog() {return false;};const observer = new MutationObserver(() => {- if (attempt()) observer.disconnect();+ if (attempt()) {+ observer.disconnect();+ }});observer.observe(root, { childList: true, subtree: true });const frame = window.requestAnimationFrame(() => {- if (attempt()) observer.disconnect();+ if (attempt()) {+ observer.disconnect();+ }});return () => {observer.disconnect();@@ -346,7 +371,9 @@ export function SettingsDialog() {}, [pendingScroll, panelTab]);useEffect(() => {- if (open) return;+ if (open) {+ return;+ }const frame = window.requestAnimationFrame(() => {setQuery("");setPendingScroll(null);@@ -371,7 +398,9 @@ export function SettingsDialog() {});useEffect(() => {- if (!open) return;+ if (!open) {+ return;+ }const frame = window.requestAnimationFrame(() => {const button = tabButtonRefs.current[activeTab];button?.focus({ preventScroll: true });@@ -612,7 +641,6 @@ export function SettingsDialog() {</div></DialogContent></Dialog>- <FloatingMonitor /></>);}diff --git a/studio/frontend/tests/find-in-page.test.ts b/studio/frontend/tests/find-in-page.test.tsindex 6c32162e51e..8afb809c998 100644--- a/studio/frontend/tests/find-in-page.test.ts+++ b/studio/frontend/tests/find-in-page.test.ts@@ -2799,7 +2799,10 @@ test("nothing of the engine is mounted while the bar is closed", async () => {"utf8",);assert.match(controller, /if \(!enabled \|\| !open\) return null;/);- assert.match(controller, /lazy\(\(\) => import\("\.\/find-bar-loader\.tsx"\)\)/);+ assert.match(+ controller,+ /lazy\(\(\) => import\("\.\/find-bar-loader\.tsx"\)\)/,+ );assert.equal(controller.includes("useFindInPage("), false);const loadedBar = await readFile(diff --git a/studio/frontend/tests/monitor-frame-ownership.test.ts b/studio/frontend/tests/monitor-frame-ownership.test.tsindex 3127629bea9..29f7521a395 100644--- a/studio/frontend/tests/monitor-frame-ownership.test.ts+++ b/studio/frontend/tests/monitor-frame-ownership.test.ts@@ -28,7 +28,6 @@ const PANEL_SOURCE = readFileSync("utf8",);-const ROOT_SOURCE = readFileSync(fileURLToPath(new URL("../src/app/routes/__root.tsx", import.meta.url)),"utf8",@@ -204,13 +203,40 @@ test("the publish hook drops an unmeasurable box rather than publishing it", ());assert.match(HOOK, /box\.width === 0 && box\.height === 0/);assert.match(HOOK, /observer\?\.disconnect\(\)/, "and it must unsubscribe");- assert.match(HOOK, /clearFrame\(publisher\);\s*\n\s*\};/, "and clear on unmount");+ assert.match(+ HOOK,+ /clearFrame\(publisher\);\s*\n\s*\};/,+ "and clear on unmount",+ );});+test("closed lazy settings surfaces cannot leave load failures on screen", () => {+ const mount = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/settings/settings-dialog-mount.tsx",+ import.meta.url,+ ),+ ),+ "utf8",+ );+ // Keep rejected boundaries mounted for a later retry, but only show their errors while the user is+ // still asking for that surface. A slow rejected chunk must not outlive a quick Open -> Close.+ for (const [open, testId] of [+ ["settingsOpen", "settings-dialog-load-failure"],+ ["monitorOpen", "floating-monitor-load-failure"],+ ]) {+ assert.match(+ mount,+ new RegExp(+ `fallback=\\{\\s*${open}\\s*\\?\\s*\\(\\s*<LazyImportFailure[\\s\\S]*?testId="${testId}"[\\s\\S]*?\\)\\s*:\\s*null\\s*\\}`,+ ),+ );+ }+});-// Once Settings has loaded the monitor, an auth-route round trip must not-// forget that lazy-entry latch. The inner dialog still unmounts on /login so-// its open monitor remains dormant there, then resumes after authentication.+// Once either surface has loaded, an auth-route round trip must not forget its lazy-entry latch.+// Both surfaces stay dormant there, then resume independently after authentication.test("the lazy Settings mount survives an auth-route round trip", () => {assert.match(ROOT_SOURCE,@@ -222,25 +248,35 @@ test("the lazy Settings mount survives an auth-route round trip", () => {);assert.match(SETTINGS_MOUNT_SOURCE,- /if \(!active \|\| !mounted\) return null;/,-+ /if \(!active \|\| !\(settingsMounted \|\| monitorMounted\)\) return null;/,+ );+ assert.match(+ SETTINGS_MOUNT_SOURCE,+ /const \[settingsMounted, setSettingsMounted\] = useState\(settingsOpen\)/,);assert.match(SETTINGS_MOUNT_SOURCE,- /const \[mounted, setMounted\] = useState\(open \|\| monitorOpen\)/,+ /const \[monitorMounted, setMonitorMounted\] = useState\(monitorOpen\)/,);- assert.match(SETTINGS_MOUNT_SOURCE, /dismissLabel=\{t\("common\.close"\)\}/);+ assert.equal(+ (+ SETTINGS_MOUNT_SOURCE.match(/dismissLabel=\{t\("common\.close"\)\}/g) ??+ []+ ).length,+ 2,+ );assert.match(SETTINGS_MOUNT_SOURCE, /data-testid="settings-dialog-loading"/);assert.match(SETTINGS_MOUNT_SOURCE, /dialog\.showModal\(\)/);assert.match(SETTINGS_MOUNT_SOURCE, /tabIndex=\{-1\}/);-assert.match(SETTINGS_MOUNT_SOURCE, /onCancel=\{\(event\) =>/);assert.match(SETTINGS_MOUNT_SOURCE, /event\.target === event\.currentTarget/);- assert.match(SETTINGS_MOUNT_SOURCE, /restoreSettingsOpener\(opener, openerFallback\)/);-assert.match(SETTINGS_MOUNT_SOURCE,- /onDismiss=\{\(\) => \{\s*closeDialog\(\);\s*setMonitorOpen\(false\);/,+ /onDismiss=\{\(\) => \{\s*closeDialog\(\);\s*restoreSettingsOpener\(opener, openerFallback\);/,+ );+ assert.match(+ SETTINGS_MOUNT_SOURCE,+ /onDismiss=\{\(\) => setMonitorOpen\(false\)\}/,);});diff --git a/tests/studio/playwright_settings_tabs.py b/tests/studio/playwright_settings_tabs.pyindex 3e9b13ffee9..4377e287fe3 100644--- a/tests/studio/playwright_settings_tabs.py+++ b/tests/studio/playwright_settings_tabs.py@@ -399,13 +399,74 @@ def run_lan_address_actions(page) -> None:log("each LAN address keeps its own QR and copy target")+def assert_persisted_monitor_restores(page) -> None:+ """An open resource monitor returns after reload without opening Settings."""+ page.evaluate(+ """() => localStorage.setItem(+ 'unsloth_monitor_overlay',+ JSON.stringify({ state: { isOpen: true, isMinimized: false }, version: 0 }),+ )"""+ )+ page.reload(wait_until = "domcontentloaded")+ page.wait_for_function("() => !!window.__settingsSmoke", timeout = 120000)++ monitor = page.locator('[data-testid="floating-monitor"]')+ try:+ monitor.wait_for(state = "visible", timeout = 15000)+ visible = True+ except Exception:+ visible = False+ dialog_count = page.locator('div[role="dialog"]').count()+ report["persisted_monitor"] = {+ "visible_after_reload": visible,+ "settings_dialog_count": dialog_count,+ }+ if not visible:+ fail("persisted open resource monitor did not return after reload")+ elif dialog_count:+ fail("persisted monitor required Settings to open")+ else:+ log("persisted resource monitor restored before Settings opened")++ page.evaluate("() => window.__settingsSmoke.open('resources')")+ dialog = page.locator('div[role="dialog"]').first+ dialog.wait_for(state = "visible", timeout = 15000)+ page.wait_for_function(+ "() => document.querySelectorAll('[data-testid=\"floating-monitor\"]').length === 1",+ timeout = 15000,+ )+ while_open = monitor.count()+ page.evaluate("() => window.__settingsSmoke.close()")+ dialog.wait_for(state = "hidden", timeout = 15000)+ monitor.wait_for(state = "visible", timeout = 15000)+ after_close = monitor.count()+ report["persisted_monitor"].update(+ {+ "count_while_settings_open": while_open,+ "count_after_settings_close": after_close,+ }+ )+ if while_open != 1 or after_close != 1:+ fail(+ "resource monitor ownership did not transfer cleanly through Settings "+ f"(open={while_open}, closed={after_close})"+ )++ page.evaluate("() => window.__settingsSmoke.setMonitor(false)")+ monitor.wait_for(state = "hidden", timeout = 15000)+ report["steps"].append("persisted-monitor-reload")++def run(page) -> None:if CHUNK_FAIL:run_chunk_fail(page)return+# --- 1. a deep-open walked away from mid-load is not replayed later --------------run_abandoned_deep_open(page)+ assert_persisted_monitor_restores(page)+# --- 2. every tab renders when selected -----------------------------------------open_dialog(page)settle_panel(page)diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pyindex 31885c2e69b..9c4842179fb 100644--- a/tests/studio/test_desktop_reliability_frontend_contract.py+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -781,8 +781,9 @@ def test_media_pages_clear_the_custom_titlebar():"""The chat-style layout gives the media pages no outer inset, so each applies its own."""root = ROOT_ROUTE.read_text(encoding = "utf-8")- assert (- "const isChatLike = isChatRoute || isImagesRoute || isVideoRoute || isAudioRoute;" in root+ assert re.search(+ r"const isChatLike =\s*isChatRoute \|\| isImagesRoute \|\| isVideoRoute \|\| isAudioRoute;",+ root,)for page in (IMAGES_PAGE, VIDEO_PAGE):shell = page.read_text(encoding = "utf-8").split('"diffusion-surface', 1)[1].split(">", 1)[0]