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 chat page on first use instead of in the startup bundle (#15943)

Daniel Hanc45bfe55a05c
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 9d7fff8806f..195b45ec707 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -3,6 +3,7 @@
import { ImageViewer } from "@/components/image-viewer";
import { useAppShellReadySignal } from "@/components/app-readiness";
+import { LazyImportFailure } from "@/components/lazy-import-boundary";
import { AppSidebar } from "@/components/app-sidebar";
import { CommandPalette } from "@/components/command-palette";
import { SpookyDecorations } from "@/features/halloween/spooky-decorations";
@@ -21,8 +22,9 @@ import {
useIsAccountOwner,
} from "@/features/auth";
import {
- ChatPage,
type ChatSearch,
+ loadChatPage,
+ loadedChatPage,
openFolderAsProject,
startLlamaCppAutoReload,
StopRunningChatsDialog,
@@ -75,10 +77,12 @@ import {
} from "@tanstack/react-router";
import { AnimatePresence, motion } from "motion/react";
import {
+ type ComponentType,
lazy,
type ReactNode,
Suspense,
+ useCallback,
useEffect,
useLayoutEffect,
useMemo,
@@ -161,6 +165,64 @@ function RouteBoundary({
);
}
+type ChatPageProps = { search: ChatSearch; active: boolean };
+type ChatPageAttemptProps = ChatPageProps & { onRetry: () => void };
+
+function ChatPageLoadFailure({
+ active,
+ onRetry,
+}: {
+ active: boolean;
+ onRetry: () => void;
+}) {
+ 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]);
+ const wasActive = useRef(active);
+ useEffect(() => {
+ if (active && !wasActive.current) {
+ onRetry();
+ }
+ wasActive.current = active;
+ }, [active, onRetry]);
+ return (
+ <LazyImportFailure
+ message={t("settings.dialog.panelFailed")}
+ reloadLabel={t("settings.dialog.panelReload")}
+ testId="chat-page-load-failure"
+ className="flex h-full min-h-0 flex-1 flex-col items-center justify-center p-6 text-center text-muted-foreground"
+ />
+ );
+}
+
+// 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.
+function chatPageAttempt(): ComponentType<ChatPageAttemptProps> {
+ return (
+ loadedChatPage() ??
+ lazy<ComponentType<ChatPageAttemptProps>>(() =>
+ loadChatPage().then(
+ (m) => ({ default: m.ChatPage }),
+ () => ({ default: ChatPageLoadFailure }),
+ ),
+ )
+ );
+}
+
+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 (
+ <Suspense fallback={<RouteFallback />}>
+ <Page {...props} onRetry={retry} />
+ </Suspense>
+ );
+}
+
// 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 })),
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 47f7c30ead0..be2f7c4cc63 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -249,6 +249,7 @@ import {
removeCustomSectionWithUndo,
sectionKeyLanding,
useSectionDrag,
+ prefetchChatPage,
} from "@/features/chat";
import {
imeOwnsInputKeydown,
@@ -5949,6 +5950,8 @@ export function AppSidebar() {
if (chatDisabled) return;
openNewChat(null);
}}
+ onPointerEnter={prefetchChatPage}
+ onFocus={prefetchChatPage}
className={cn(
"flex min-w-0 items-center gap-[calc(6px*var(--ui-space-scale,1))] select-none transition-opacity",
chatDisabled && "pointer-events-none",
@@ -6073,6 +6076,7 @@ export function AppSidebar() {
: t("shell.navigation.newChat")
}
spinner={anyChatRunning && !isChatRoute}
+ onIntent={prefetchChatPage}
// On every route: the waiting row can be folded away, behind Show more, or scrolled off.
waiting={
anyChatWaiting
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-render-html.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-render-html.tsx
index 7a208867136..3cdb4b74c50 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-render-html.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-render-html.tsx
@@ -4,6 +4,7 @@
"use client";
import { ArtifactCard } from "@/features/chat";
+import { appSessionStartedAt } from "@/lib/app-session-start";
import {
type ToolCallMessagePartComponent,
useAuiState,
@@ -19,8 +20,6 @@ type RenderHtmlArgs = Record<string, unknown> & {
title?: string;
};
-const RENDER_HTML_SESSION_STARTED_AT = Date.now();
-
const RenderHtmlToolUIImpl: ToolCallMessagePartComponent = ({
args,
result,
@@ -56,7 +55,7 @@ const RenderHtmlToolUIImpl: ToolCallMessagePartComponent = ({
!(isThreadRunning && isMessageRunning) && (isRunning || codeIsStreaming);
const messageCreatedThisSession =
messageCreatedAtMs != null &&
- messageCreatedAtMs >= RENDER_HTML_SESSION_STARTED_AT - 1000;
+ messageCreatedAtMs >= appSessionStartedAt() - 1000;
const shouldAutoOpenArtifact =
(isLiveGeneratingArtifact && (hasCode || isRunning || codeIsStreaming)) ||
(hasCode && messageCreatedThisSession);
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 6e80ef7f23b..a5d816110cc 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -280,6 +280,7 @@ import { useResearchRunStore } from "./stores/research-run-store";
import { useExternalProvidersStore } from "./stores/external-providers-store";
import { buildChatTourSteps } from "./tour";
import type { ChatView, MessageRecord } from "./types";
+import type { ChatSearch } from "./chat-search";
import {
type ComparePairReadState,
checkpointCompareClass,
@@ -2594,22 +2595,6 @@ function ProjectLanding({
);
}
-export type ChatSearch = {
- thread?: string;
- compare?: string;
- new?: string;
- project?: string;
-};
-
-export function validateChatSearch(search: Record<string, unknown>): ChatSearch {
- return {
- thread: typeof search.thread === "string" ? search.thread : undefined,
- compare: typeof search.compare === "string" ? search.compare : undefined,
- new: typeof search.new === "string" ? search.new : undefined,
- project: typeof search.project === "string" ? search.project : undefined,
- };
-}
-
type PendingHubAutoLoad = {
selection: SelectedModelInput;
contextKey: string;
diff --git a/studio/frontend/src/features/chat/chat-search.ts b/studio/frontend/src/features/chat/chat-search.ts
new file mode 100644
index 00000000000..bb69f070957
--- /dev/null
+++ b/studio/frontend/src/features/chat/chat-search.ts
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Separate from chat-page so /chat can validate search without loading the page.
+export type ChatSearch = {
+ thread?: string;
+ compare?: string;
+ new?: string;
+ project?: string;
+};
+
+export function validateChatSearch(
+ search: Record<string, unknown>,
+): ChatSearch {
+ return {
+ thread: typeof search.thread === "string" ? search.thread : undefined,
+ compare: typeof search.compare === "string" ? search.compare : undefined,
+ new: typeof search.new === "string" ? search.new : undefined,
+ project: typeof search.project === "string" ? search.project : undefined,
+ };
+}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index f37492b13d4..b7a61ce0fc2 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -1,7 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-export { ChatPage, validateChatSearch, type ChatSearch } from "./chat-page";
+export { validateChatSearch, type ChatSearch } from "./chat-search";
+export {
+ loadChatPage,
+ loadedChatPage,
+ prefetchChatPage,
+} from "./load-chat-page";
export { isRenderableRenderHtmlToolPart } from "./artifacts/html-fences";
export {
browseFolders,
diff --git a/studio/frontend/src/features/chat/load-chat-page.ts b/studio/frontend/src/features/chat/load-chat-page.ts
new file mode 100644
index 00000000000..4bf4c95deeb
--- /dev/null
+++ b/studio/frontend/src/features/chat/load-chat-page.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+type ChatPageModule = typeof import("./chat-page");
+
+// One shared promise so preload, idle prefetch and mount share a single fetch.
+let chatPageModule: Promise<ChatPageModule> | null = null;
+let loadedModule: ChatPageModule | null = null;
+
+export function loadChatPage(): Promise<ChatPageModule> {
+ if (!chatPageModule) {
+ chatPageModule = import("./chat-page").then(
+ (module) => {
+ loadedModule = module;
+ return module;
+ },
+ (error: unknown) => {
+ chatPageModule = null;
+ throw error;
+ },
+ );
+ }
+ return chatPageModule;
+}
+
+export function loadedChatPage(): ChatPageModule["ChatPage"] | null {
+ return loadedModule?.ChatPage ?? null;
+}
+
+/** A failure is left for the mount to surface. */
+export function prefetchChatPage(): void {
+ loadChatPage().catch(() => undefined);
+}
diff --git a/studio/frontend/src/lib/app-session-start.ts b/studio/frontend/src/lib/app-session-start.ts
new file mode 100644
index 00000000000..ca34a8741e9
--- /dev/null
+++ b/studio/frontend/src/lib/app-session-start.ts
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Marked at startup so lazily loaded chunks date the session from app start.
+let startedAt: number | null = null;
+
+export function markAppSessionStart(): void {
+ startedAt ??= Date.now();
+}
+
+export function appSessionStartedAt(): number {
+ startedAt ??= Date.now();
+ return startedAt;
+}
diff --git a/studio/frontend/src/main.tsx b/studio/frontend/src/main.tsx
index c6d31f20261..e24343267b4 100644
--- a/studio/frontend/src/main.tsx
+++ b/studio/frontend/src/main.tsx
@@ -20,20 +20,35 @@ 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 { loadChatPage, prefetchChatPage } from "./features/chat/load-chat-page";
import {
applyInterfaceScaleBeforeFirstPaint,
useInterfaceScaleStore,
} from "./features/settings/stores/interface-scale-store";
import { initializeLocale } from "./i18n";
import { isTauri } from "./lib/api-base";
+import { markAppSessionStart } from "./lib/app-session-start";
import { setHubSessionRefresh } from "./lib/hf-endpoint";
import { watchInputModality } from "./lib/input-modality";
import { watchMacStrayKeyText } from "./lib/mac-stray-key-text";
import { watchOverlayScrollbarGutter } from "./lib/overlay-scrollbar";
import { watchSpellCheck } from "./lib/spellcheck";
+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" ||
+ (startPath === "/" && hasAuthToken() && getPostAuthRoute() === "/chat")
+ ? loadChatPage().then(
+ () => undefined,
+ () => undefined,
+ )
+ : null;
+
const rootElement = document.getElementById("root");
if (!rootElement) {
throw new Error("Root element not found");
@@ -76,22 +91,40 @@ if (isTauri && /Mac/.test(navigator.platform)) {
watchMacStrayKeyText(window);
}
+const APP_SHELL_READY_EVENT = "unsloth:app-shell-ready";
+const CHAT_PREFETCH_FALLBACK_MS = 3000;
+
function renderApp(): void {
root.render(
<StrictMode>
<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);
+ window.clearTimeout(fallback);
+ prefetchChatPage();
+ };
+ const afterReady = () => {
+ window.setTimeout(prefetchOnce, 0);
+ };
+ window.addEventListener(APP_SHELL_READY_EVENT, afterReady, { once: true });
+ const fallback = window.setTimeout(prefetchOnce, CHAT_PREFETCH_FALLBACK_MS);
+ }
}
const localeInitialization = initializeLocale();
const interfaceScaleInitialization = applyInterfaceScaleBeforeFirstPaint(
useInterfaceScaleStore.getState().scale,
);
-if (typeof localeInitialization !== "string" || isTauri) {
- Promise.all([localeInitialization, interfaceScaleInitialization]).then(
- renderApp,
- );
+if (typeof localeInitialization !== "string" || isTauri || chatPageAtStart) {
+ Promise.all([
+ localeInitialization,
+ interfaceScaleInitialization,
+ chatPageAtStart,
+ ]).then(renderApp);
} else {
renderApp();
}
diff --git a/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts b/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts
index c9a2350756f..bc1de7a1e30 100644
--- a/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts
+++ b/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts
@@ -1214,25 +1214,8 @@ function barrelInitClosure(files: string[]): Set<string> {
* Keyed by file and name with a count, not by line, so unrelated edits do not break it.
*/
const KNOWN_DEEP_CYCLE_READS = new Map<string, number>([
- ["components/assistant-ui/markdown-text.tsx: SEARCH_IMAGE_TAG", 2],
- ["components/assistant-ui/markdown-text.tsx: SearchImageElement", 1],
- ["components/assistant-ui/thread.tsx: CodeExecutionToolUI", 1],
- ["components/assistant-ui/thread.tsx: ImageGenerationToolUI", 1],
- ["components/assistant-ui/thread.tsx: KnowledgeBaseToolUI", 1],
- ["components/assistant-ui/thread.tsx: MarkdownText", 1],
- ["components/assistant-ui/thread.tsx: PythonToolUI", 1],
- ["components/assistant-ui/thread.tsx: Reasoning", 1],
- ["components/assistant-ui/thread.tsx: ReasoningGroup", 1],
- ["components/assistant-ui/thread.tsx: RenderHtmlToolUI", 1],
- ["components/assistant-ui/thread.tsx: Sources", 1],
- ["components/assistant-ui/thread.tsx: TerminalToolUI", 1],
- ["components/assistant-ui/thread.tsx: VideoGenerationToolUI", 1],
- ["components/assistant-ui/thread.tsx: ToolFallback", 1],
- ["components/assistant-ui/thread.tsx: WebSearchToolUI", 1],
["components/ui/sidebar.tsx: SIDEBAR_WIDTH_DEFAULT", 1],
["features/chat/attachment-content.ts: MAX_OPEN_DOCUMENT_ARCHIVE_BYTES", 1],
- ["features/chat/chat-page.tsx: CONVERSATION_MARKDOWN_FORMAT", 1],
- ["features/chat/chat-page.tsx: CONVERSATION_MARKDOWN_LABEL", 1],
["features/chat/presets/preset-load-config.ts: KV_CACHE_DTYPES", 1],
["features/training/stores/training-config-store.ts: TRAINING_CONFIG_PERSISTENCE_NAME", 1],
["features/training/stores/training-config-store.ts: TRAINING_CONFIG_PERSISTENCE_VERSION", 1],
diff --git a/studio/frontend/tests/chat-page-lazy-startup.test.ts b/studio/frontend/tests/chat-page-lazy-startup.test.ts
new file mode 100644
index 00000000000..9b2b9463eec
--- /dev/null
+++ b/studio/frontend/tests/chat-page-lazy-startup.test.ts
@@ -0,0 +1,164 @@
+// 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 { readFileSync, readdirSync, statSync } from "node:fs";
+import { join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import vm from "node:vm";
+
+import { chatPreloadScript } from "../vite-plugin-chat-preload.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const SRC = fileURLToPath(new URL("../src/", import.meta.url));
+
+function sources(dir: string): string[] {
+ return readdirSync(dir).flatMap((name) => {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) return sources(path);
+ return /\.(ts|tsx)$/.test(name) && !/\.(test|check)\.tsx?$/.test(name)
+ ? [path]
+ : [];
+ });
+}
+
+test("nothing imports the chat page statically", () => {
+ const staticImport =
+ /^\s*(import|export)\s+(?!type\b)[^;]*?\bfrom\s+["'](?:\.\/chat-page|@\/features\/chat\/chat-page)["']/m;
+ const importers = sources(SRC)
+ .filter((path) => staticImport.test(readFileSync(path, "utf8")))
+ .map((path) => path.slice(SRC.length));
+ assert.deepEqual(importers, []);
+});
+
+test("the chat route validates its search without loading the chat page", () => {
+ assert.match(
+ readSrc("features/chat/index.ts"),
+ /validateChatSearch[^;]*from "\.\/chat-search"/,
+ );
+ assert.match(
+ readSrc("features/chat/load-chat-page.ts"),
+ /import\("\.\/chat-page"\)/,
+ );
+});
+
+test("the vite build registers the chat preload", () => {
+ const config = readFileSync(
+ new URL("../vite.config.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(config, /chatPagePreload\(\)/);
+});
+
+function preloadsFor(
+ path: string,
+ storage: Record<string, string>,
+ desktop = false,
+): string[] {
+ const appended: string[] = [];
+ const window: Record<string, unknown> = desktop
+ ? { __TAURI_INTERNALS__: {} }
+ : {};
+ const context = {
+ window,
+ location: { pathname: path, protocol: desktop ? "tauri:" : "http:" },
+ localStorage: { getItem: (key: string) => storage[key] ?? null },
+ document: {
+ createElement: () =>
+ ({}) as { rel?: string; href?: string; crossOrigin?: string },
+ head: {
+ appendChild: (link: {
+ rel?: string;
+ href?: string;
+ crossOrigin?: string;
+ }) => {
+ assert.equal(link.rel, "modulepreload");
+ assert.equal(link.crossOrigin, "");
+ appended.push(link.href as string);
+ },
+ },
+ },
+ };
+ vm.runInNewContext(
+ chatPreloadScript(["/assets/a.js", "/assets/b.js"]),
+ context,
+ );
+ return appended;
+}
+
+test("the preload runs only where the app lands on Chat", () => {
+ const files = ["/assets/a.js", "/assets/b.js"];
+ const signedIn = { unsloth_auth_token: "t" };
+ assert.deepEqual(preloadsFor("/chat", {}), files);
+ assert.deepEqual(preloadsFor("/", signedIn), files);
+ assert.deepEqual(preloadsFor("/", {}), []);
+ assert.deepEqual(
+ preloadsFor("/", { ...signedIn, unsloth_auth_must_change_password: "1" }),
+ [],
+ );
+ for (const path of ["/login", "/hub", "/studio", "/chatty", "/chat/x"]) {
+ assert.deepEqual(preloadsFor(path, signedIn), [], path);
+ }
+});
+
+test("the preload follows main.tsx for the single-user Desktop app", () => {
+ const files = ["/assets/a.js", "/assets/b.js"];
+ const pending = {
+ unsloth_auth_token: "t",
+ unsloth_auth_must_change_password: "1",
+ };
+ assert.deepEqual(preloadsFor("/", pending, true), files);
+ assert.deepEqual(
+ preloadsFor(
+ "/",
+ { ...pending, "unsloth.auth-login-mode.v1": "multi" },
+ true,
+ ),
+ [],
+ );
+ assert.deepEqual(preloadsFor("/", { unsloth_auth_token: "t" }, true), files);
+ assert.deepEqual(preloadsFor("/", {}, true), []);
+ assert.deepEqual(
+ preloadsFor("/login", { unsloth_auth_token: "t" }, true),
+ [],
+ );
+});
+
+test("a failed chat page load stays inside the chat area and retries", () => {
+ const root = readSrc("app/routes/__root.tsx");
+ const attempt = root.slice(
+ root.indexOf("function chatPageAttempt("),
+ root.indexOf("function ChatPage("),
+ );
+ assert.match(attempt, /loadedChatPage\(\) \?\?\s*lazy</);
+ assert.match(attempt, /\(\) => \(\{ default: ChatPageLoadFailure \}\)/);
+ assert.match(root, /setPage\(\(\) => chatPageAttempt\(\)\)/);
+ assert.match(
+ root,
+ /<Suspense fallback=\{<RouteFallback \/>\}>\s*<Page \{\.\.\.props\} onRetry=\{retry\} \/>/,
+ );
+ const loader = readSrc("features/chat/load-chat-page.ts");
+ assert.match(loader, /chatPageModule = null;\s*throw error;/);
+});
+
+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"),
+ );
+ assert.doesNotMatch(page, /Boundary/);
+});
+
+test("the chat load failure panel releases the startup screen", () => {
+ const root = readSrc("app/routes/__root.tsx");
+ const failure = root.slice(
+ root.indexOf("function ChatPageLoadFailure("),
+ root.indexOf("function chatPageAttempt("),
+ );
+ assert.match(
+ failure,
+ /const signalReady = useAppShellReadySignal\(\);[^]*?useLayoutEffect\(\(\) => \{\s*signalReady\(\);/,
+ );
+});
diff --git a/studio/frontend/tests/share-run-configs.lifecycle.test.ts b/studio/frontend/tests/share-run-configs.lifecycle.test.ts
index 6db04d2fef1..06a9018574a 100644
--- a/studio/frontend/tests/share-run-configs.lifecycle.test.ts
+++ b/studio/frontend/tests/share-run-configs.lifecycle.test.ts
@@ -3,7 +3,7 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
-import type { ChatSearch } from "../src/features/chat/chat-page.tsx";
+import type { ChatSearch } from "../src/features/chat/chat-search.ts";
import type * as ImportConfig from "../src/features/model-picker/sharing/import-config.ts";
import type * as Lifecycle from "../src/features/model-picker/sharing/link-lifecycle.ts";
import {
diff --git a/studio/frontend/vite-plugin-chat-preload.ts b/studio/frontend/vite-plugin-chat-preload.ts
new file mode 100644
index 00000000000..ec0a252c0aa
--- /dev/null
+++ b/studio/frontend/vite-plugin-chat-preload.ts
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Preloads the chat chunks before the entry on a start that lands on Chat. A file, not inline: script-src is 'self'.
+
+import { createHash } from "node:crypto";
+import type { Plugin } from "vite";
+
+const CHAT_PAGE_MODULE = "/src/features/chat/chat-page.tsx";
+const ENTRY_TAG = /<script type="module"[^>]*\ssrc="[^"]+"[^>]*><\/script>/;
+
+type ChunkLike = {
+ type: "chunk";
+ isEntry: boolean;
+ isDynamicEntry: boolean;
+ imports: string[];
+ moduleIds: string[];
+};
+
+function staticClosure(
+ bundle: Record<string, { type: string }>,
+ roots: string[],
+): Set<string> {
+ const seen = new Set<string>();
+ const stack = [...roots];
+ while (stack.length > 0) {
+ const name = stack.pop() as string;
+ if (seen.has(name)) {
+ continue;
+ }
+ seen.add(name);
+ const chunk = bundle[name] as ChunkLike | undefined;
+ if (chunk?.type === "chunk") {
+ stack.push(...chunk.imports);
+ }
+ }
+ return seen;
+}
+
+export function chatPreloadScript(files: string[]): string {
+ return `(function () {
+ try {
+ var path = location.pathname;
+ // Mirrors main.tsx: hasAuthToken() and getPostAuthRoute() === "/chat", where the single-user
+ // Desktop app goes to Chat even with a password change pending.
+ var singleUserDesktop =
+ ("__TAURI__" in window ||
+ "__TAURI_INTERNALS__" in window ||
+ location.protocol === "tauri:") &&
+ localStorage.getItem("unsloth.auth-login-mode.v1") !== "multi";
+ var landsOnChat =
+ path === "/chat" ||
+ (path === "/" &&
+ Boolean(localStorage.getItem("unsloth_auth_token")) &&
+ (singleUserDesktop ||
+ localStorage.getItem("unsloth_auth_must_change_password") === null));
+ if (!landsOnChat) return;
+ var files = ${JSON.stringify(files)};
+ for (var i = 0; i < files.length; i++) {
+ var link = document.createElement("link");
+ link.rel = "modulepreload";
+ link.crossOrigin = "";
+ link.href = files[i];
+ document.head.appendChild(link);
+ }
+ } catch (error) {}
+})();
+`;
+}
+
+export function chatPagePreload(): Plugin {
+ let base = "/";
+ return {
+ name: "chat-page-preload",
+ apply: "build",
+ enforce: "post",
+ configResolved(config) {
+ base = config.base;
+ },
+ generateBundle(_options, bundle) {
+ const html = bundle["index.html"];
+ if (!html || html.type !== "asset") {
+ return;
+ }
+ const chunks = Object.entries(bundle).filter(
+ (entry): entry is [string, ChunkLike & (typeof bundle)[string]] =>
+ entry[1].type === "chunk",
+ );
+ const page = chunks.find(
+ ([, chunk]) =>
+ chunk.isDynamicEntry &&
+ chunk.moduleIds.some((id) =>
+ id.replaceAll("\\", "/").endsWith(CHAT_PAGE_MODULE),
+ ),
+ );
+ if (!page) {
+ this.error(
+ `no lazy chunk holds ${CHAT_PAGE_MODULE}; Chat would start without its preload`,
+ );
+ }
+ const eager = staticClosure(
+ bundle,
+ chunks.filter(([, chunk]) => chunk.isEntry).map(([name]) => name),
+ );
+ const files = [...staticClosure(bundle, [page[0]])]
+ .filter((name) => !eager.has(name))
+ .sort()
+ .map((name) => `${base}${name}`);
+ const source = chatPreloadScript(files);
+ const hash = createHash("sha256")
+ .update(source)
+ .digest("hex")
+ .slice(0, 8);
+ const fileName = `assets/chat-preload-${hash}.js`;
+ this.emitFile({ type: "asset", fileName, source });
+ const text = String(html.source);
+ if (!ENTRY_TAG.test(text)) {
+ this.error(
+ "index.html has no module entry script to put the Chat preload before",
+ );
+ }
+ html.source = text.replace(
+ ENTRY_TAG,
+ (tag) => `<script src="${base}${fileName}"></script>\n ${tag}`,
+ );
+ },
+ };
+}
diff --git a/studio/frontend/vite.config.ts b/studio/frontend/vite.config.ts
index 8bed23b7a73..7bdfd24faa7 100644
--- a/studio/frontend/vite.config.ts
+++ b/studio/frontend/vite.config.ts
@@ -5,6 +5,7 @@ import path from "node:path";
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { type Plugin, defineConfig } from "vite";
+import { chatPagePreload } from "./vite-plugin-chat-preload";
import { childSelectorOrder } from "./vite-plugin-child-selectors";
import { viewportMediaGate } from "./vite-plugin-viewport-media";
import { previewRuntime } from "./vite-preview-runtime.ts";
@@ -32,7 +33,7 @@ export default defineConfig({
cacheDir: process.env.VITE_TEST_CACHE_DIR || "node_modules/.vite",
// Reasoning's highlighter loads only the grammar it needs in its module worker.
worker: { format: "es" },
- plugins: [react(), tailwindcss(), childSelectorOrder(), viewportMediaGate(), smokeModuleDelay(), previewRuntime()],
+ plugins: [react(), tailwindcss(), childSelectorOrder(), viewportMediaGate(), smokeModuleDelay(), previewRuntime(), chatPagePreload()],
// prevent ancestor PostCSS configs from leaking into installs; Tailwind uses its Vite plugin.
css: {
postcss: {