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 mermaid, node-forge and js-yaml on first use, not at startup (#15565)

Daniel Han37c219c5263a
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index 0013b1f53ba..a93d285ec8a 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -430,8 +430,10 @@ export const BUDGET = {
// with startup code (chat-settings-api, sidebar-organization-keys) split into their own eager chunks, plus the
// mount hook and store wiring: +3,074 B raw / +2,025 B transfer (6,958,762 -> 6,961,836 B raw, 2,099,260 ->
// 2,101,285 B transfer against 9c397197e0, Node 24, 106 -> 109 chunks). Raised by that growth.
- transferBytes: 2_103_210,
- rawBytes: 6_976_629,
+ // Mermaid, node-forge and js-yaml load on first use: -998.5 KB raw / -260.1 KB transfer against 4e673d32e.
+ // Lowered by that, so the headroom stays what it was and a regression of that size fails here.
+ transferBytes: 1_836_868,
+ rawBytes: 5_954_165,
};
// Chunk count is not budgeted: splitting a page out raises it while lowering bytes.
diff --git a/studio/frontend/src/components/assistant-ui/mermaid-plugin.ts b/studio/frontend/src/components/assistant-ui/mermaid-plugin.ts
index 887c8f23c6b..a449b6817fb 100644
--- a/studio/frontend/src/components/assistant-ui/mermaid-plugin.ts
+++ b/studio/frontend/src/components/assistant-ui/mermaid-plugin.ts
@@ -1,7 +1,11 @@
// 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 { createMermaidPlugin } from "@streamdown/mermaid";
+import type {
+ DiagramPlugin,
+ MermaidConfig,
+ MermaidInstance,
+} from "@streamdown/mermaid";
// Mermaid's own secure keys, plus the three CSS strings a `%%{init}%%` directive or front matter
// would otherwise write into the diagram's <style>, where a url() would load from elsewhere.
@@ -17,7 +21,45 @@ const SECURE_KEYS = [
"altFontFamily",
];
-const stock = createMermaidPlugin({ config: { secure: SECURE_KEYS } });
+// Mermaid loads with the first diagram; until then the last config handed in is kept and applied on load.
+let stock: DiagramPlugin | null = null;
+let loading: Promise<DiagramPlugin> | null = null;
+let pendingConfig: MermaidConfig | undefined;
+
+function loadStock(): Promise<DiagramPlugin> {
+ if (!loading) {
+ loading = import("@streamdown/mermaid").then(({ createMermaidPlugin }) => {
+ stock = createMermaidPlugin({ config: { secure: SECURE_KEYS } });
+ if (pendingConfig) {
+ stock.getMermaid(pendingConfig);
+ }
+ pendingConfig = undefined;
+ return stock;
+ });
+ // A failed chunk fetch retries on the next diagram.
+ loading.catch(() => {
+ loading = null;
+ });
+ }
+ return loading;
+}
+
+const lazyInstance: MermaidInstance = {
+ initialize(config) {
+ if (stock) {
+ stock.getMermaid().initialize(config);
+ } else {
+ pendingConfig = config;
+ }
+ },
+ async render(id, source) {
+ const [instance, { stripRemoteDiagramImages }] = await Promise.all([
+ loadStock().then((plugin) => plugin.getMermaid()),
+ import("./mermaid-guard.ts"),
+ ]);
+ return instance.render(id, stripRemoteDiagramImages(source));
+ },
+};
/**
* Replaces the `mermaid` export of @streamdown/mermaid, one instance for every surface that draws
@@ -25,17 +67,14 @@ const stock = createMermaidPlugin({ config: { secure: SECURE_KEYS } });
* `stripRemoteDiagramImages`, which keeps a diagram to the chat's image policy. Package imports
* only: the chat barrel reaches this module while it loads.
*/
-export const mermaid: typeof stock = {
- ...stock,
+export const mermaid: DiagramPlugin = {
+ name: "mermaid",
+ type: "diagram",
+ language: "mermaid",
getMermaid(config) {
- const instance = stock.getMermaid(config);
- return {
- ...instance,
- async render(id, source) {
- // Loaded with the first diagram, not with the app: diagrams already render lazily.
- const { stripRemoteDiagramImages } = await import("./mermaid-guard.ts");
- return instance.render(id, stripRemoteDiagramImages(source));
- },
- };
+ if (config) {
+ lazyInstance.initialize(config);
+ }
+ return lazyInstance;
},
};
diff --git a/studio/frontend/src/features/chat/api/providers-api.ts b/studio/frontend/src/features/chat/api/providers-api.ts
index 43247e3738c..44c04c38d99 100644
--- a/studio/frontend/src/features/chat/api/providers-api.ts
+++ b/studio/frontend/src/features/chat/api/providers-api.ts
@@ -1,7 +1,7 @@
// 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 forge from "node-forge";
+import type forge from "node-forge";
import { authFetch } from "@/features/auth/api";
import { formatFastApiDetail } from "@/lib/format-fastapi-error";
import type { ModelCatalogSnapshotEntry } from "../model-catalog-snapshot";
@@ -126,6 +126,11 @@ export function isProviderKeyRotationError(error: unknown): boolean {
);
}
+// node-forge (~270 KB) loads with the first key encryption, not with the app.
+function loadForge(): Promise<typeof forge> {
+ return import("node-forge").then((module) => module.default);
+}
+
let cachedPublicKeyPem: string | null = null;
let cachedForgeKey: forge.pki.rsa.PublicKey | null = null;
@@ -149,7 +154,8 @@ async function importProviderPublicKey(
if (!forceRefresh && cachedPublicKeyPem === publicKeyPem && cachedForgeKey) {
return cachedForgeKey;
}
- const forgeKey = forge.pki.publicKeyFromPem(publicKeyPem);
+ const { pki } = await loadForge();
+ const forgeKey = pki.publicKeyFromPem(publicKeyPem);
cachedPublicKeyPem = publicKeyPem;
cachedForgeKey = forgeKey;
return forgeKey;
@@ -172,6 +178,7 @@ export async function encryptProviderApiKey(
forceRefresh = false,
): Promise<string> {
const key = await importProviderPublicKey(forceRefresh);
+ const forge = await loadForge();
const aesKey = randomBinaryString(AES_KEY_BYTES);
const nonce = randomBinaryString(NONCE_BYTES);
diff --git a/studio/frontend/src/features/chat/utils/chat-attachment-events.ts b/studio/frontend/src/features/chat/utils/chat-attachment-events.ts
index def2b050c17..9632146c5c2 100644
--- a/studio/frontend/src/features/chat/utils/chat-attachment-events.ts
+++ b/studio/frontend/src/features/chat/utils/chat-attachment-events.ts
@@ -3,8 +3,6 @@
/** Notifies runtimes of Data tab deletions; otherwise a later sync writes the attachment back. */
-import forge from "node-forge";
-
export type ChatAttachmentDeletedEvent = {
messageId: string;
attachmentId: string;
@@ -87,6 +85,7 @@ export async function chatContentPartAttachmentIdFromSignature(
}
}
if (hex === null) {
+ const { default: forge } = await import("node-forge");
const digest = forge.md.sha256.create();
digest.update(signature, "utf8");
hex = digest.digest().toHex();
diff --git a/studio/frontend/src/features/studio/wizard/config-actions.tsx b/studio/frontend/src/features/studio/wizard/config-actions.tsx
index cc1ccc56ed2..c25c638a0cd 100644
--- a/studio/frontend/src/features/studio/wizard/config-actions.tsx
+++ b/studio/frontend/src/features/studio/wizard/config-actions.tsx
@@ -7,11 +7,12 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
+import { useTrainingConfigStore } from "@/features/training";
+// eslint-disable-next-line no-restricted-imports -- through the barrel, js-yaml would load at startup.
import {
parseYamlConfig,
serializeConfigToYaml,
- useTrainingConfigStore,
-} from "@/features/training";
+} from "@/features/training/lib/yaml-config";
import { useT } from "@/i18n";
import { isTauri } from "@/lib/api-base";
import {
diff --git a/studio/frontend/src/features/training/index.ts b/studio/frontend/src/features/training/index.ts
index c2acf9b91d3..549ea047cd8 100644
--- a/studio/frontend/src/features/training/index.ts
+++ b/studio/frontend/src/features/training/index.ts
@@ -92,7 +92,7 @@ export {
emitTrainingRunDeleted,
emitTrainingRunsChanged,
} from "./events";
-export { parseYamlConfig, serializeConfigToYaml } from "./lib/yaml-config";
+// lib/yaml-config is imported directly: re-exporting it here would make js-yaml eager.
export {
type StartValidationResult,
validateTrainingConfig,
diff --git a/studio/frontend/tests/mermaid-plugin-lazy.test.ts b/studio/frontend/tests/mermaid-plugin-lazy.test.ts
new file mode 100644
index 00000000000..cc6c9470a24
--- /dev/null
+++ b/studio/frontend/tests/mermaid-plugin-lazy.test.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Config handed in before mermaid loads must be the one in force at the first render.
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type Plugin = {
+ name: string;
+ type: string;
+ language: string;
+ getMermaid(config?: Record<string, unknown>): {
+ initialize(config: Record<string, unknown>): void;
+ render(id: string, source: string): Promise<{ svg: string }>;
+ };
+};
+
+function harness(options: { failFirstLoad?: boolean } = {}) {
+ const calls: unknown[][] = [];
+ let loads = 0;
+ const stock = {
+ createMermaidPlugin(pluginOptions: unknown) {
+ calls.push(["create", pluginOptions]);
+ const instance = {
+ initialize(config: unknown) {
+ calls.push(["initialize", config]);
+ },
+ async render(id: string, source: string) {
+ calls.push(["render", id, source]);
+ return { svg: `<svg>${source}</svg>` };
+ },
+ };
+ return {
+ name: "mermaid",
+ type: "diagram",
+ language: "mermaid",
+ getMermaid(config?: unknown) {
+ if (config) {
+ instance.initialize(config);
+ }
+ return instance;
+ },
+ };
+ },
+ };
+ const { mermaid } = loadWithStubs<{ mermaid: Plugin }>(
+ new URL("../src/components/assistant-ui/mermaid-plugin.ts", import.meta.url),
+ {
+ get "@streamdown/mermaid"() {
+ loads += 1;
+ if (options.failFirstLoad && loads === 1) throw new Error("chunk failed");
+ return stock;
+ },
+ "./mermaid-guard.ts": { stripRemoteDiagramImages: (source: string) => `guarded:${source}` },
+ },
+ );
+ return { mermaid, calls, loads: () => loads };
+}
+
+test("loading the plugin does not load mermaid", () => {
+ const { mermaid, calls, loads } = harness();
+ assert.deepEqual(
+ { name: mermaid.name, type: mermaid.type, language: mermaid.language },
+ { name: "mermaid", type: "diagram", language: "mermaid" },
+ );
+ mermaid.getMermaid({ theme: "dark" });
+ assert.equal(loads(), 0);
+ assert.deepEqual(calls, []);
+});
+
+test("the last config before the first render is applied before it, then the guarded source renders", async () => {
+ const { mermaid, calls } = harness();
+ mermaid.getMermaid({ theme: "dark" });
+ const instance = mermaid.getMermaid({ theme: "neutral" });
+ assert.deepEqual(await instance.render("m1", "graph TD; A-->B"), {
+ svg: "<svg>guarded:graph TD; A-->B</svg>",
+ });
+ assert.equal(calls[0][0], "create");
+ assert.ok((calls[0][1] as { config: { secure: string[] } }).config.secure.includes("themeCSS"));
+ assert.deepEqual(calls.slice(1), [
+ ["initialize", { theme: "neutral" }],
+ ["render", "m1", "guarded:graph TD; A-->B"],
+ ]);
+});
+
+test("once loaded, a config initializes at once, as the eager plugin did", async () => {
+ const { mermaid, calls } = harness();
+ await mermaid.getMermaid().render("m1", "x");
+ calls.length = 0;
+ mermaid.getMermaid({ theme: "forest" });
+ assert.deepEqual(calls, [["initialize", { theme: "forest" }]]);
+ mermaid.getMermaid().initialize({ theme: "base" });
+ assert.deepEqual(calls[1], ["initialize", { theme: "base" }]);
+});
+
+test("a render with no config handed in initializes nothing itself", async () => {
+ const { mermaid, calls } = harness();
+ await mermaid.getMermaid().render("m1", "x");
+ assert.deepEqual(calls.map((call) => call[0]), ["create", "render"]);
+});
+
+test("a failed load is retried by the next diagram", async () => {
+ const { mermaid, loads } = harness({ failFirstLoad: true });
+ await assert.rejects(mermaid.getMermaid().render("m1", "x"), /chunk failed/);
+ assert.deepEqual(await mermaid.getMermaid().render("m2", "y"), { svg: "<svg>guarded:y</svg>" });
+ assert.equal(loads(), 2);
+});
diff --git a/studio/frontend/tests/startup-lazy-heavy-deps.test.ts b/studio/frontend/tests/startup-lazy-heavy-deps.test.ts
new file mode 100644
index 00000000000..4cd6c75a9f1
--- /dev/null
+++ b/studio/frontend/tests/startup-lazy-heavy-deps.test.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A static import of these from the chat graph puts them back in the eager startup bundle.
+import assert from "node:assert/strict";
+import { readdirSync, readFileSync, statSync } from "node:fs";
+import { join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+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] : [];
+ });
+}
+
+function staticValueImporters(specifier: string): string[] {
+ const escaped = specifier.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
+ const pattern = new RegExp(`^\\s*(import|export)\\s+(?!type\\b)[^;]*?\\bfrom\\s+["']${escaped}["']`, "m");
+ return sources(SRC)
+ .filter((path) => pattern.test(readFileSync(path, "utf8")))
+ .map((path) => path.slice(SRC.length));
+}
+
+test("node-forge is only imported dynamically", () => {
+ assert.deepEqual(staticValueImporters("node-forge"), []);
+});
+
+test("mermaid is only imported dynamically", () => {
+ assert.deepEqual(staticValueImporters("@streamdown/mermaid"), []);
+ assert.deepEqual(staticValueImporters("mermaid"), []);
+});
+
+test("the training barrel does not re-export the YAML helpers", () => {
+ assert.doesNotMatch(readSrc("features/training/index.ts"), /from\s+["']\.\/lib\/yaml-config["']/);
+});