Skip to content

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

Studio: load the settings tab panels when they are shown, not at launch (#8966)

Daniel Han2073e0fe4d38
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.yml
index e3fcb8051c4..18ae46382a3 100644
--- a/.github/workflows/studio-frontend-ci.yml
+++ b/.github/workflows/studio-frontend-ci.yml
@@ -21,6 +21,8 @@ on:
- 'tests/studio/playwright_strip_ansi_smoke.py'
- 'tests/studio/playwright_chat_autoscroll.py'
- 'tests/studio/playwright_research_freeze.py'
+ - 'tests/studio/playwright_settings_tabs.py'
+
- 'tests/studio/playwright_stream_pacing.py'
# Shared lifecycle helpers, and the contract test that keeps verdicts from going unread.
- 'tests/studio/_playwright_robust.py'
@@ -187,6 +189,22 @@ jobs:
working-directory: ${{ github.workspace }}
run: python3 tests/studio/playwright_research_freeze.py
+ # The settings panels are fetched on first view, so only a browser can answer whether
+ # every tab renders and deep-opens land (and abandoned ones do not come back).
+ - name: Browser smoke for the settings tab panels
+ working-directory: ${{ github.workspace }}
+ run: python3 tests/studio/playwright_settings_tabs.py
+
+ # A panel that cannot be fetched is new with lazy loading, and nothing above the
+ # root-mounted dialog catches, so unguarded it unmounts Studio, not one panel.
+ - name: Browser smoke for a settings panel that cannot load
+ working-directory: ${{ github.workspace }}
+ env:
+ PW_CHUNK_FAIL: data
+ PW_PORT: '5400'
+ PW_OUT: logs/settings_tabs_blocked_report.json
+ run: python3 tests/studio/playwright_settings_tabs.py
+
# Reports, does not gate, for now. The budgets inside are calibrated on a
# developer machine, and this measures a CPU-bound render on a shared runner
# under 6x throttling, so a budget set from one box is a flake waiting to
diff --git a/studio/frontend/smoke-settings-main.tsx b/studio/frontend/smoke-settings-main.tsx
new file mode 100644
index 00000000000..92a050dbd0d
--- /dev/null
+++ b/studio/frontend/smoke-settings-main.tsx
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Harness for tests/studio/playwright_settings_tabs.py, shaped like smoke-ansi.html: a vite
+// entry with no backend and no auth, driving the real SettingsDialog against the real store.
+
+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 {
+ type SettingsTab,
+ useSettingsDialogStore,
+} from "@/features/settings/stores/settings-dialog-store";
+/* eslint-enable no-restricted-imports */
+import { initializeLocale } from "@/i18n";
+import {
+ RouterProvider,
+ createMemoryHistory,
+ createRootRoute,
+ createRoute,
+ createRouter,
+} from "@tanstack/react-router";
+import { Component, StrictMode, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import "./src/index.css";
+
+declare global {
+ interface Window {
+ // Optional: the app typechecks this entry, but only the harness page installs it.
+ __settingsSmoke?: {
+ open: (tab?: string) => void;
+ openArchived: (shelf: string) => void;
+ close: () => void;
+ setTab: (tab: string) => void;
+ state: () => {
+ open: boolean;
+ activeTab: string;
+ archivedRequested: string | null;
+ };
+ errors: () => string[];
+ };
+ }
+}
+
+const seenErrors: string[] = [];
+window.addEventListener("error", (e) => {
+ seenErrors.push(String(e.message));
+});
+window.addEventListener("unhandledrejection", (e) => {
+ seenErrors.push(String(e.reason));
+});
+
+// The app has no boundary above the dialog, so give the harness one: whether anything
+// reaches it is exactly what is under test.
+class Boundary extends Component<
+ { children: ReactNode },
+ { error: string | null }
+> {
+ state: { error: string | null } = { error: null };
+ static getDerivedStateFromError(error: unknown) {
+ return { error: String(error) };
+ }
+ render() {
+ if (this.state.error) {
+ return <div data-testid="harness-error-boundary">{this.state.error}</div>;
+ }
+ return this.props.children;
+ }
+}
+
+const store = useSettingsDialogStore;
+window.__settingsSmoke = {
+ open: (tab?: string) => {
+ store.getState().openDialog(tab as SettingsTab | undefined);
+ },
+ // 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");
+ },
+ close: () => {
+ store.getState().closeDialog();
+ },
+ setTab: (tab: string) => {
+ store.getState().setActiveTab(tab as SettingsTab);
+ },
+ state: () => {
+ const s = store.getState();
+ return {
+ open: s.open,
+ activeTab: s.activeTab,
+ archivedRequested: s.archivedRequested,
+ };
+ },
+ errors: () => [...seenErrors],
+};
+
+function Harness() {
+ return (
+ <TooltipProvider>
+ <div data-testid="harness-root">
+ <Boundary>
+ <SettingsDialog />
+ </Boundary>
+ </div>
+ </TooltipProvider>
+ );
+}
+
+// Several panels use router hooks (Link, useNavigate), so provide a memory router.
+const harnessRootRoute = createRootRoute({ component: Harness });
+const harnessIndexRoute = createRoute({
+ getParentRoute: () => harnessRootRoute,
+ path: "/",
+ component: () => null,
+});
+const harnessRouter = createRouter({
+ routeTree: harnessRootRoute.addChildren([harnessIndexRoute]),
+ history: createMemoryHistory({ initialEntries: ["/"] }),
+});
+
+const rootElement = document.getElementById("root");
+if (!rootElement) throw new Error("Root element not found");
+const root = createRoot(rootElement);
+const strict = !new URLSearchParams(window.location.search).has("nostrict");
+
+function render(): void {
+ const tree = <RouterProvider router={harnessRouter} />;
+ root.render(strict ? <StrictMode>{tree}</StrictMode> : tree);
+}
+
+const localeInitialization = initializeLocale();
+if (typeof localeInitialization !== "string") {
+ void localeInitialization.then(render);
+} else {
+ render();
+}
diff --git a/studio/frontend/smoke-settings.html b/studio/frontend/smoke-settings.html
new file mode 100644
index 00000000000..3ec690fdd0b
--- /dev/null
+++ b/studio/frontend/smoke-settings.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <script src="/crypto-boot.js"></script>
+ <title>settings dialog smoke</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/smoke-settings-main.tsx"></script>
+ </body>
+</html>
diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsx
index a7b902f742c..dedd4568712 100644
--- a/studio/frontend/src/features/settings/settings-dialog.tsx
+++ b/studio/frontend/src/features/settings/settings-dialog.tsx
@@ -3,6 +3,7 @@
import { FloatingMonitor } from "@/components/floating-monitor";
import { getClientPlatform } from "@/components/tauri/window-titlebar";
+import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
@@ -13,6 +14,7 @@ import { type TranslationKey, useT } from "@/i18n";
import { isTauri } from "@/lib/api-base";
import { MicIcon } from "@/lib/mic-icon";
import { cn } from "@/lib/utils";
+import { scheduleIdleTask } from "@/lib/schedule-idle-task";
import {
BotIcon,
Cancel01Icon,
@@ -31,7 +33,12 @@ import {
import { HugeiconsIcon } from "@hugeicons/react";
import { motion, useReducedMotion } from "motion/react";
import {
+ Component,
+ type ComponentType,
type FC,
+ type ReactNode,
+ Suspense,
+ lazy,
useDeferredValue,
useEffect,
useMemo,
@@ -46,18 +53,96 @@ import {
type SettingsTab,
useSettingsDialogStore,
} from "./stores/settings-dialog-store";
-import { AboutTab } from "./tabs/about-tab";
-import { AgentsTab } from "./tabs/agents-tab";
-import { ApiKeysTab } from "./tabs/api-keys-tab";
-import { AppearanceTab } from "./tabs/appearance-tab";
-import { ChatTab } from "./tabs/chat-tab";
-import { ConnectionsTab } from "./tabs/connections-tab";
-import { DataTab } from "./tabs/data-tab";
-import { DebuggingTab } from "./tabs/debugging-tab";
-import { GeneralTab } from "./tabs/general-tab";
-import { ProfileTab } from "./tabs/profile-tab";
-import { ResourcesTab } from "./tabs/resources-tab";
-import { VoiceTab } from "./tabs/voice-tab";
+// Statically imported, all twelve panels 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 })),
+ 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 })),
+ connections: () =>
+ import("./tabs/connections-tab").then((m) => ({ default: m.ConnectionsTab })),
+ data: () => import("./tabs/data-tab").then((m) => ({ default: m.DataTab })),
+ "api-keys": () => import("./tabs/api-keys-tab").then((m) => ({ default: m.ApiKeysTab })),
+ 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 })),
+} satisfies Record<SettingsTab, () => Promise<{ default: FC }>>;
+
+function lazyTabs<T extends Record<string, () => Promise<{ default: FC }>>>(
+ loaders: T,
+): Record<keyof T, ComponentType> {
+ const out = {} as Record<keyof T, ComponentType>;
+ for (const id of Object.keys(loaders) as (keyof T)[]) {
+ out[id] = lazy(loaders[id]);
+ }
+ return out;
+}
+
+const LAZY_TABS = lazyTabs(TAB_LOADERS);
+
+interface PanelBoundaryProps {
+ tab: SettingsTab;
+ message: string;
+ reloadLabel: string;
+ children: ReactNode;
+}
+
+interface PanelBoundaryState {
+ tab: SettingsTab;
+ failed: boolean;
+}
+
+/**
+ * A panel fetch can fail (offline, or an entry bundle naming chunks a `dist/` rewrite
+ * replaced). Nothing above this root-mounted dialog catches, so unguarded that unmounts
+ * all of Studio rather than one panel.
+ *
+ * Reload rather than retry: React and the browser's module map both cache the failed
+ * import, so re-importing rethrows with no new request (whatwg/html#6768), while
+ * index.html is no-store and a reload does pick up the current chunk names.
+ */
+class SettingsPanelBoundary extends Component<
+ PanelBoundaryProps,
+ PanelBoundaryState
+> {
+ state: PanelBoundaryState = { tab: this.props.tab, failed: false };
+
+ static getDerivedStateFromError(): Partial<PanelBoundaryState> {
+ return { failed: true };
+ }
+
+ // A different tab is a different chunk, so one panel's failure must not hold the rest.
+ static getDerivedStateFromProps(
+ props: PanelBoundaryProps,
+ state: PanelBoundaryState,
+ ): Partial<PanelBoundaryState> | null {
+ return props.tab === state.tab ? null : { tab: props.tab, failed: false };
+ }
+
+ render() {
+ 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>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ window.location.reload();
+ }}
+ >
+ {this.props.reloadLabel}
+ </Button>
+ </div>
+ );
+ }
+}
interface TabDef {
id: SettingsTab;
@@ -138,32 +223,8 @@ const SETTINGS_SEARCH_INDEX = createSettingsSearchIndex({
});
function renderTab(tab: SettingsTab) {
- switch (tab) {
- case "general":
- return <GeneralTab />;
- case "profile":
- return <ProfileTab />;
- case "appearance":
- return <AppearanceTab />;
- case "resources":
- return <ResourcesTab />;
- case "chat":
- return <ChatTab />;
- case "voice":
- return <VoiceTab />;
- case "connections":
- return <ConnectionsTab />;
- case "data":
- return <DataTab />;
- case "api-keys":
- return <ApiKeysTab />;
- case "agents":
- return <AgentsTab />;
- case "debugging":
- return <DebuggingTab />;
- case "about":
- return <AboutTab />;
- }
+ const Tab = LAZY_TABS[tab];
+ return <Tab />;
}
export function SettingsDialog() {
@@ -180,6 +241,19 @@ export function SettingsDialog() {
const panelTab = useDeferredValue(activeTab);
const [query, setQuery] = useState("");
+ // 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;
+ return scheduleIdleTask(() => {
+ for (const load of Object.values(TAB_LOADERS)) {
+ // Warming a panel nobody asked for must not surface as an unhandled rejection;
+ // the boundary above speaks for the panel the user does open.
+ void load().catch(() => undefined);
+ }
+ });
+ }, [open]);
+
const results = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return null;
@@ -484,7 +558,23 @@ export function SettingsDialog() {
ref={mainScrollRef}
className="hover-scrollbar flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto p-6 [scrollbar-gutter:stable]"
>
- {renderTab(panelTab)}
+ {/* Only a panel's first view waits, so the fallback is delayed and a
+ promptly arriving panel never flashes it. */}
+ <SettingsPanelBoundary
+ tab={panelTab}
+ message={t("settings.dialog.panelFailed")}
+ reloadLabel={t("settings.dialog.panelReload")}
+ >
+ <Suspense
+ fallback={
+ <div className="fade-in fill-mode-both flex flex-1 animate-in items-center justify-center text-muted-foreground text-sm delay-300 duration-150">
+ {t("common.loading")}
+ </div>
+ }
+ >
+ {renderTab(panelTab)}
+ </Suspense>
+ </SettingsPanelBoundary>
</div>
</main>
</div>
diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
index a17b83da6cd..7a383cad7e6 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -36,7 +36,8 @@ interface SettingsDialogState {
// explicitly via onCloseAutoFocus.
opener: HTMLElement | null;
// Set when something asks to jump straight to an archive listing (the archive
- // toast). DataTab uses it as its initial subpage, then clears it.
+ // toast). DataTab uses it as its initial subpage, then clears it. See requestsFor
+ // for how long it lives unconsumed.
archivedRequested: ArchivedShelf | null;
openDialog: (tab?: SettingsTab, options?: OpenDialogOptions) => void;
openArchivedChats: () => void;
@@ -84,6 +85,31 @@ function loadInitialTab(): SettingsTab {
: "general";
}
+/** The panel that delivers each scroll target, so a navigation elsewhere abandons it. */
+const SCROLL_TARGET_TAB: Record<SettingsScrollTarget, SettingsTab> = {
+ "about-updates": "about",
+ "appearance-sidebar-nav": "appearance",
+};
+
+/**
+ * The unconsumed deep-link requests that outlive a navigation landing on `tab`.
+ *
+ * Only the panel that performs a jump clears its request, and panels are fetched on first
+ * view, so a navigation can move before the chunk arrives. A request therefore lives while
+ * the dialog is open on the tab that reads it: reselecting keeps it, anything else drops
+ * it, and closing (below) always does. Held wider, a stale request replays on a later
+ * visit; held narrower, reselecting loses a deep-link still in flight.
+ */
+function requestsFor(state: SettingsDialogState, tab: SettingsTab) {
+ return {
+ scrollTarget:
+ state.scrollTarget && SCROLL_TARGET_TAB[state.scrollTarget] === tab
+ ? state.scrollTarget
+ : null,
+ archivedRequested: tab === "data" ? state.archivedRequested : null,
+ };
+}
+
export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
open: false,
activeTab: loadInitialTab(),
@@ -91,12 +117,18 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
opener: null,
archivedRequested: null,
openDialog: (tab, options) =>
- set((state) => ({
- open: true,
- activeTab: tab ?? state.activeTab,
- scrollTarget: options?.scrollTarget ?? null,
- opener: captureOpener(),
- })),
+ set((state) => {
+ const next = tab ?? state.activeTab;
+ const pending = requestsFor(state, next);
+ return {
+ open: true,
+ activeTab: next,
+ // A caller that names a target replaces whatever was still pending.
+ scrollTarget: options?.scrollTarget ?? pending.scrollTarget,
+ archivedRequested: pending.archivedRequested,
+ opener: captureOpener(),
+ };
+ }),
openArchivedChats: () =>
set({
open: true,
@@ -121,13 +153,14 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
// Do NOT clear `opener` here. onCloseAutoFocus runs on the next render
// pass after `open: false` lands, so the opener must still be readable
// from the store at that point. The next openDialog() overwrites it.
- closeDialog: () => set({ open: false, scrollTarget: null }),
+ closeDialog: () =>
+ set({ open: false, scrollTarget: null, archivedRequested: null }),
setActiveTab: (tab) => {
try {
window.localStorage.setItem(ACTIVE_TAB_KEY, tab);
} catch {
// ignore storage failures
}
- set({ activeTab: tab, scrollTarget: null });
+ set((state) => ({ activeTab: tab, ...requestsFor(state, tab) }));
},
}));
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 73d7eb3345b..a6f3e8ea4f7 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -182,6 +182,8 @@ export const ar = {
closeAriaLabel: "إغلاق الإعدادات",
searchPlaceholder: "ابحث في الإعدادات…",
searchNoResults: "لم يُعثر على أي إعداد.",
+ panelFailed: "تعذر تحميل هذا القسم.",
+ panelReload: "إعادة التحميل",
},
tabs: {
general: "عام",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index e1363138e01..1cbfba4e32e 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -186,6 +186,8 @@ export const de = {
closeAriaLabel: "Einstellungen schließen",
searchPlaceholder: "Einstellungen durchsuchen…",
searchNoResults: "Keine Einstellungen gefunden.",
+ panelFailed: "Dieser Bereich konnte nicht geladen werden.",
+ panelReload: "Neu laden",
},
tabs: {
general: "Allgemein",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index aca2b8714d4..f198362f45d 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -182,6 +182,8 @@ export const en = {
closeAriaLabel: "Close settings",
searchPlaceholder: "Search settings…",
searchNoResults: "No settings found.",
+ panelFailed: "This section could not be loaded.",
+ panelReload: "Reload",
},
tabs: {
general: "General",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 7a4cba1e32d..cf90bf4da6c 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -185,6 +185,8 @@ export const es = {
closeAriaLabel: "Cerrar configuración",
searchPlaceholder: "Buscar en la configuración…",
searchNoResults: "No se encontró ninguna opción.",
+ panelFailed: "No se pudo cargar esta sección.",
+ panelReload: "Recargar",
},
tabs: {
general: "General",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index ff3208f1c59..e493acb98a4 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -186,6 +186,8 @@ export const fr = {
closeAriaLabel: "Fermer les paramètres",
searchPlaceholder: "Rechercher dans les paramètres…",
searchNoResults: "Aucun paramètre trouvé.",
+ panelFailed: "Cette section n'a pas pu être chargée.",
+ panelReload: "Recharger",
},
tabs: {
general: "Général",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 84b2f7ae8b4..ad40d05d250 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -185,6 +185,8 @@ export const hi = {
closeAriaLabel: "सेटिंग्स बंद करें",
searchPlaceholder: "सेटिंग्स खोजें…",
searchNoResults: "कोई सेटिंग नहीं मिली।",
+ panelFailed: "यह अनुभाग लोड नहीं हो सका।",
+ panelReload: "फिर से लोड करें",
},
tabs: {
general: "सामान्य",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 7527da45d9a..28fe34bc626 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -150,6 +150,8 @@ export const it = {
closeAriaLabel: "Chiudi le impostazioni",
searchPlaceholder: "Cerca nelle impostazioni…",
searchNoResults: "Nessuna impostazione trovata.",
+ panelFailed: "Non è stato possibile caricare questa sezione.",
+ panelReload: "Ricarica",
},
tabs: {
general: "Generali",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 1fbb7e86d27..59755ed8b3a 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -184,6 +184,8 @@ export const ja = {
closeAriaLabel: "設定を閉じる",
searchPlaceholder: "設定を検索…",
searchNoResults: "設定が見つかりません。",
+ panelFailed: "このセクションを読み込めませんでした。",
+ panelReload: "再読み込み",
},
tabs: {
general: "一般",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 9ec599111f1..d6c743e4379 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -182,6 +182,8 @@ export const ko = {
closeAriaLabel: "설정 닫기",
searchPlaceholder: "설정 검색…",
searchNoResults: "설정을 찾을 수 없습니다.",
+ panelFailed: "이 섹션을 불러오지 못했습니다.",
+ panelReload: "새로고침",
},
tabs: {
general: "일반",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 3646d5bc83d..dd884c34076 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -184,6 +184,8 @@ export const ptBR = {
closeAriaLabel: "Fechar configurações",
searchPlaceholder: "Pesquisar configurações…",
searchNoResults: "Nenhuma configuração encontrada.",
+ panelFailed: "Não foi possível carregar esta seção.",
+ panelReload: "Recarregar",
},
tabs: {
general: "Geral",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index ce5dff1c456..ed320d9dd72 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -184,6 +184,8 @@ export const ru = {
closeAriaLabel: "Закрыть настройки",
searchPlaceholder: "Поиск по настройкам…",
searchNoResults: "Настройки не найдены.",
+ panelFailed: "Не удалось загрузить этот раздел.",
+ panelReload: "Перезагрузить",
},
tabs: {
general: "Общие",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index b4a094696e8..be672f30fc1 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -180,6 +180,8 @@ export const zhCN = {
closeAriaLabel: "关闭设置",
searchPlaceholder: "搜索设置…",
searchNoResults: "未找到设置。",
+ panelFailed: "无法加载此部分。",
+ panelReload: "重新加载",
},
tabs: {
general: "通用",
diff --git a/studio/frontend/tests/settings-deep-open-requests.test.ts b/studio/frontend/tests/settings-deep-open-requests.test.ts
new file mode 100644
index 00000000000..a32a35812f0
--- /dev/null
+++ b/studio/frontend/tests/settings-deep-open-requests.test.ts
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// `archivedRequested` and `scrollTarget` are one-shot deep-link requests, cleared only by
+// the panel that performs the jump. Panels load on first view, so a navigation can move
+// before the chunk arrives: clearing too widely loses a deep-link still being served,
+// too narrowly replays a stale one. Both live while the dialog is open on their tab.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { useSettingsDialogStore } from "../src/features/settings/stores/settings-dialog-store.ts";
+
+const store = useSettingsDialogStore;
+
+function reset(): void {
+ store.setState({
+ open: false,
+ activeTab: "general",
+ scrollTarget: null,
+ opener: null,
+ archivedRequested: null,
+ });
+}
+
+test("an archive deep-open survives until the panel it targets can read it", () => {
+ reset();
+ store.getState().openArchivedChats();
+ assert.equal(store.getState().open, true);
+ assert.equal(store.getState().activeTab, "data");
+ assert.equal(store.getState().archivedRequested, "chats");
+});
+
+test("closing the dialog drops a deep-open the panel never reached", () => {
+ reset();
+ store.getState().openArchivedChats();
+ store.getState().closeDialog();
+ assert.equal(store.getState().archivedRequested, null);
+});
+
+test("leaving Data drops a deep-open the panel never reached", () => {
+ reset();
+ store.getState().openArchivedMedia("images");
+ store.getState().setActiveTab("about");
+ assert.equal(store.getState().archivedRequested, null);
+});
+
+test("an ordinary open does not inherit an abandoned deep-open", () => {
+ reset();
+ store.getState().openArchivedMedia("videos");
+ store.getState().openDialog("voice");
+ assert.equal(store.getState().archivedRequested, null);
+});
+
+test("reselecting Data navigates nowhere, so the deep-open still stands", () => {
+ // The nav button fires on the active tab too, and the panel is still on the wire.
+ reset();
+ store.getState().openArchivedChats();
+ store.getState().setActiveTab("data");
+ assert.equal(store.getState().archivedRequested, "chats");
+});
+
+test("reopening on Data does not drop a deep-open still in flight", () => {
+ reset();
+ store.getState().openArchivedMedia("images");
+ store.getState().openDialog();
+ assert.equal(store.getState().archivedRequested, "images");
+ store.getState().openDialog("data");
+ assert.equal(store.getState().archivedRequested, "images");
+});
+
+test("consuming it clears it, so a later visit to Data is an ordinary one", () => {
+ reset();
+ store.getState().openArchivedChats();
+ store.getState().consumeArchivedChatsRequest();
+ assert.equal(store.getState().archivedRequested, null);
+});
+
+test("a scroll target survives until the panel it targets can read it", () => {
+ reset();
+ store.getState().openDialog("about", { scrollTarget: "about-updates" });
+ assert.equal(store.getState().activeTab, "about");
+ assert.equal(store.getState().scrollTarget, "about-updates");
+});
+
+test("reselecting the target's own tab keeps the scroll target", () => {
+ reset();
+ store.getState().openDialog("about", { scrollTarget: "about-updates" });
+ store.getState().setActiveTab("about");
+ assert.equal(store.getState().scrollTarget, "about-updates");
+ store.getState().openDialog();
+ assert.equal(store.getState().scrollTarget, "about-updates");
+});
+
+test("leaving the target's tab, or closing, drops the scroll target", () => {
+ reset();
+ store
+ .getState()
+ .openDialog("appearance", { scrollTarget: "appearance-sidebar-nav" });
+ store.getState().setActiveTab("about");
+ assert.equal(store.getState().scrollTarget, null);
+
+ reset();
+ store
+ .getState()
+ .openDialog("appearance", { scrollTarget: "appearance-sidebar-nav" });
+ store.getState().closeDialog();
+ assert.equal(store.getState().scrollTarget, null);
+});
+
+test("an open that names its own target replaces one still pending", () => {
+ reset();
+ store.getState().openDialog("about", { scrollTarget: "about-updates" });
+ store
+ .getState()
+ .openDialog("appearance", { scrollTarget: "appearance-sidebar-nav" });
+ assert.equal(store.getState().scrollTarget, "appearance-sidebar-nav");
+});
+
+test("consuming a scroll target clears it", () => {
+ reset();
+ store.getState().openDialog("about", { scrollTarget: "about-updates" });
+ store.getState().consumeScrollTarget("about-updates");
+ assert.equal(store.getState().scrollTarget, null);
+});
diff --git a/studio/frontend/tests/settings-tab-panel-loading.test.ts b/studio/frontend/tests/settings-tab-panel-loading.test.ts
new file mode 100644
index 00000000000..e6151391a9d
--- /dev/null
+++ b/studio/frontend/tests/settings-tab-panel-loading.test.ts
@@ -0,0 +1,176 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * The dialog is closed for the whole launch, yet its twelve tab panels were static imports
+ * and so ran before first paint. One static `./tabs/...` edge from anywhere reachable at
+ * startup puts them all back, so these assert the import graph, not rendered output.
+ */
+
+import assert from "node:assert/strict";
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import ts from "typescript";
+
+const SRC = fileURLToPath(new URL("../src", import.meta.url));
+const SETTINGS = path.join(SRC, "features/settings");
+const DIALOG = path.join(SETTINGS, "settings-dialog.tsx");
+const TABS_DIR = path.join(SETTINGS, "tabs");
+
+async function* walk(dir: string): AsyncGenerator<string> {
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) yield* walk(full);
+ else if (/\.tsx?$/.test(entry.name)) yield full;
+ }
+}
+
+/**
+ * Module specifiers of `import`/`export ... from` declarations, parsed rather than grepped:
+ * a deferred `import(...)` is a call expression, so it is never collected.
+ */
+const staticSpecifiers = (file: string, text: string): string[] => {
+ const parsed = ts.createSourceFile(
+ file,
+ text,
+ ts.ScriptTarget.ESNext,
+ false,
+ file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
+ );
+ const specifiers: string[] = [];
+ const visit = (node: ts.Node): void => {
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
+ const specifier = node.moduleSpecifier;
+ if (specifier && ts.isStringLiteral(specifier)) {
+ specifiers.push(specifier.text);
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ ts.forEachChild(parsed, visit);
+ return specifiers;
+};
+
+/** A tab panel, however the importer spelled the path. */
+const isTabPanel = (specifier: string): boolean =>
+ /(^|\/)tabs\/[\w-]+-tab$/.test(specifier);
+
+test("the dialog loads every tab panel on demand", async () => {
+ const source = await readFile(DIALOG, "utf8");
+
+ const statics = staticSpecifiers(DIALOG, source).filter(isTabPanel);
+ assert.deepEqual(statics, [], `settings-dialog still statically imports: ${statics}`);
+
+ // One loader per panel on disk, so a tab added later cannot go missing from the map.
+ const panels = (await readdir(TABS_DIR)).filter((f) => /-tab\.tsx$/.test(f));
+ assert.ok(panels.length >= 12, `only found ${panels.length} tab panels`);
+ for (const file of panels) {
+ const specifier = `./tabs/${file.replace(/\.tsx$/, "")}`;
+ assert.ok(
+ source.includes(`import("${specifier}")`),
+ `no deferred import for ${specifier}`,
+ );
+ }
+});
+
+test("nothing else in src statically imports a tab panel", async () => {
+ const offenders: string[] = [];
+ for await (const file of walk(SRC)) {
+ if (file.startsWith(TABS_DIR)) {
+ // A panel importing a sibling is its own business; it is already lazy.
+ continue;
+ }
+ const text = await readFile(file, "utf8");
+ for (const specifier of staticSpecifiers(file, text)) {
+ if (isTabPanel(specifier)) {
+ offenders.push(`${path.relative(SRC, file)}: ${specifier}`);
+ }
+ }
+ }
+ assert.deepEqual(
+ offenders,
+ [],
+ `settings tab panels are back on the startup path via:\n${offenders.join("\n")}`,
+ );
+});
+
+test("a panel that fails to load cannot take the app down with it", async () => {
+ // Nothing above the root-mounted dialog catches, so an uncaught render throw unmounts
+ // the whole tree, not one panel.
+ const source = await readFile(DIALOG, "utf8");
+ const parsed = ts.createSourceFile(
+ DIALOG,
+ source,
+ ts.ScriptTarget.ESNext,
+ // Parent pointers: the assertion is about which element encloses which.
+ true,
+ ts.ScriptKind.TSX,
+ );
+
+ const boundaries = new Set<string>();
+ const collect = (node: ts.Node): void => {
+ if (ts.isClassDeclaration(node) && node.name) {
+ const catches = node.members.some(
+ (member) =>
+ (ts.isMethodDeclaration(member) || ts.isPropertyDeclaration(member)) &&
+ member.name !== undefined &&
+ ts.isIdentifier(member.name) &&
+ (member.name.text === "getDerivedStateFromError" ||
+ member.name.text === "componentDidCatch"),
+ );
+ if (catches) boundaries.add(node.name.text);
+ }
+ ts.forEachChild(node, collect);
+ };
+ ts.forEachChild(parsed, collect);
+ assert.ok(
+ boundaries.size > 0,
+ "settings-dialog defines no error boundary for the lazy panels",
+ );
+
+ const tagName = (node: ts.Node): string | null => {
+ if (ts.isJsxElement(node)) return node.openingElement.tagName.getText(parsed);
+ if (ts.isJsxSelfClosingElement(node)) return node.tagName.getText(parsed);
+ return null;
+ };
+
+ let guarded = 0;
+ let total = 0;
+ const check = (node: ts.Node): void => {
+ if (tagName(node) === "Suspense") {
+ total += 1;
+ for (
+ let parent: ts.Node | undefined = node.parent;
+ parent;
+ parent = parent.parent
+ ) {
+ const name = tagName(parent);
+ if (name && boundaries.has(name)) {
+ guarded += 1;
+ break;
+ }
+ }
+ }
+ ts.forEachChild(node, check);
+ };
+ ts.forEachChild(parsed, check);
+ assert.ok(total > 0, "settings-dialog has no Suspense boundary around the panels");
+ assert.equal(
+ guarded,
+ total,
+ `${total - guarded} of ${total} panel Suspense boundaries are not inside ` +
+ `one of ${[...boundaries].join(", ")}`,
+ );
+});
+
+test("the panels are prefetched once the dialog opens", async () => {
+ // Without this the first tab click trades the startup cost for an interaction one.
+ const source = await readFile(DIALOG, "utf8");
+ assert.match(source, /scheduleIdleTask/);
+ assert.match(source, /Object\.values\(TAB_LOADERS\)/);
+ // It warms unselected panels, so a failed chunk must not reach the page as a rejection.
+ assert.match(source, /load\(\)\.catch\(/);
+});
diff --git a/studio/frontend/tsconfig.app.json b/studio/frontend/tsconfig.app.json
index 8e7ff07fd60..7bec599ac3b 100644
--- a/studio/frontend/tsconfig.app.json
+++ b/studio/frontend/tsconfig.app.json
@@ -33,6 +33,7 @@
"smoke-ansi-main.tsx",
"smoke-autoscroll-main.tsx",
"smoke-research-main.tsx",
+ "smoke-settings-main.tsx",
"smoke-stream-pacing-main.tsx"
]
}
diff --git a/tests/studio/playwright_settings_tabs.py b/tests/studio/playwright_settings_tabs.py
new file mode 100644
index 00000000000..7da57cb769f
--- /dev/null
+++ b/tests/studio/playwright_settings_tabs.py
@@ -0,0 +1,516 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Settings dialog behaviour harness: every tab renders, search jumps land, deep-open works.
+
+Drives smoke-settings.html (the real SettingsDialog and store, no backend), so a static-import
+tree and a React.lazy one are directly comparable. Emits a JSON report to $PW_OUT for a
+field-by-field diff.
+
+ PW_ENGINE=chromium PW_PORT=5399 PW_OUT=out.json python tests/studio/playwright_settings_tabs.py
+
+PW_CHUNK_DELAY_MS delays every tab module response, widening the window a lazy panel is
+in-flight for; PW_CHUNK_FAIL=<tab> aborts one tab's module outright.
+"""
+
+import json
+import os
+import re
+import sys
+import time
+from pathlib import Path
+
+from playwright.sync_api import sync_playwright
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _playwright_robust import ( # noqa: E402
+ chromium_launch_args,
+ start_vite,
+ stop_process,
+)
+
+TABS = [
+ "general",
+ "profile",
+ "appearance",
+ "resources",
+ "chat",
+ "voice",
+ "connections",
+ "data",
+ "api-keys",
+ "agents",
+ "debugging",
+ "about",
+]
+
+ENGINE = os.environ.get("PW_ENGINE", "chromium")
+PORT = int(os.environ.get("PW_PORT", "5399"))
+OUT = Path(os.environ.get("PW_OUT", "logs/settings_tabs_report.json"))
+CHUNK_DELAY_MS = int(os.environ.get("PW_CHUNK_DELAY_MS", "0"))
+CHUNK_FAIL = os.environ.get("PW_CHUNK_FAIL", "")
+SETTLE_MS = 600
+SETTLE_TIMEOUT_S = 25.0
+# The panel scroller inside the dialog, the element `mainScrollRef` points at.
+PANEL = 'div[role="dialog"] main div.hover-scrollbar'
+# How long the Data module is held, and how far into that hold the deep-open is abandoned.
+DEEP_OPEN_HOLD_MS = 2500
+DEEP_OPEN_ABANDON_MS = 300
+# The Data panel's own module, however the server spells it (vite appends ?t=, ?v=).
+DATA_MODULE = re.compile(r"/data-tab(\.tsx)?(\?|$)")
+
+report: dict = {
+ "engine": ENGINE,
+ "chunk_delay_ms": CHUNK_DELAY_MS,
+ "chunk_fail": CHUNK_FAIL,
+ "steps": [],
+ "tabs": {},
+ "failures": [],
+}
+
+
+def log(msg: str) -> None:
+ print(f"[settings-tabs] {msg}", flush = True)
+
+
+def fail(msg: str) -> None:
+ log(f"FAIL {msg}")
+ report["failures"].append(msg)
+
+
+SNAPSHOT_JS = """(sel) => {
+ const root = document.querySelector(sel);
+ if (!root) return { present: false, sig: 'none' };
+ const labels = [...root.querySelectorAll('[data-settings-label]')]
+ .map((el) => el.dataset.settingsLabel);
+ const text = (root.innerText || '').trim();
+ return {
+ present: true,
+ labels,
+ elements: root.querySelectorAll('*').length,
+ textLength: text.length,
+ // Identity of what is on screen, insensitive to live values (versions, sizes).
+ sig: labels.join('|') + '#' + root.querySelectorAll('*').length,
+ };
+}"""
+
+
+def snapshot(page) -> dict:
+ return page.evaluate(SNAPSHOT_JS, PANEL)
+
+
+def settle(page, timeout_s: float = SETTLE_TIMEOUT_S) -> dict:
+ """Poll until the panel signature holds still for SETTLE_MS, then return it."""
+ deadline = time.time() + timeout_s
+ last = snapshot(page)
+ stable_since = time.time()
+ while time.time() < deadline:
+ page.wait_for_timeout(50)
+ now = snapshot(page)
+ if now.get("sig") != last.get("sig"):
+ last = now
+ stable_since = time.time()
+ continue
+ if (time.time() - stable_since) * 1000 >= SETTLE_MS:
+ return now
+ last["settle_timeout"] = True
+ return last
+
+
+def settle_panel(page, timeout_s: float = SETTLE_TIMEOUT_S) -> dict:
+ """Settle, but do not accept a placeholder as the answer.
+
+ The panel renders from a deferred value, so the outgoing content stays on screen until
+ the incoming one is ready, and under load that hand-off can hold still past SETTLE_MS.
+ """
+ deadline = time.time() + timeout_s
+ latest = settle(page, timeout_s = timeout_s)
+ while latest.get("elements", 0) < 5 and time.time() < deadline:
+ page.wait_for_timeout(100)
+ latest = settle(page, timeout_s = max(1.0, deadline - time.time()))
+ return latest
+
+
+def click_tab_and_observe(page, tab: str) -> dict:
+ """Click a tab; record how long the panel keeps the old content and whether it blanks."""
+ before = snapshot(page)
+ page.locator(f'[data-testid="settings-tab-{tab}"]').click(force = True, timeout = 15000)
+ started = time.time()
+ changed_ms = None
+ blank_frames = 0
+ frames = 0
+ deadline = started + SETTLE_TIMEOUT_S
+ while time.time() < deadline:
+ now = snapshot(page)
+ frames += 1
+ if now.get("present") and now.get("elements", 0) < 5:
+ blank_frames += 1
+ if changed_ms is None and now.get("sig") != before.get("sig"):
+ changed_ms = round((time.time() - started) * 1000)
+ break
+ page.wait_for_timeout(20)
+ final = settle_panel(page)
+ return {
+ "before_sig": before.get("sig"),
+ "changed_ms": changed_ms,
+ "blank_frames": blank_frames,
+ "frames_sampled": frames,
+ "settled": final,
+ }
+
+
+def require_harness(page) -> None:
+ """Fail with the cause rather than a selector timeout if the page has moved on.
+
+ Vite dev proxies /api to 127.0.0.1:8888. With a real Studio listening there and no
+ token, those calls come back 401 and the app's auth handling navigates, which takes
+ the harness's window with it. Every later step then times out on a dialog that cannot
+ exist. This is not the dialog's doing: it happens on main too, where the harness is
+ unmounted before the first open. So say so.
+ """
+ if not page.evaluate("() => !!window.__settingsSmoke"):
+ raise RuntimeError(
+ "the harness page is gone (window.__settingsSmoke undefined). This smoke page "
+ f"is served by vite on {PORT} and proxies /api to 127.0.0.1:8888; a Studio "
+ "listening there answers 401 and the app navigates away. Run this without a "
+ "backend on 8888."
+ )
+
+
+def open_dialog(page, tab: str | None = None) -> None:
+ require_harness(page)
+ page.evaluate("(t) => window.__settingsSmoke.open(t || undefined)", tab)
+ page.wait_for_selector('div[role="dialog"]', timeout = 15000)
+
+
+# Only subpages put a back button in the panel header, so this is locale-independent.
+ON_SUBPAGE_JS = """() => ({
+ subpage: !!document.querySelector('div[role="dialog"] main header button'),
+ elements: (document.querySelector('div[role="dialog"] main div.hover-scrollbar')
+ || { querySelectorAll: () => [] }).querySelectorAll('*').length,
+})"""
+
+# Deep-open the archived chats, then walk away partway through the hold. Both halves run in
+# the page, because a route handler that sleeps blocks this script too.
+ABANDON_DEEP_OPEN_JS = """(delay) => {
+ window.__abandonedAt = null;
+ window.__settingsSmoke.openArchived('chats');
+ setTimeout(() => {
+ const panel = document.querySelector('div[role="dialog"] main div.hover-scrollbar');
+ window.__abandonedAt = {
+ elements: panel ? panel.querySelectorAll('*').length : null,
+ subpage: !!document.querySelector('div[role="dialog"] main header button'),
+ };
+ window.__settingsSmoke.close();
+ }, delay);
+}"""
+
+
+def run_abandoned_deep_open(page) -> None:
+ """A deep-open the panel never mounted for must not outlive the navigation.
+
+ `openArchivedChats` sets `archivedRequested`, and DataTab is the only thing that clears
+ it. Now that the panel is fetched on first view, closing the dialog while that fetch is
+ in flight leaves the request set with nothing to consume it, and the next ordinary visit
+ to Data opens an archive listing nobody asked for. Runs before anything else opens the
+ dialog, so the Data module is still cold and the hold is what decides when it arrives.
+ """
+
+ # Matched on the Data module alone rather than on everything. The sleep below runs on
+ # the driver thread, so a handler that sees every request makes the whole page's module
+ # load queue behind it, and the panel that arrives next has to be rendered by a main
+ # thread that got the lot at once. On a busy two-core runner that pushed the reopen
+ # below past its timeout even though nothing was wrong with the dialog.
+ def hold_data(route):
+ time.sleep(DEEP_OPEN_HOLD_MS / 1000)
+ return route.continue_()
+
+ page.route(DATA_MODULE, hold_data)
+ try:
+ page.evaluate(ABANDON_DEEP_OPEN_JS, DEEP_OPEN_ABANDON_MS)
+ page.wait_for_timeout(DEEP_OPEN_HOLD_MS + 1500)
+ finally:
+ page.unroute(DATA_MODULE, hold_data)
+ abandoned = page.evaluate("() => window.__abandonedAt")
+ open_dialog(page, "data")
+ settled = settle_panel(page)
+ landed = page.evaluate(ON_SUBPAGE_JS)
+ report["abandoned_deep_open"] = {
+ "abandoned_at": abandoned,
+ "landed": landed,
+ "state": page.evaluate("() => window.__settingsSmoke.state()"),
+ "settled_sig": settled.get("sig"),
+ }
+ log(f"abandoned deep-open: at close {abandoned}, later visit {landed}")
+ if not abandoned or abandoned.get("subpage"):
+ fail(f"deep-open abandon never happened mid-load, so nothing was tested ({abandoned})")
+ elif landed["elements"] < 5:
+ fail(f"after an abandoned deep-open, Data did not render at all ({landed})")
+ elif landed["subpage"]:
+ fail("an abandoned archive deep-open reopened the archive on the next visit to Data")
+ else:
+ log("an abandoned deep-open leaves the next visit to Data on the main page")
+ page.evaluate("() => window.__settingsSmoke.close()")
+ page.wait_for_timeout(200)
+
+ # Dropping the abandoned ones must not drop the honoured ones.
+ page.evaluate("() => window.__settingsSmoke.openArchived('chats')")
+ page.wait_for_selector('div[role="dialog"]', timeout = 15000)
+ settle_panel(page)
+ honoured = page.evaluate(ON_SUBPAGE_JS)
+ report["abandoned_deep_open"]["honoured"] = honoured
+ if not honoured["subpage"]:
+ fail(f"a deep-open the panel did reach no longer opens the archive ({honoured})")
+ else:
+ log("a deep-open the panel reaches still opens the archive")
+ page.evaluate("() => window.__settingsSmoke.close()")
+ page.wait_for_timeout(200)
+ report["steps"].append("abandoned-deep-open")
+
+
+def run_chunk_fail(page) -> None:
+ """One panel's module is blocked. The dialog must survive it, and so must the app."""
+ open_dialog(page)
+ settle_panel(page)
+ page.locator('[data-testid="settings-tab-general"]').click(force = True, timeout = 15000)
+ settle_panel(page)
+ page.locator(f'[data-testid="settings-tab-{CHUNK_FAIL}"]').click(force = True, timeout = 15000)
+ page.wait_for_timeout(3000)
+ state = page.evaluate(
+ """() => ({
+ dialog: !!document.querySelector('div[role="dialog"]'),
+ nav: document.querySelectorAll('[data-testid^="settings-tab-"]').length,
+ harness: !!document.querySelector('[data-testid="harness-root"]'),
+ boundary: !!document.querySelector('[data-testid="harness-error-boundary"]'),
+ panelText: (document.querySelector('div[role="dialog"] main div.hover-scrollbar')
+ || {}).innerText || null,
+ bodyText: (document.body.innerText || '').trim().length,
+ })"""
+ )
+ report["chunk_fail_state"] = state
+ log(f"after blocking {CHUNK_FAIL}: {state}")
+ # The idle prefetch pulls every panel, so a blocked one must not surface as a rejection.
+ errors = page.evaluate("() => window.__settingsSmoke.errors()")
+ report["chunk_fail_window_errors"] = errors
+ unhandled = [
+ e for e in errors if "dynamically imported module" in e or "Importing a module" in e
+ ]
+ if unhandled:
+ fail(f"blocking the {CHUNK_FAIL} panel left an unhandled rejection: {unhandled}")
+ else:
+ log("no unhandled rejection from the idle prefetch")
+ if state["boundary"]:
+ fail(
+ f"blocking the {CHUNK_FAIL} panel unmounted the app: the throw reached the "
+ "harness root boundary, and the real app has none"
+ )
+ if not state["dialog"] or state["nav"] != 12:
+ fail(f"blocking the {CHUNK_FAIL} panel took the dialog down ({state})")
+ else:
+ log("the dialog and its twelve nav entries survived")
+ # Another tab must still work.
+ page.locator('[data-testid="settings-tab-about"]').click(force = True, timeout = 15000)
+ after = settle_panel(page)
+ report["chunk_fail_recovery"] = after
+ if not after.get("present") or after.get("elements", 0) < 5:
+ fail(f"after a failed panel, another tab no longer renders ({after})")
+ else:
+ log("another tab still renders after the failure")
+
+
+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)
+
+ # --- 2. every tab renders when selected -----------------------------------------
+ open_dialog(page)
+ settle_panel(page)
+ # Start off the persisted tab, so the first iteration is a real switch.
+ page.locator('[data-testid="settings-tab-about"]').click(force = True, timeout = 15000)
+ settle_panel(page)
+ for tab in TABS:
+ obs = click_tab_and_observe(page, tab)
+ report["tabs"][tab] = obs
+ snap = obs["settled"]
+ if not snap.get("present"):
+ fail(f"tab {tab}: panel container missing")
+ elif snap.get("elements", 0) < 5:
+ fail(f"tab {tab}: panel settled empty ({snap})")
+ elif snap.get("sig") == obs["before_sig"]:
+ fail(f"tab {tab}: panel never changed from the previous tab ({snap['sig']})")
+ else:
+ log(
+ f"tab {tab}: changed after {obs['changed_ms']}ms, "
+ f"{snap['elements']} elements, {len(snap['labels'])} labels, "
+ f"blank frames {obs['blank_frames']}/{obs['frames_sampled']}"
+ )
+ report["steps"].append("all-tabs-render")
+
+ # --- 3. close/reopen, and deep-open straight to a tab ----------------------------
+ page.evaluate("() => window.__settingsSmoke.close()")
+ page.wait_for_timeout(300)
+ for tab in ("voice", "api-keys", "data", "about", "connections"):
+ open_dialog(page, tab)
+ state = page.evaluate("() => window.__settingsSmoke.state()")
+ snap = settle_panel(page)
+ report.setdefault("deep_open", {})[tab] = {"state": state, "settled": snap}
+ if state["activeTab"] != tab:
+ fail(f"deep-open {tab}: store activeTab is {state['activeTab']}")
+ if not snap.get("present") or snap.get("elements", 0) < 5:
+ fail(f"deep-open {tab}: panel did not render ({snap})")
+ elif snap["sig"] != report["tabs"][tab]["settled"]["sig"]:
+ fail(
+ f"deep-open {tab}: panel differs from the same tab reached by clicking "
+ f"({snap['sig']} vs {report['tabs'][tab]['settled']['sig']})"
+ )
+ else:
+ log(f"deep-open {tab}: matches the clicked-to panel")
+ page.evaluate("() => window.__settingsSmoke.close()")
+ page.wait_for_timeout(200)
+ report["steps"].append("deep-open")
+
+ # --- 4. search, then jump to a result and confirm the scroll target flashed ------
+ # A real setting well down a long panel, so a jump that never happens shows in scrollTop.
+ target_tab = "general"
+ target_label = report["tabs"][target_tab]["settled"]["labels"][-1]
+ query = target_label.split()[0]
+ open_dialog(page, "about")
+ settle_panel(page)
+ search = page.locator('div[role="dialog"] aside input').first
+ search.fill(query)
+ page.wait_for_timeout(400)
+ entries = page.locator('div[role="dialog"] aside button:not([data-testid])')
+ texts = [entries.nth(i).inner_text().strip() for i in range(entries.count())]
+ report["search"] = {"query": query, "target_label": target_label, "result_texts": texts}
+ log(f"search '{query}' -> {texts}")
+ index = next((i for i, txt in enumerate(texts) if txt == target_label), None)
+ if index is None:
+ fail(f"search '{query}': '{target_label}' not among results {texts}")
+ else:
+ entries.nth(index).click(force = True)
+ flashed = None
+ deadline = time.time() + 15
+ while time.time() < deadline:
+ state = page.evaluate(
+ """(sel) => {
+ const hit = document.querySelector('.settings-search-hit');
+ const root = document.querySelector(sel);
+ return {
+ hit: hit ? (hit.dataset.settingsLabel || hit.tagName) : null,
+ scrollTop: root ? root.scrollTop : null,
+ };
+ }""",
+ PANEL,
+ )
+ if state["hit"]:
+ flashed = state
+ break
+ page.wait_for_timeout(30)
+ report["search"]["flashed"] = flashed
+ report["search"]["settled"] = settle_panel(page)
+ if not flashed:
+ fail(
+ f"search jump to '{target_label}': never flashed "
+ f"(panel {report['search']['settled'].get('sig')})"
+ )
+ elif flashed["hit"] != target_label:
+ fail(f"search jump: flashed '{flashed['hit']}', expected '{target_label}'")
+ else:
+ log(f"search jump to '{target_label}': flashed, scrollTop {flashed['scrollTop']}")
+ report["steps"].append("search-jump")
+
+ report["page_errors"] = page.evaluate("() => window.__settingsSmoke.errors()")
+
+
+def write_report() -> None:
+ OUT.parent.mkdir(parents = True, exist_ok = True)
+ OUT.write_text(json.dumps(report, indent = 2), encoding = "utf-8")
+ log(f"report -> {OUT}")
+
+
+def main() -> int:
+ vite = start_vite(PORT)
+ try:
+ url = f"http://127.0.0.1:{PORT}/smoke-settings.html"
+ with sync_playwright() as pw:
+ launcher = getattr(pw, ENGINE)
+ kwargs: dict = {"headless": True}
+ if ENGINE == "chromium":
+ kwargs["args"] = chromium_launch_args()
+ browser = launcher.launch(**kwargs)
+ ctx = browser.new_context(
+ viewport = {"width": 1440, "height": 900},
+ reduced_motion = "reduce",
+ )
+ page = ctx.new_page()
+ if CHUNK_DELAY_MS or CHUNK_FAIL:
+
+ def handle(route):
+ path = route.request.url
+ if "/tabs/" not in path:
+ return route.continue_()
+ if CHUNK_FAIL and f"/{CHUNK_FAIL}-tab" in path:
+ return route.abort("failed")
+ if CHUNK_DELAY_MS:
+ time.sleep(CHUNK_DELAY_MS / 1000)
+ return route.continue_()
+
+ page.route("**/*", handle)
+ console: list[str] = []
+ page.on("console", lambda m: console.append(f"{m.type}: {m.text}"))
+ page.on("pageerror", lambda e: console.append(f"pageerror: {e}"))
+ for attempt in range(40):
+ try:
+ page.goto(url, wait_until = "domcontentloaded", timeout = 30000)
+ break
+ except Exception:
+ if attempt == 39:
+ raise
+ time.sleep(2)
+ page.wait_for_function("() => !!window.__settingsSmoke", timeout = 120000)
+ # Vite dev re-optimizes deps on first sight and full-reloads; settle, then
+ # reload once for a stable dep graph.
+ page.wait_for_timeout(4000)
+ page.reload(wait_until = "domcontentloaded")
+ page.wait_for_function("() => !!window.__settingsSmoke", timeout = 120000)
+ page.wait_for_timeout(1500)
+ try:
+ run(page)
+ finally:
+ report["console"] = [
+ c
+ for c in console
+ if ("error" in c.lower() or "pageerror" in c.lower())
+ and "502" not in c
+ and "403" not in c
+ ][:40]
+ boundary = page.locator('[data-testid="harness-error-boundary"]')
+ report["error_boundary"] = boundary.inner_text() if boundary.count() else None
+ if report["error_boundary"] and not CHUNK_FAIL:
+ fail(f"error boundary tripped: {report['error_boundary']}")
+ browser.close()
+ except Exception as exc:
+ # A cold-start dev server can fail to serve a module before anything is under
+ # test. Report that rather than dying with no record.
+ report["aborted"] = f"{type(exc).__name__}: {exc}"
+ fail(f"harness aborted: {report['aborted'].splitlines()[0]}")
+ write_report()
+ raise
+ finally:
+ stop_process(vite)
+
+ write_report()
+ if report["failures"]:
+ log(f"{len(report['failures'])} FAILURES")
+ for f in report["failures"]:
+ log(f" - {f}")
+ return 1
+ log("PASS")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/studio/playwright_ui_font_scale.py b/tests/studio/playwright_ui_font_scale.py
index a9dd4652b06..a75f90bef6f 100644
--- a/tests/studio/playwright_ui_font_scale.py
+++ b/tests/studio/playwright_ui_font_scale.py
@@ -15,6 +15,7 @@ Runs against an already-booted, already-bootstrapped Unsloth:
import os
import re
import sys
+import time
from pathlib import Path
from playwright.sync_api import TimeoutError as PWTimeout
@@ -53,6 +54,33 @@ if _BASE is None:
CSS_BASE = int(_BASE.group(1))
+def settled_scroll_top(
+ page,
+ quiet_ms = 200,
+ timeout_ms = 5_000,
+):
+ """The select viewport's scrollTop once it has stopped moving.
+
+ Radix scrolls the highlighted item into view off the back of the keypress, so
+ a scrollTop read straight after `keyboard.press` is a mid-scroll sample, not
+ where the viewport ends up. Poll until it holds the same value for `quiet_ms`.
+ Falls back to the last value seen rather than raising: this only establishes
+ the floor for the wheel check, and that check reports its own failure.
+ """
+ last = page.evaluate(SCROLL_TOP_JS)
+ quiet_since = time.monotonic()
+ deadline = time.monotonic() + timeout_ms / 1000
+ while time.monotonic() < deadline:
+ page.wait_for_timeout(50)
+ now = page.evaluate(SCROLL_TOP_JS)
+ if now != last:
+ last = now
+ quiet_since = time.monotonic()
+ elif (time.monotonic() - quiet_since) * 1000 >= quiet_ms:
+ return now
+ return last
+
+
def step(s):
print(f"[font-scale] STEP {s}", flush = True)
@@ -226,17 +254,36 @@ def main():
if not kb_top > 0:
fail(f"keyboard did not scroll the select viewport after 40 presses: {kb_top}")
+ # That read lands mid-scroll and comes in low (24-35px on the ubuntu CI image),
+ # which is neither the floor the wheel has to beat nor a moment a wheel event
+ # survives. Let the scroll finish and re-read instead of racing it.
+ kb_top = settled_scroll_top(page)
+ # At 0 the comparison below is unsatisfiable, so the wheel would always fail.
+ if not kb_top > 0:
+ fail(f"select viewport returned to the top once the keyboard scroll settled: {kb_top}")
+
vp_box = viewport.bounding_box()
- page.mouse.move(vp_box["x"] + vp_box["width"] / 2, vp_box["y"] + 40)
- page.mouse.wheel(0, -400)
- try:
- page.wait_for_function(
- "top => document.querySelector('[data-radix-select-viewport]').scrollTop < top",
- arg = kb_top,
- timeout = 10_000,
- )
- except PWTimeout:
- wheel_top = page.evaluate(SCROLL_TOP_JS)
+ # Keep the pointer inside the viewport: a fixed 40px offset lands outside a
+ # shorter box and the wheel then goes to whatever is underneath.
+ page.mouse.move(
+ vp_box["x"] + vp_box["width"] / 2,
+ vp_box["y"] + min(40, vp_box["height"] / 2),
+ )
+ # A single wheel event can be dropped, so retry a bounded number of times. A
+ # viewport that truly refuses the wheel never moves and still fails.
+ wheel_top = kb_top
+ for _ in range(5):
+ page.mouse.wheel(0, -400)
+ try:
+ page.wait_for_function(
+ "top => document.querySelector('[data-radix-select-viewport]').scrollTop < top",
+ arg = kb_top,
+ timeout = 2_000,
+ )
+ break
+ except PWTimeout:
+ wheel_top = page.evaluate(SCROLL_TOP_JS)
+ else:
fail(f"wheel did not scroll the select viewport: {kb_top} -> {wheel_top}")
page.keyboard.press("Escape")
page.set_viewport_size({"width": 1440, "height": 900})