Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: overlap credential reads and preserve startup recovery (#16389)
Daniel Handaaa2e289ba7
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex b5fba5e5ed6..9a9ab23c6b7 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -38,7 +38,10 @@ import { useExportRuntimeLifecycle } from "@/features/export";import { FIND_SCOPE_ATTRIBUTE, FindInPage } from "@/features/find-in-page";import { HfTokenWarningDialog } from "@/features/hf-auth";import { InterfaceZoom, zoomInterfaceFromMenu } from "@/features/interface-zoom";-import { bootstrapPersistedCredentials } from "@/features/credentials/bootstrap";+import {+ bootstrapPersistedCredentials,+ takeStartupCredentialBootstrap,+} from "@/features/credentials/bootstrap";import { ManagedEngineOfferDialog } from "@/features/model-picker/components/managed-engine-offer-dialog";import { SharedRunConfigLinkHandler } from "@/features/model-picker/sharing/link-handler";import { backfillModelOverrides } from "@/features/model-picker/api/migrate-model-overrides";@@ -118,7 +121,6 @@ function RouteFallback() {);}-// Retires the reload shell inside the route's Suspense, so a lazy page keeps the shell up.function InitialReadyPage({children,}: {@@ -181,7 +183,6 @@ function ChatPageLoadFailure({}) {const t = useT();const signalReady = useAppShellReadySignal();- // The page it stands in for would have signalled; without this Desktop keeps its startup screen.useLayoutEffect(() => {signalReady();}, [signalReady]);@@ -202,8 +203,7 @@ function ChatPageLoadFailure({);}-// A failed import resolves to the failure panel (not a throw), so a crash inside the page still-// reaches the route boundary; a new lazy() per attempt since lazy() caches its result.+// Recreate lazy() after failure because it caches failed imports.function chatPageAttempt(): ComponentType<ChatPageAttemptProps> {return (loadedChatPage() ??@@ -217,7 +217,6 @@ function chatPageAttempt(): ComponentType<ChatPageAttemptProps> {}function ChatPage(props: ChatPageProps) {- // Kept until a failure: swapping component type would remount the page and drop its state.const [Page, setPage] = useState(chatPageAttempt);const retry = useCallback(() => setPage(() => chatPageAttempt()), []);return (@@ -227,7 +226,6 @@ function ChatPage(props: ChatPageProps) {);}-// Mounted persistently below so an in-flight batch survives leaving the tab; lazy on first visit.const ImagesPage = lazy(() =>import("@/features/images").then((m) => ({ default: m.ImagesPage })),);@@ -249,8 +247,7 @@ function PersonalizationSyncMount() {return null;}-// Voice Settings "Load into" kept in step with the server copy that device-less STT API loads read (#15280). Here,-// not on store rehydrate: the store loads at startup, before the desktop backend port is known and before sign-in.+// Wait for the Desktop port and sign-in before mirroring STT device preference (#15280).function SttDeviceSyncMount() {useRouterState({ select: (s) => s.location.pathname });const settled = hasSettledAuthSession();@@ -264,10 +261,6 @@ function SttDeviceSyncMount() {return null;}-// A full disk is not a training problem, so the warning cannot live on the-// training route: it belongs to whichever route the user happens to be on when-// space runs out. Mounted here it subscribes once for the session, and stays-// subscribed across navigation, instead of coming and going with /studio.function LowDiskNoticeMount() {useLowDiskNotice();return null;@@ -278,7 +271,6 @@ function HubSourceNoticeMount() {return null;}-// Models page and picker read chat settings too, so hydration cannot wait for ChatPage.function ChatSettingsHydrationMount() {usePinnedChatsSync();const hydratePersistedSettings = useChatRuntimeStore(@@ -315,7 +307,9 @@ function CredentialBootstrapGate({return;}setReady(false);- void bootstrapPersistedCredentials().finally(() => {+ void (+ takeStartupCredentialBootstrap() ?? bootstrapPersistedCredentials()+ ).finally(() => {if (mounted &&revision === runRevision.current &&@@ -353,23 +347,16 @@ const CHAT_ONLY_ALLOWED = new Set(["/chat","/projects","/library",- // Tasks only need a chat model, which a chat-only host runs."/tasks","/hub","/login","/signup","/change-password",- // Reachable on chat-only hosts so the page shows its own reason; it self-gates."/export",- // Must stay reachable on chat-only hosts: the overlay "Expand" and Settings API card link here."/api-monitor",]);-// Paths that render their own "still checking" state and self-gate once the verdict lands.-// The redirect below is one-way, so acting on the pre-measurement guess strands a healthy host-// on /chat; these two wait it out instead. Everything else keeps the old behaviour.-// /video is allowed outright below, so this is in practice what keeps /studio off the guess. It-// stays listed so that admission is the only thing /video depends on, not both.+// Wait for measured admission: redirecting on an initial guess strands healthy hosts on /chat.const SELF_GATED_WHILE_UNKNOWN = ["/studio", "/video"];function waitsOutUnknownVerdict(pathname: string): boolean {@@ -384,10 +371,8 @@ function isChatOnlyAllowed(pathname: string, trainAvailable: boolean): boolean {return true;if (pathname === "/data-recipes" || pathname.startsWith("/data-recipes/"))return true;- // Images runs on CPU/MPS via sd.cpp; chat-only is about training/export.if (pathname === "/images" || pathname.startsWith("/images/")) return true;if (pathname === "/audio" || pathname.startsWith("/audio/")) return true;- // Video self-gates on the backend's video verdict, and works on chat-only Apple Silicon.if (pathname === "/video" || pathname.startsWith("/video/")) return true;return false;}@@ -436,18 +421,14 @@ function RootLayout() {(s) => s.isTrainUnavailable() && !s.capabilitiesUnknown(),);const chatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);- // Video is the other row the sidebar grays out, on the two verdicts its pipelines cannot run on- // at all. Same hint the row reads, so the two cannot disagree about which hosts they are.const videoCpuOptIn = usePlatformStore((s) => s.videoCpuOptIn);const cpuTraining = usePlatformStore((s) => s.cpuTraining);const videoDisabled =videoNavHint(chatOnlyMeasured, chatOnlyReason, videoCpuOptIn, cpuTraining) !== undefined;- // Exact match: a prefix would treat /chatty as chat, hiding its not-found UI.const isChatRoute = pathname === "/chat";const { pinned, setPinned, togglePinned } = useSidebarPin();const navigate = useNavigate();- // ChatPage is mounted persistently so generation survives leaving the tab; search frozen off-route.const rawSearch = useRouterState({ select: (s) => s.location.search }) as| Record<string, unknown>| undefined;@@ -467,11 +448,7 @@ function RootLayout() {}),[rawThread, rawCompare, rawNew, rawProject],);- // Freeze the last /chat search and latch "mounted" via render-phase setState (React's "adjust- // state during render" pattern), avoiding effects/refs. Empty until /chat is visited:- // location.search is the raw URL's, not the matched route's, so seeding it would let another- // route's ?project= stand in for a chat the user has never opened. The adjustment below fills it- // on the first /chat render, so landing straight on /chat loses nothing.+ // Seed search only on /chat; another route's ?project= must not create a phantom chat.const [frozenChatSearch, setFrozenChatSearch] = useState<ChatSearch>({});const [chatMounted, setChatMounted] = useState(isChatRoute);if (isChatRoute && frozenChatSearch !== liveChatSearch) {@@ -483,7 +460,6 @@ function RootLayout() {const chatSearch = isChatRoute ? liveChatSearch : frozenChatSearch;const shouldMountChat = isChatRoute || chatMounted;- // `active` lags the matches by a render, so ImagesPage reads ?model= from its own match.const isImagesRoute = pathname === "/images";const [imagesMounted, setImagesMounted] = useState(isImagesRoute);if (isImagesRoute && !imagesMounted) {@@ -505,9 +481,7 @@ function RootLayout() {setAudioMounted(true);}const shouldMountAudio = isAudioRoute || audioMounted;- // All four pages render their own full-height shell: no outer inset or scroll.const isChatLike = isChatRoute || isImagesRoute || isVideoRoute || isAudioRoute;- // Uses Navbar's hook, not the md breakpoint: a narrowed desktop window keeps the desktop navbar.const nonChatTopInset = useIsMobileShell()? "pt-14": "pt-[calc(var(--studio-non-chat-content-top-inset,var(--studio-content-top-inset,0px))-var(--studio-non-chat-scroller-top,0px))] [--studio-titlebar-height:var(--studio-non-chat-content-top-inset,var(--studio-content-top-inset,0px))]";@@ -539,7 +513,6 @@ function RootLayout() {// Desktop mounts this root before the port exists; authFetch retries keep the URL it started with.const desktopShellReady = useDesktopShellReady();- // Settings predating the server override map live only locally; backfill once after auth.useEffect(() => {if (isAuthFlowRoute || !desktopShellReady) {return;@@ -570,12 +543,7 @@ function RootLayout() {standalone?: boolean;}) => {const chatRuntime = useChatRuntimeStore.getState();- // The project on screen, which on Chat is the runtime's. The page keeps that in step with the- // route, the inferred ones included: a thread or a compare pair opened without ?project= still- // belongs to its project, and the page's own New chat button starts the next chat there.- // Reading the search param instead would leave that project without being asked to. Off Chat- // the page is hidden rather than unmounted, so its project is one the user cannot see and a new- // chat belongs to none.+ // Off Chat, the hidden runtime project must not become the new chat's project.const openProjectId = isChatRoute ? chatRuntime.activeProjectId : null;const projectId = options?.standalone ? null : openProjectId;chatRuntime.setActiveThreadId(null);@@ -587,8 +555,6 @@ function RootLayout() {});};- // Gated like the workspace chords below: /login has no shell, and /chat- // bounces straight back off requireAuth.const routeShortcutEnabled = !isAuthFlowRoute && !settingsDialogOpen;useShortcut("newChat", () => startNewChat(), {enabled: routeShortcutEnabled,@@ -605,7 +571,6 @@ function RootLayout() {const pathLeasesSupported = useNativePathLeasesSupported();const ragUnavailable = useRagAvailabilityStore((s) => s.isUnavailable());const openingFolder = useOpeningFolder();- // Menu items for web shortcuts are live exactly while a mounted handler would take them.const sidebarMounted = useShortcutAvailable("toggleSidebar", hasAppMenus);const findMounted = useShortcutAvailable("findInPage", hasAppMenus);const previousChatMounted = useShortcutAvailable("previousChat", hasAppMenus);@@ -617,7 +582,6 @@ function RootLayout() {isAuthFlowRoute || !helpActionAvailable(action, isOwner) ? null : () => runHelpAction(action);const goTo = (to: string) => () => void navigate({ to });const goAction = (enabled: boolean, go: () => void) => (enabled ? go : null);- // Go > Settings: the pages this account can open.const settingsActions = Object.fromEntries(SETTINGS_TABS.map((tab) => [`settings-${tab}`,@@ -673,7 +637,6 @@ function RootLayout() {...settingsActions,}, desktopShellReady);- // Carry the frozen search back: a bare /chat is a fresh chat and would drop the thread.useShortcut("switchToChat",() => void navigate({ to: "/chat", search: chatSearch }),@@ -685,7 +648,6 @@ function RootLayout() {useShortcut("switchToHub", goTo("/hub"), {enabled: routeShortcutEnabled,});- // Train's chord waits for a measured verdict, or it would bounce off /studio to /chat.useShortcut("switchToTrain", goTo("/studio"), {enabled: routeShortcutEnabled && !trainBlocked,});@@ -695,7 +657,6 @@ function RootLayout() {useShortcut("switchToImages", goTo("/images"), {enabled: routeShortcutEnabled,});- // /video only checks auth, so gate the chord on its own measured predicate.useShortcut("switchToVideo", goTo("/video"), {enabled: routeShortcutEnabled && !videoDisabled,});@@ -735,7 +696,6 @@ function RootLayout() {<TransformersUpgradeDialog /><ManagedEngineOfferDialog /><LlmCompressorConsentDialog />- {/* At the root, not under /chat: a swap can start from the Hub too. */}<StopRunningChatsDialog /><ImageViewer />{!hideNavbar && <CommandPalette />}@@ -772,14 +732,8 @@ function RootLayout() {{...{ [FIND_SCOPE_ATTRIBUTE]: "" }}className={`relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col ${isChatLike ? "overflow-hidden" : "overflow-visible"} ${isChatLike ? "" : nonChatTopInset}`}>- {/* The find bar floats over this region and searches it: the workspace on screen,- without the sidebar, the navbar, or the off-route workspaces parked here under- `inert`. Gated off behind a modal, which owns Escape while it is up. */}<FindInPage enabled={routeShortcutEnabled} />- {/* Stays mounted across navigation so an in-flight generation is- not cancelled when leaving /chat; hidden (not unmounted) off-route.- `active` lets ChatPage close its body-portaled surfaces (model- selector, settings sheet, tour) so they don't bleed over other tabs. */}+ {/* Keep generation mounted across routes; active closes hidden page overlays. */}{shouldMountChat && (<divclassName={@@ -792,7 +746,6 @@ function RootLayout() {<ChatPage search={chatSearch} active={isChatRoute} /></div>)}- {/* `active` force-closes body-portaled overlays so none bleed over another tab while hidden. */}{shouldMountImages && (<divclassName={@@ -847,11 +800,7 @@ function RootLayout() {</Suspense></div>)}- {/* Use mode="popLayout" instead of "wait" to prevent UI freezes when- switching from heavy pages (like Export with many checkpoints).- "popLayout" allows the new route to mount immediately while the- old one animates out, avoiding blocking on expensive exit renders.- See issue #5850. */}+ {/* wait mode froze navigation behind slow page exits (#5850). */}{!isChatRoute && !isImagesRoute && !isVideoRoute && !isAudioRoute && (<AnimatePresence initial={false} mode="popLayout"><motion.divdiff --git a/studio/frontend/src/features/credentials/bootstrap.ts b/studio/frontend/src/features/credentials/bootstrap.tsindex 13d428fb92a..5c6b0e84053 100644--- a/studio/frontend/src/features/credentials/bootstrap.ts+++ b/studio/frontend/src/features/credentials/bootstrap.ts@@ -2,22 +2,89 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { getAuthSessionEpoch, hasAuthToken } from "@/features/auth";+import type { ExternalProviderConfig } from "@/features/chat";import { useExternalProvidersStore } from "@/features/chat/stores/external-providers-store";import { syncExternalProvidersFromBackend } from "@/features/chat/sync-external-providers";import { hydrateHfTokenFromBackend } from "@/features/hub/stores/hf-token-store";import { runCredentialBootstrap } from "./reconciliation";-export function bootstrapPersistedCredentials(): Promise<void> {+let credentialBootstrapRevision = 0;++function credentialBootstrapDependencies() {+ const bootstrapRevision = ++credentialBootstrapRevision;const sessionEpoch = getAuthSessionEpoch();const isCurrent = () =>- hasAuthToken() && getAuthSessionEpoch() === sessionEpoch;- return runCredentialBootstrap({+ hasAuthToken() && getAuthSessionEpoch() === sessionEpoch &&+ bootstrapRevision === credentialBootstrapRevision;+ return {hydrateHfToken: hydrateHfTokenFromBackend,getProviders: () => useExternalProvidersStore.getState().providers,- syncProviders: (providers) =>+ syncProviders: (providers: ExternalProviderConfig[]) =>syncExternalProvidersFromBackend(providers, isCurrent),- setProviders: (providers) =>+ setProviders: (providers: ExternalProviderConfig[]) =>useExternalProvidersStore.getState().setProviders(providers),isCurrent,+ };+}++export function bootstrapPersistedCredentials(): Promise<void> {+ return runCredentialBootstrap(credentialBootstrapDependencies());+}++let startupBootstrap: {+ sessionEpoch: number;+ run: Promise<void>;+ retry: () => Promise<void>;+ handoff?: Promise<void>;+} | null = null;+let startupBootstrapRequested = false;++export function startStartupCredentialBootstrap(): void {+ if (startupBootstrapRequested) return;+ startupBootstrapRequested = true;+ if (!hasAuthToken()) return;+ const sessionEpoch = getAuthSessionEpoch();+ const dependencies = credentialBootstrapDependencies();+ const failedTasks = new Set<"hfToken" | "providers">();+ const run = runCredentialBootstrap({+ ...dependencies,+ onFailure: (task) => failedTasks.add(task),});+ startupBootstrap = {+ sessionEpoch,+ run,+ retry: async () => {+ if (!dependencies.isCurrent() || !failedTasks.size) return;+ await runCredentialBootstrap({+ ...dependencies,+ hydrateHfToken: () =>+ failedTasks.has("hfToken")+ ? dependencies.hydrateHfToken()+ : Promise.resolve(),+ syncProviders: (providers) =>+ failedTasks.has("providers")+ ? dependencies.syncProviders(providers)+ : Promise.resolve(providers),+ setProviders: (providers) => {+ if (failedTasks.has("providers")) dependencies.setProviders(providers);+ },+ });+ },+ };+}++export function takeStartupCredentialBootstrap(): Promise<void> | null {+ const startup = startupBootstrap;+ if (+ startup &&+ hasAuthToken() &&+ getAuthSessionEpoch() === startup.sessionEpoch+ ) {+ startup.handoff ??= startup.run.then(startup.retry).finally(() => {+ if (startupBootstrap === startup) startupBootstrap = null;+ });+ return startup.handoff;+ }+ startupBootstrap = null;+ return null;}diff --git a/studio/frontend/src/features/credentials/reconciliation.ts b/studio/frontend/src/features/credentials/reconciliation.tsindex eabb0708280..74deef9f368 100644--- a/studio/frontend/src/features/credentials/reconciliation.ts+++ b/studio/frontend/src/features/credentials/reconciliation.ts@@ -47,7 +47,6 @@ export async function reconcileLegacyHfToken<T extends HfCredentialStatus>(try {migrated = await dependencies.saveLegacyToken(legacyToken);} catch (error) {- // Keep the legacy token working while the backend is unavailable.dependencies.applyToken(legacyToken);throw error;}@@ -101,7 +100,6 @@ export async function reconcileLegacyProviderKeys<dependencies.removeLegacyKey(config.id, legacyKey);}} catch {- // Preserve local input for retry and per-request fallback.}}return reconciled;@@ -123,6 +121,7 @@ export interface CredentialBootstrapDependencies<T> {setProviders: (providers: T[]) => void;isCurrent?: () => boolean;+ onFailure?: (task: "hfToken" | "providers") => void;}export async function runCredentialBootstrap<T>(@@ -131,10 +130,12 @@ export async function runCredentialBootstrap<T>(if (dependencies.isCurrent && !dependencies.isCurrent()) return;const providerSync = dependencies.syncProviders(dependencies.getProviders());- const [, providerResult] = await Promise.allSettled([+ const [hfResult, providerResult] = await Promise.allSettled([dependencies.hydrateHfToken(),providerSync,]);+ if (hfResult.status === "rejected") dependencies.onFailure?.("hfToken");+ if (providerResult.status === "rejected") dependencies.onFailure?.("providers");if (providerResult.status === "fulfilled" &&(!dependencies.isCurrent || dependencies.isCurrent())diff --git a/studio/frontend/src/main.tsx b/studio/frontend/src/main.tsxindex 9c79b5c0a9c..c684ff31bc2 100644--- a/studio/frontend/src/main.tsx+++ b/studio/frontend/src/main.tsx@@ -20,7 +20,12 @@ import {} from "./components/assistant-ui/reasoning-row-containment";import { fetchDeviceType } from "./config/env";import { refreshSession } from "./features/auth/api";-import { getPostAuthRoute, hasAuthToken } from "./features/auth/session";+import {+ getPostAuthRoute,+ hasAuthToken,+ hasSettledAuthSession,+} from "./features/auth/session";+import { startStartupCredentialBootstrap } from "./features/credentials/bootstrap";import { loadChatPage, prefetchChatPage } from "./features/chat/load-chat-page";import {applyInterfaceScaleBeforeFirstPaint,@@ -39,7 +44,6 @@ import { watchTimeFormat } from "./lib/time-format";markAppSessionStart();setHubSessionRefresh(refreshSession);-// Signed-in sessions land on Chat, so fetch it with the startup bundle and wait for it.const startPath = window.location.pathname;const chatPageAtStart =startPath === "/chat" ||@@ -60,21 +64,17 @@ if (isTauri) {document.documentElement.classList.add("tauri");}-// Rasterization follows the browser OS, not the possibly remote server.-// Calibrated for desktop Linux, so Android is excluded.const uaLower = navigator.userAgent.toLowerCase();if (uaLower.includes("linux") && !uaLower.includes("android")) {document.documentElement.classList.add("render-linux");}-// index.css keys off this to restore ::-webkit-scrollbar styling on Windows.if (uaLower.includes("windows")) {document.documentElement.classList.add("client-windows");}// Must run before the first render: arming the containment rule late relayouts the first thread.applyMathBlockContainment();-// Reapply when the devtools override `__UNSLOTH_MATH_BLOCK_CONTAINMENT__` flips.watchMathBlockContainmentOverride();applyCodeBlockContainment();watchCodeBlockContainmentOverride();@@ -84,7 +84,6 @@ watchReasoningRowContainmentOverride();watchOverlayScrollbarGutter(window);watchInputModality(window);-// Before the first render, so a disabled spell check never flashes underlines.watchSpellCheck(window);watchTimeFormat(window);@@ -102,7 +101,6 @@ function renderApp(): void {<App /></StrictMode>,);- // Otherwise prefetch Chat once the first screen is up, not during its first frame.if (!chatPageAtStart) {const prefetchOnce = () => {window.removeEventListener(APP_SHELL_READY_EVENT, afterReady);@@ -132,3 +130,13 @@ if (typeof localeInitialization !== "string" || isTauri || chatPageAtStart) {}fetchDeviceType().catch(() => undefined);++// Desktop signs in after its backend starts, so its gate owns reconciliation.+if (+ !isTauri &&+ hasSettledAuthSession() &&+ startPath !== "/login" &&+ startPath !== "/change-password"+) {+ startStartupCredentialBootstrap();+}diff --git a/studio/frontend/tests/chat-page-lazy-startup.test.ts b/studio/frontend/tests/chat-page-lazy-startup.test.tsindex 9b2b9463eec..e9eb7f4aa2c 100644--- a/studio/frontend/tests/chat-page-lazy-startup.test.ts+++ b/studio/frontend/tests/chat-page-lazy-startup.test.ts@@ -144,10 +144,8 @@ test("a failed chat page load stays inside the chat area and retries", () => {test("a crash inside the chat page is not caught as a load failure", () => {const root = readSrc("app/routes/__root.tsx");- const page = root.slice(- root.indexOf("function ChatPage("),- root.indexOf("// Mounted persistently below"),- );+ const page = root.match(/function ChatPage\([^]*?\n\}/)?.[0];+ assert.ok(page, "ChatPage declaration must be present");assert.doesNotMatch(page, /Boundary/);});diff --git a/studio/frontend/tests/startup-recovery.test.ts b/studio/frontend/tests/startup-recovery.test.tsnew file mode 100644index 00000000000..a795dcdf2b3--- /dev/null+++ b/studio/frontend/tests/startup-recovery.test.ts@@ -0,0 +1,243 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import { pathToFileURL } from "node:url";++import { loadWithStubs } from "./helpers/module-stubs.ts";+import { installLocalStorageFake, registerStoreStubResolver } from "./helpers/kit.ts";++type Bootstrap = typeof import("../src/features/credentials/bootstrap.ts");+const source = process.env.CREDENTIAL_BOOTSTRAP_ROOT+ ? pathToFileURL(`${process.env.CREDENTIAL_BOOTSTRAP_ROOT}/src/features/credentials/`)+ : new URL("../src/features/credentials/", import.meta.url);++function fixture() {+ const session = { epoch: 0, token: true };+ const live = { hf: true, providers: true };+ const calls = { hf: 0, providers: 0 };+ const state = { hfHydrated: false, providers: [] as string[] };+ let holdHf: Promise<void> | null = null;+ let holdProviders: Promise<string[]> | null = null;+ const reconciliation = loadWithStubs(+ new URL("reconciliation.ts", source), {},+ );+ const mod = loadWithStubs<Bootstrap>(new URL("bootstrap.ts", source), {+ "@/features/auth": {+ getAuthSessionEpoch: () => session.epoch,+ hasAuthToken: () => session.token,+ },+ "@/features/chat/stores/external-providers-store": {+ useExternalProvidersStore: {+ getState: () => ({+ providers: state.providers,+ setProviders: (rows: string[]) => { state.providers = rows; },+ }),+ },+ },+ "@/features/chat/sync-external-providers": {+ syncExternalProvidersFromBackend: async () => {+ calls.providers += 1;+ if (!live.providers) throw new Error("providers temporarily unavailable");+ if (holdProviders) return holdProviders;+ return ["saved-provider"];+ },+ },+ "@/features/hub/stores/hf-token-store": {+ hydrateHfTokenFromBackend: async () => {+ calls.hf += 1;+ if (holdHf) await holdHf;+ if (!live.hf) throw new Error("HF temporarily unavailable");+ state.hfHydrated = true;+ },+ },+ "./reconciliation": reconciliation,+ });+ return {+ mod, session, live, calls, state,+ holdHf: (value: Promise<void>) => { holdHf = value; },+ holdProviders: (value: Promise<string[]>) => { holdProviders = value; },+ };+}++const settle = () => new Promise<void>((resolve) => setImmediate(resolve));++test("successful startup work is reused before and after settlement", async () => {+ for (const settled of [false, true]) {+ const f = fixture();+ f.mod.startStartupCredentialBootstrap();+ if (settled) await settle();+ await f.mod.takeStartupCredentialBootstrap();+ assert.deepEqual(f.calls, { hf: 1, providers: 1 });+ assert.equal(f.state.hfHydrated, true);+ assert.deepEqual(f.state.providers, ["saved-provider"]);+ assert.equal(f.mod.takeStartupCredentialBootstrap(), null);+ }+});++for (const failure of ["hf", "providers", "both"] as const) {+ test(`the gate retries a settled ${failure} startup failure after recovery`, async () => {+ const f = fixture();+ f.live.hf = failure === "providers";+ f.live.providers = failure === "hf";+ f.mod.startStartupCredentialBootstrap();+ await settle();+ f.live.hf = f.live.providers = true;+ await f.mod.takeStartupCredentialBootstrap();+ assert.equal(f.state.hfHydrated, true);+ assert.deepEqual(f.state.providers, ["saved-provider"]);+ assert.deepEqual(f.calls, {+ hf: failure === "providers" ? 1 : 2,+ providers: failure === "hf" ? 1 : 2,+ });+ assert.equal(f.mod.takeStartupCredentialBootstrap(), null);+ });+}++test("a failure that settles after handoff also gets one retry", async () => {+ const f = fixture();+ let fail!: (reason: Error) => void;+ f.holdHf(new Promise<void>((_, reject) => { fail = reject; }));+ f.mod.startStartupCredentialBootstrap();+ const gate = f.mod.takeStartupCredentialBootstrap();+ f.holdHf(Promise.resolve());+ fail(new Error("initial request failed"));+ await gate;+ assert.equal(f.state.hfHydrated, true);+ assert.deepEqual(f.calls, { hf: 2, providers: 1 });+ assert.deepEqual(f.state.providers, ["saved-provider"]);+});++test("a session change while startup is pending prevents its retry", async () => {+ const f = fixture();+ let fail!: (reason: Error) => void;+ f.holdHf(new Promise<void>((_, reject) => { fail = reject; }));+ f.live.providers = false;+ f.mod.startStartupCredentialBootstrap();+ const gate = f.mod.takeStartupCredentialBootstrap();+ f.session.epoch += 1;+ f.holdHf(Promise.resolve());+ f.live.providers = true;+ fail(new Error("old session request failed"));+ await gate;+ assert.deepEqual(f.calls, { hf: 1, providers: 1 });+ assert.deepEqual(f.state.providers, []);+});++test("retried providers are not published before the HF retry settles", async () => {+ const f = fixture();+ f.live.hf = f.live.providers = false;+ f.mod.startStartupCredentialBootstrap();+ await settle();+ f.live.hf = f.live.providers = true;+ let finish!: () => void;+ f.holdHf(new Promise<void>((resolve) => { finish = resolve; }));+ const gate = f.mod.takeStartupCredentialBootstrap();+ await settle();+ assert.deepEqual(f.calls, { hf: 2, providers: 2 });+ assert.deepEqual(f.state.providers, []);+ finish();+ await gate;+ assert.equal(f.state.hfHydrated, true);+ assert.deepEqual(f.state.providers, ["saved-provider"]);+});++test("a failed handoff retry settles without a retry loop", async () => {+ const f = fixture();+ f.live.hf = f.live.providers = false;+ f.mod.startStartupCredentialBootstrap();+ await settle();+ await f.mod.takeStartupCredentialBootstrap();+ assert.deepEqual(f.calls, { hf: 2, providers: 2 });+ assert.equal(f.state.hfHydrated, false);+ assert.deepEqual(f.state.providers, []);+ await f.mod.bootstrapPersistedCredentials();+ assert.deepEqual(f.calls, { hf: 3, providers: 3 });+});++test("a replacement bootstrap suppresses a detached startup retry", async () => {+ const f = fixture();+ f.live.providers = false;+ f.mod.startStartupCredentialBootstrap();+ await settle();+ f.live.providers = true;+ f.holdProviders(Promise.resolve(["replacement"]));+ const detached = f.mod.takeStartupCredentialBootstrap();+ const replacement = f.mod.bootstrapPersistedCredentials();+ let finish!: (providers: string[]) => void;+ f.holdProviders(new Promise((resolve) => { finish = resolve; }));+ await replacement;+ f.state.providers = ["user-edit"];+ finish(["stale-startup-retry"]);+ await detached;+ assert.deepEqual(f.state.providers, ["user-edit"]);+ assert.equal(f.calls.providers, 2);+});++test("a replacement bootstrap supersedes a pending startup publication", async () => {+ const f = fixture();+ let finish!: (providers: string[]) => void;+ f.holdProviders(new Promise((resolve) => { finish = resolve; }));+ f.mod.startStartupCredentialBootstrap();+ const detached = f.mod.takeStartupCredentialBootstrap();+ f.holdProviders(Promise.resolve(["replacement"]));+ await f.mod.bootstrapPersistedCredentials();+ f.state.providers = ["user-edit"];+ finish(["stale-original-startup"]);+ await detached;+ assert.deepEqual(f.state.providers, ["user-edit"]);+ assert.equal(f.calls.providers, 2);+});++test("gate replay recovers a pending shared HF read that fails after readiness", async () => {+ registerStoreStubResolver();+ const { store } = installLocalStorageFake();+ store.set("unsloth_auth_token", "session-token");+ const originalFetch = globalThis.fetch;+ let release!: (response: Response) => void;+ let started!: () => void;+ const firstResponse = new Promise<Response>((resolve) => { release = resolve; });+ const firstStarted = new Promise<void>((resolve) => { started = resolve; });+ let reads = 0;+ globalThis.fetch = (async () => {+ reads += 1;+ if (reads === 1) {+ started();+ return firstResponse;+ }+ return new Response(JSON.stringify({ has_token: true, token: "hf_saved_fixture" }), {+ headers: { "Content-Type": "application/json" },+ });+ }) as typeof fetch;+ try {+ const hf = await import("../src/features/hub/stores/hf-token-store.ts");+ const reconciliation = loadWithStubs(new URL("reconciliation.ts", source), {});+ const mod = loadWithStubs<Bootstrap>(new URL("bootstrap.ts", source), {+ "@/features/auth": { getAuthSessionEpoch: () => 0, hasAuthToken: () => true },+ "@/features/chat/stores/external-providers-store": {+ useExternalProvidersStore: { getState: () => ({ providers: [], setProviders: () => {} }) },+ },+ "@/features/chat/sync-external-providers": {+ syncExternalProvidersFromBackend: async () => [],+ },+ "@/features/hub/stores/hf-token-store": hf,+ "./reconciliation": reconciliation,+ });+ mod.startStartupCredentialBootstrap();+ await firstStarted;+ const firstGate = mod.takeStartupCredentialBootstrap();+ const replayGate = mod.takeStartupCredentialBootstrap() ?? mod.bootstrapPersistedCredentials();+ release(new Response(JSON.stringify({ detail: "brief early outage" }), {+ status: 503, headers: { "Content-Type": "application/json" },+ }));+ await Promise.all([firstGate, replayGate]);+ assert.equal(hf.getHfToken(), "hf_saved_fixture");+ assert.equal(reads, 2);+ assert.equal(mod.takeStartupCredentialBootstrap(), null);+ } finally {+ globalThis.fetch = originalFetch;+ Reflect.deleteProperty(globalThis, "window");+ Reflect.deleteProperty(globalThis, "localStorage");+ }+});diff --git a/studio/frontend/tests/startup-waterfall.test.ts b/studio/frontend/tests/startup-waterfall.test.tsnew file mode 100644index 00000000000..05d74cb6d07--- /dev/null+++ b/studio/frontend/tests/startup-waterfall.test.ts@@ -0,0 +1,135 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { readSrc } from "./helpers/kit.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++type Bootstrap = typeof import("../src/features/credentials/bootstrap.ts");++function loadBootstrap() {+ const session = { epoch: 0, token: "original" as string | null };+ const runs: Array<{ resolve: () => void; promise: Promise<void> }> = [];+ const mod = loadWithStubs<Bootstrap>(+ new URL("../src/features/credentials/bootstrap.ts", import.meta.url),+ {+ "@/features/auth": {+ getAuthSessionEpoch: () => session.epoch,+ hasAuthToken: () => Boolean(session.token),+ },+ "@/features/chat/stores/external-providers-store": {+ useExternalProvidersStore: {+ getState: () => ({ providers: [], setProviders: () => {} }),+ },+ },+ "@/features/chat/sync-external-providers": {+ syncExternalProvidersFromBackend: async () => [],+ },+ "@/features/hub/stores/hf-token-store": {+ hydrateHfTokenFromBackend: async () => {},+ },+ "./reconciliation": {+ runCredentialBootstrap: () => {+ let resolve = () => {};+ const promise = new Promise<void>((done) => {+ resolve = done;+ });+ runs.push({ resolve, promise });+ return promise;+ },+ },+ },+ );+ return { mod, session, runs };+}++test("the gate's first run joins the run the entry started", async () => {+ const { mod, runs } = loadBootstrap();+ mod.startStartupCredentialBootstrap();+ mod.startStartupCredentialBootstrap();+ assert.equal(runs.length, 1, "a second entry call started a second run");+ const gate = mod.takeStartupCredentialBootstrap();+ runs[0].resolve();+ await gate;+ assert.equal(runs.length, 1);+});++test("gate replay shares the startup handoff until it settles", async () => {+ const { mod, runs } = loadBootstrap();+ mod.startStartupCredentialBootstrap();+ const first = mod.takeStartupCredentialBootstrap();+ assert.equal(mod.takeStartupCredentialBootstrap(), first);+ runs[0].resolve();+ await first;+ assert.equal(mod.takeStartupCredentialBootstrap(), null);+ mod.startStartupCredentialBootstrap();+ assert.equal(runs.length, 1, "a second startup run after the first was taken");+});++test("a settled startup run is still the gate's first run", async () => {+ const { mod, runs } = loadBootstrap();+ mod.startStartupCredentialBootstrap();+ runs[0].resolve();+ await runs[0].promise;+ await mod.takeStartupCredentialBootstrap();+ assert.equal(runs.length, 1, "the gate repeated the startup requests");+});++test("no startup run without a token, so the gate runs as before", () => {+ const { mod, session, runs } = loadBootstrap();+ session.token = null;+ mod.startStartupCredentialBootstrap();+ assert.equal(runs.length, 0);+ session.token = "new-session";+ assert.equal(mod.takeStartupCredentialBootstrap(), null);+ assert.equal(runs.length, 0);+});++test("a session change before the gate mounts drops the startup run", () => {+ for (const change of ["sign-in", "sign-out"] as const) {+ const { mod, session, runs } = loadBootstrap();+ mod.startStartupCredentialBootstrap();+ if (change === "sign-in") session.epoch += 1;+ else {+ session.epoch += 1;+ session.token = null;+ }+ assert.equal(mod.takeStartupCredentialBootstrap(), null, change);+ assert.equal(runs.length, 1, change);+ }+});++test("a refreshed access token keeps the startup run", async () => {+ const { mod, runs, session } = loadBootstrap();+ mod.startStartupCredentialBootstrap();+ session.token = "refreshed";+ const gate = mod.takeStartupCredentialBootstrap();+ assert.notEqual(gate, null);+ runs[0].resolve();+ await gate;+ assert.equal(runs.length, 1);+});++test("the entry starts the credential bootstrap only where the gate will run it", () => {+ const main = readSrc("main.tsx");+ const tail = main.slice(main.indexOf("fetchDeviceType().catch(() => undefined);"));+ assert.match(+ tail,+ /if \(\s*!isTauri &&\s*hasSettledAuthSession\(\) &&\s*startPath !== "\/login" &&\s*startPath !== "\/change-password"\s*\) \{\s*startStartupCredentialBootstrap\(\);\s*\}/,+ );+ const root = readSrc("app/routes/__root.tsx");+ const gate = root.slice(+ root.indexOf("function CredentialBootstrapGate("),+ root.indexOf("const CHAT_ONLY_ALLOWED"),+ );+ assert.match(+ gate,+ /void \(\s*takeStartupCredentialBootstrap\(\) \?\? bootstrapPersistedCredentials\(\)\s*\)\.finally\(/,+ );+ assert.equal(gate.match(/takeStartupCredentialBootstrap\(\)/g)?.length, 1);+ for (const page of ["login", "change-password"]) {+ assert.match(readSrc(`app/routes/${page}.tsx`), /isAuthFlow: true/);+ }+});