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: budget the JavaScript that runs before the first screen (#8964)
Daniel Han1bf4be70e3f9
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex 87be60fbf3c..94a8d433904 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -211,6 +211,12 @@ jobs:exit 1fi+ # The 75 MB above is the whole artifact, which a lazily loaded page does not+ # make worse. This is the part the user waits through: the entry chunk plus+ # everything Vite preloads for it, fetched and executed before first paint.+ - name: Startup bundle budget+ run: npm run bundle:check+- name: Biome (non-blocking until accumulated drift is cleared)continue-on-error: truerun: npm run biome:checkdiff --git a/studio/frontend/biome.json b/studio/frontend/biome.jsonindex f61e504fa77..18bbabe5bc4 100644--- a/studio/frontend/biome.json+++ b/studio/frontend/biome.json@@ -37,6 +37,16 @@}},"overrides": [+ {+ "include": ["scripts/**"],+ "linter": {+ "rules": {+ "correctness": { "noNodejsModules": "off" },+ "suspicious": { "noConsole": "off", "noConsoleLog": "off" },+ "performance": { "useTopLevelRegex": "off" }+ }+ }+ },{"include": ["vite.config.ts", "eslint.config.js"],"linter": {diff --git a/studio/frontend/package.json b/studio/frontend/package.jsonindex c6a744043e2..095d685b54d 100644--- a/studio/frontend/package.json+++ b/studio/frontend/package.json@@ -12,6 +12,7 @@"lint": "eslint .","preview": "vite preview","test": "node --experimental-strip-types --test \"tests/**/*.test.ts\"",+ "bundle:check": "node --experimental-strip-types scripts/check-bundle-budget.ts","typecheck": "tsc -b --pretty false && tsc -p tsconfig.test.json --pretty false","i18n:check": "node --experimental-strip-types --no-warnings src/i18n/check-parity.ts","i18n:check:strict": "node --experimental-strip-types --no-warnings src/i18n/check-parity.ts --strict",diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsnew file mode 100644index 00000000000..915c1c7bb25--- /dev/null+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -0,0 +1,533 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * Budget for the JavaScript Studio must download, parse and execute before the+ * first screen exists.+ *+ * Two PRs (#8623, #8624) moved 1.5 MB of decoded resources off this path by hand,+ * each measuring it with a throwaway Chromium harness. Nothing then stopped the+ * next static import from putting it back, and nothing noticed when one did: a+ * single `import` of a dialog that is closed on load was carrying 2.4 MB.+ *+ * The eager set is not inferred here. Vite already computes it and writes it into+ * index.html: the entry `<script type="module">` plus one `<link rel="modulepreload">`+ * per chunk in the entry's STATIC import closure. That is exactly what the browser+ * fetches before the app boots. Chunks reachable only through `import()` carry no+ * preload link and are correctly not counted. A parser-blocking classic+ * `<script src>` (public/theme-boot.js) is added to that: it is not Vite's, but it+ * runs before the module graph and so is part of the same wait.+ *+ * Raising a budget is a normal thing to do. Doing it in the same diff as the import+ * that needed it is the point.+ */++import { readFileSync, realpathSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { gzipSync } from "node:zlib";++const HERE = dirname(fileURLToPath(import.meta.url));+const DIST = resolve(HERE, "..", "dist");++/**+ * Measured on the build these were set from, plus a little headroom.+ *+ * Transfer is what crosses the wire. Raw is what the main thread has to parse and+ * execute, which is the part that shows up as a slow launch on a weak machine.+ */+export const BUDGET = {+ // Measured 1,496.2 KB transfer / 5,207.2 KB raw at 17363f8a2.+ transferBytes: 1_600_000,+ rawBytes: 5_500_000,+};++// The chunk count is reported but not budgeted. Splitting a page out of the entry+// raises it while lowering the bytes, which is the behaviour this is trying to+// reward; capping it would penalise the fix.++/**+ * A start tag: lowercased name, and its attributes by lowercased name. A valueless+ * attribute like `defer` is present with an empty-string value, as HTML defines it.+ */+type StartTag = { name: string; attrs: Map<string, string> };++/**+ * ASCII whitespace, which is what separates one attribute from the next.+ *+ * CR is in here for safety only: the parser's input preprocessor turns every CR+ * into an LF before the tokenizer sees it, so a CRLF file cannot behave+ * differently. https://html.spec.whatwg.org/multipage/parsing.html#preprocessing-the-input-stream+ */+const WHITESPACE = new Set(["\t", "\n", "\f", "\r", " "]);++/** First index at or after `from` that is not ASCII whitespace. */+function skipWhitespace(html: string, from: number): number {+ let i = from;+ while (i < html.length && WHITESPACE.has(html[i] as string)) {+ i += 1;+ }+ return i;+}++/** First index at or after `from` that ends a name or an unquoted value. */+function scanUntil(html: string, from: number, stop: string): number {+ let i = from;+ while (+ i < html.length &&+ !WHITESPACE.has(html[i] as string) &&+ !stop.includes(html[i] as string)+ ) {+ i += 1;+ }+ return i;+}++/** One attribute value, from the `=`. Quoted values run to their closing quote. */+function readValue(+ html: string,+ from: number,+): { value: string; next: number } {+ const i = skipWhitespace(html, from + 1);+ const quote = html[i];+ if (quote !== '"' && quote !== "'") {+ const end = scanUntil(html, i, ">"); // Unquoted: ends at whitespace or `>`.+ return { value: html.slice(i, end), next: end };+ }+ const close = html.indexOf(quote, i + 1);+ return close < 0+ ? { value: html.slice(i + 1), next: html.length }+ : { value: html.slice(i + 1, close), next: close + 1 };+}++/**+ * Reads the attributes of one start tag, beginning just past its name, and returns+ * where the tag ends.+ *+ * This is the tokenizer's attribute states, narrowed to what a build artefact can+ * contain. The two rules that matter, and that no regex over the tag text can+ * express:+ *+ * - `>` ends the tag only OUTSIDE a quoted value. Inside one it is ordinary text+ * ("anything else: append the current input character to the current+ * attribute's value"), so `data-note="a > b"` is one attribute and the tag does+ * not end there.+ * https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state+ * - An attribute begins only after whitespace, `/` or a previous value, so a NAME+ * is the only place `async` or `type` can be read from. A value is arbitrary+ * text: `data-mode="load async later"` contains no `async` attribute.+ * https://html.spec.whatwg.org/multipage/parsing.html#before-attribute-name-state+ *+ * Both were live bugs while this searched the tag text instead: the first dropped+ * the entry chunk, the second dropped the parser-blocking script, and in each case+ * enough of the build survived to satisfy the shape guard below, so the gate+ * reported a comfortable pass on a startup path it had not measured.+ */+function readAttributes(+ html: string,+ start: number,+): { attrs: Map<string, string>; end: number; closed: boolean } {+ const attrs = new Map<string, string>();+ let i = start;+ while (i < html.length) {+ // Before attribute name: whitespace is ignored, and `/` (self-closing, or a+ // stray solidus) is not part of a name.+ if (WHITESPACE.has(html[i] as string) || html[i] === "/") {+ i += 1;+ continue;+ }+ if (html[i] === ">") {+ return { attrs, end: i + 1, closed: true };+ }+ const nameEnd = scanUntil(html, i, "/>=");+ const name = html.slice(i, nameEnd).toLowerCase();+ // After attribute name: whitespace may separate the name from its `=`.+ i = skipWhitespace(html, nameEnd);+ let value = "";+ if (html[i] === "=") {+ ({ value, next: i } = readValue(html, i));+ }+ // A repeated attribute is a parse error and the browser keeps the first, so a+ // later `src=` cannot overwrite the one the browser actually fetches.+ if (name && !attrs.has(name)) {+ attrs.set(name, value);+ }+ }+ return { attrs, end: i, closed: false };+}++/**+ * End of a comment, from just past its `<!--`.+ *+ * `<!-->` and `<!--->` close there rather than running on: the comment start and+ * comment start dash states both end the comment on `>`. Read as unterminated, the+ * rest of the file disappears along with the tags in it.+ * https://html.spec.whatwg.org/multipage/parsing.html#comment-start-state+ */+const COMMENT_END = /^-?>|--!?>/;+function endOfComment(html: string, start: number): number {+ const m = COMMENT_END.exec(html.slice(start));+ return m ? start + m.index + m[0].length : html.length;+}++/** End of a script element's raw text, from just past its start tag. */+const SCRIPT_END = /<\/script[\t\n\f\r >/]/i;+function endOfScriptBody(html: string, start: number): number {+ const m = SCRIPT_END.exec(html.slice(start));+ return m ? start + m.index : html.length;+}++/** Tag open state: only an ASCII letter after `<` starts a tag name. */+const TAG_NAME_START = /[a-z]/i;++/**+ * Every start tag in the document, in order.+ *+ * Comments and script bodies are skipped rather than scanned, for the same reason+ * the attribute parser exists: a tag is only a tag where the browser sees one. A+ * `<script src>` commented out during debugging is not downloaded and must not be+ * charged, and a tag written inside a string in an inline script is text.+ * https://html.spec.whatwg.org/multipage/parsing.html#script-data-state+ *+ * A script body ends at the first `</script`, which is the tokenizer's answer+ * unless the body itself contains `<!-- <script`: those escaped states let a+ * `</script>` be text. Erring there reads a bit of script body as markup, so the+ * mistake is to charge a chunk that is not there rather than to miss one. Checked+ * against parse5 over 40,000 generated documents, that is the only case left.+ */+function* startTags(html: string): Generator<StartTag> {+ let i = 0;+ while (i < html.length) {+ const lt = html.indexOf("<", i);+ if (lt < 0) {+ return;+ }+ if (html.startsWith("<!--", lt)) {+ i = endOfComment(html, lt + 4);+ continue;+ }+ if (!TAG_NAME_START.test(html[lt + 1] ?? "")) {+ i = lt + 1;+ continue;+ }+ // Tag name state: the name ends at whitespace, `/` or `>`.+ const nameEnd = scanUntil(html, lt + 1, "/>");+ const name = html.slice(lt + 1, nameEnd).toLowerCase();+ const { attrs, end, closed } = readAttributes(html, nameEnd);+ if (!closed) {+ return; // A tag the file ends in the middle of is never emitted, or fetched.+ }+ yield { name, attrs };+ i = name === "script" ? endOfScriptBody(html, end) : end;+ }+}++/** Reads an attribute off a tag. Absent is undefined; valueless is `""`. */+function attr(tag: StartTag, name: string): string | undefined {+ return tag.attrs.get(name);+}++/** True for a valueless attribute like `defer`, which carries no value to read. */+function hasAttr(tag: StartTag, name: string): boolean {+ return tag.attrs.has(name);+}++/** `rel` is a space-separated token list, and its tokens are case-insensitive. */+function relTokens(tag: StartTag): string[] {+ return (attr(tag, "rel") ?? "").toLowerCase().split(/\s+/).filter(Boolean);+}++/**+ * True when the tag carries `blocking="render"`, which holds the FIRST RENDER back+ * until the resource has been fetched and evaluated.+ *+ * The spec's own reading: "Let value be the value of el's blocking attribute...+ * converted to ASCII lowercase... split on ASCII whitespace", then "An element is+ * potentially render-blocking if its blocking tokens set contains 'render'", and in+ * prepare the script element, "If el is potentially render-blocking, then block+ * rendering on el" -- which is reached for any external script, `async` or not. The+ * async/defer carve-out applies only to what is IMPLICITLY render-blocking.+ * https://html.spec.whatwg.org/multipage/urls-and-fetching.html#blocking-attributes+ * https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element+ *+ * Measured, not assumed: a `<script async blocking="render" src>` held back for two+ * seconds moved first contentful paint from 20 ms to 2,020 ms in Chromium 151 and+ * from 11 ms to 2,009 ms in WebKit 26.5, with Chromium reporting the request's+ * renderBlockingStatus as "blocking". Firefox has not shipped it (bugzil.la/1751383)+ * and simply treats the script as async.+ */+function blocksRender(tag: StartTag): boolean {+ return (attr(tag, "blocking") ?? "")+ .toLowerCase()+ .split(/\s+/)+ .includes("render");+}++/**+ * The eager set, in three buckets, as paths relative to `dist/`.+ *+ * `entry` and `preloads` are Vite's output and stay apart so the caller can tell+ * "Vite stopped emitting preload links" from "this page really does load one+ * chunk": flattened, a build with no preloads reads as a very small app.+ *+ * `blocking` is the classic `<script src>` in `<head>`, which is not Vite's and+ * carries no preload link, but is parser-blocking: it is downloaded and run before+ * the module graph starts. `public/theme-boot.js` is one, and left out it could+ * grow without limit inside a gate whose whole subject is startup JavaScript.+ */+export type EagerSet = {+ entry: string[];+ preloads: string[];+ blocking: string[];+};++/**+ * A `type` the browser still runs as a classic script. An absent type is the same+ * thing; anything else (`importmap`, `application/json`, a template) is not code+ * that runs, and `module` is handled on its own.+ *+ * Exact strings, deliberately. The spec matches this attribute on JavaScript MIME+ * type ESSENCE, so a parameter makes it match nothing: `text/javascript;+ * charset=utf-8` is not evaluated, and Chromium, Firefox and WebKit do not even+ * fetch such a script. Bytes the browser never requests are not startup cost.+ *+ * The whole essence list, not the four anyone would write today. The legacy+ * spellings are not historical trivia: every one of them still executes. Measured+ * in Chromium 151, a script tagged `application/x-javascript`, `text/jscript`,+ * `text/javascript1.5`, `text/livescript`, `application/x-ecmascript` or+ * `text/x-javascript` runs, while `text/javascript; charset=utf-8` and+ * `application/json` do not. The list is frozen, so this does not grow.+ * https://mimesniff.spec.whatwg.org/#javascript-mime-type+ */+const CLASSIC_TYPES = new Set([+ "application/ecmascript",+ "application/javascript",+ "application/x-ecmascript",+ "application/x-javascript",+ "text/ecmascript",+ "text/javascript",+ "text/javascript1.0",+ "text/javascript1.1",+ "text/javascript1.2",+ "text/javascript1.3",+ "text/javascript1.4",+ "text/javascript1.5",+ "text/jscript",+ "text/livescript",+ "text/x-ecmascript",+ "text/x-javascript",+]);++/** Same-origin, build-relative, and not a traversal out of `dist/`. */+function distRelative(url: string | undefined): string | undefined {+ if (!url?.startsWith("/") || url.startsWith("//")) {+ return undefined; // Absent, external, or protocol-relative: not ours to budget.+ }+ const path = url.slice(1).split(/[?#]/)[0];+ return path && !path.split("/").includes("..") ? path : undefined;+}++/** What the browser fetches and runs before the app boots, in document order. */+export function eagerSetFromHtml(html: string): EagerSet {+ const set: EagerSet = { entry: [], preloads: [], blocking: [] };+ const seen = new Set<string>();+ const add = (into: string[], url: string | undefined, prefix = "") => {+ const path = distRelative(url);+ if (!path?.startsWith(prefix) || seen.has(path)) {+ return;+ }+ seen.add(path);+ into.push(path);+ };++ const tags = [...startTags(html)];+ for (const tag of tags.filter((t) => t.name === "script")) {+ const type = attr(tag, "type")?.toLowerCase();+ if (type === "module") {+ // Vite's entry, always one of its own hashed assets.+ add(set.entry, attr(tag, "src"), "assets/");+ } else if (!type || CLASSIC_TYPES.has(type)) {+ // Counts from anywhere in the build, not just assets/. `defer` is included:+ // a deferred script runs after parsing but BEFORE DOMContentLoaded, in+ // document order with the module entry, which is itself deferred -- so it is+ // on exactly the timeline this budgets. Only `async` is out, having no+ // ordering relationship to the first screen at all. `async` also wins when+ // both are present, which is why it is the one tested.+ //+ // Unless it is asked to block rendering, which restores the relationship the+ // exclusion assumes is absent: `blocking="render"` is the documented way to+ // keep a boot script off the parser without letting the unthemed page paint,+ // and it delays the first screen by the whole fetch and evaluation. Not+ // counting it would leave the one thing this gate exists to bound -- bytes+ // between the navigation and the first screen -- unbounded.+ if (!hasAttr(tag, "async") || blocksRender(tag)) {+ add(set.blocking, attr(tag, "src"));+ }+ }+ }+ for (const tag of tags.filter((t) => t.name === "link")) {+ if (relTokens(tag).includes("modulepreload")) {+ add(set.preloads, attr(tag, "href"), "assets/");+ }+ }+ return set;+}++/** Flattened eager set, in the order the browser gets to it. */+export function eagerChunksFromHtml(html: string): string[] {+ const { entry, preloads, blocking } = eagerSetFromHtml(html);+ return [...blocking, ...entry, ...preloads];+}++type Measured = { name: string; raw: number; transfer: number };++/**+ * What the browser actually downloads. The backend gzips the `/assets` mount only+ * (studio/backend/main.py mounts `_AssetGZipMiddleware` there); everything else+ * goes out through a plain FileResponse, so its raw size IS its transfer size.+ */+function transferBytes(name: string, bytes: Buffer): number {+ return name.startsWith("assets/")+ ? gzipSync(bytes, { level: 6 }).byteLength+ : bytes.byteLength;+}++function measure(names: string[]): Measured[] | string {+ const out: Measured[] = [];+ for (const name of names) {+ let bytes: Buffer;+ try {+ bytes = readFileSync(join(DIST, name));+ } catch {+ // index.html names a file the build did not emit. Reporting it rather than+ // a stack trace, because the alternative reading -- that the budget is fine+ // -- is the one that must never be reachable.+ return `dist/index.html references ${name}, which is not in the build`;+ }+ out.push({+ name,+ raw: bytes.byteLength,+ transfer: transferBytes(name, bytes),+ });+ }+ return out;+}++function kb(bytes: number): string {+ return `${(bytes / 1024).toFixed(1)} KB`;+}++function main(): number {+ let html: string;+ try {+ html = readFileSync(join(DIST, "index.html"), "utf8");+ } catch {+ console.error("no dist/index.html -- run `npm run build` first");+ return 2;+ }++ const { entry, preloads, blocking } = eagerSetFromHtml(html);+ const names = [...blocking, ...entry, ...preloads];++ // Counting Vite's own output only: a parser-blocking classic script is not+ // evidence that the module graph was read correctly, so it cannot stand in for+ // the entry when deciding whether this still understands the build.+ //+ // A code-split build of this app is dozens of chunks. One or none means the+ // shape this reads has changed and the number below would be fiction: with+ // `build.modulePreload: false` the links disappear and the entry alone measured+ // 424 KB of a 5,207 KB startup path, reporting 4.8 MB to spare. A comfortable+ // pass is the one answer this must never give by accident.+ //+ // Counting scripts and links together rather than requiring both: when the entry+ // module is nothing but imports, Vite inlines it into one `<script>` per imported+ // chunk and emits no preload links at all, which is a complete measurement. So+ // the total is what decides whether this is a code-split build.+ //+ // But at least one entry is required on top of that total, because preloads+ // without one is not a build shape Vite emits: a modulepreload link exists to+ // announce the entry's static import closure, so links surviving while the entry+ // does not means the entry was read wrong, not that it is absent. Left to the+ // total alone, the app's 48 links carry the guard while the largest single chunk+ // in the startup path silently leaves the measurement -- which is exactly how+ // two mis-parses of this file's own making stayed invisible.+ const fromVite = entry.length + preloads.length;+ if (entry.length === 0 || fromVite < 2) {+ console.error(+ entry.length === 0+ ? `dist/index.html yielded no module entry (and ${preloads.length} preload link(s)), so there is nothing trustworthy to measure here.`+ : `dist/index.html yielded ${fromVite} eager chunk(s) from Vite, so there is nothing trustworthy to measure here.`,+ );+ console.error(+ 'A code-split build served from the site root gives a `<script type="module" src="/assets/...">` plus one `<link rel="modulepreload" href="/assets/...">` per statically imported chunk. If the shape changed on purpose -- `build.modulePreload` turned off, a non-root or relative `base`, a different `build.assetsDir`, `renderBuiltUrl` pointing at a CDN -- teach scripts/check-bundle-budget.ts the new shape rather than leaving a gate that measures nothing.',+ );+ return 2;+ }++ const sized = measure(names);+ if (typeof sized === "string") {+ console.error(sized);+ return 2;+ }+ const measured = sized.sort((a, b) => b.raw - a.raw);+ const raw = measured.reduce((sum, c) => sum + c.raw, 0);+ const transfer = measured.reduce((sum, c) => sum + c.transfer, 0);++ console.log(+ `eager startup JS: ${kb(raw)} raw, ${kb(transfer)} transfer, ${measured.length} chunks`,+ );+ console.log("largest:");+ for (const c of measured.slice(0, 8)) {+ console.log(+ ` ${kb(c.raw).padStart(10)} raw ${kb(c.transfer).padStart(9)} transfer ${c.name}`,+ );+ }++ const over: string[] = [];+ if (transfer > BUDGET.transferBytes) {+ over.push(`transfer ${kb(transfer)} > ${kb(BUDGET.transferBytes)}`);+ }+ if (raw > BUDGET.rawBytes) {+ over.push(`raw ${kb(raw)} > ${kb(BUDGET.rawBytes)}`);+ }++ if (over.length > 0) {+ console.error(`\nover the startup budget: ${over.join(", ")}`);+ console.error(+ "Something is now imported statically that the first screen does not need. " ++ "Either load it on use (React.lazy, lazyRouteComponent, or a dynamic import " ++ "at the point of use), or raise BUDGET in this file in the same PR, with the " ++ "measurement that justifies it.",+ );+ return 1;+ }+ console.log(+ `\nwithin budget (${kb(BUDGET.transferBytes - transfer)} transfer, ${kb(BUDGET.rawBytes - raw)} raw to spare)`,+ );+ return 0;+}++/**+ * True when this file was run, rather than imported by the tests.+ *+ * Compared through realpath on both sides. `import.meta.url` is already the real+ * path (node resolves modules through symlinks), while `process.argv[1]` is the+ * path as typed, so a checkout reached through a symlinked directory made the two+ * disagree and the whole check became a silent no-op that exited 0.+ */+function invokedDirectly(): boolean {+ const argv = process.argv[1];+ if (!argv) {+ return false;+ }+ const here = fileURLToPath(import.meta.url);+ try {+ return realpathSync(argv) === realpathSync(here);+ } catch {+ return resolve(argv) === resolve(here);+ }+}++if (invokedDirectly()) {+ process.exit(main());+}diff --git a/studio/frontend/tests/bundle-budget-cli.test.ts b/studio/frontend/tests/bundle-budget-cli.test.tsnew file mode 100644index 00000000000..7009a93a2f8--- /dev/null+++ b/studio/frontend/tests/bundle-budget-cli.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 parsing tests live in bundle-budget-closure.test.ts. These run the script as+ * CI runs it, because the ways a size gate goes wrong are not parsing bugs: it+ * exits 0 having measured nothing, and nobody reads a passing step.+ *+ * Every case here asserts the exit code AND that a pass came with a measurement+ * printed next to it.+ */++import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { randomBytes } from "node:crypto";+import {+ copyFileSync,+ mkdirSync,+ mkdtempSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { test } from "node:test";+import { fileURLToPath } from "node:url";++const SCRIPT = join(+ dirname(fileURLToPath(import.meta.url)),+ "..",+ "scripts",+ "check-bundle-budget.ts",+);++/**+ * Whatever this process needed to load TypeScript, the child needs too. Reusing+ * the flags rather than naming one keeps this working across the node versions+ * where `--experimental-strip-types` is required, optional, and gone.+ */+const TS_FLAGS = process.execArgv.filter((flag) =>+ /^--(experimental-)?(strip-types|transform-types)/.test(flag),+);++const MEASURED_TWO = /eager startup JS: .* raw, .* transfer, 2 chunks/;++const INDEX_HTML = `<!doctype html><html><head>+<script type="module" crossorigin src="/assets/index-aaa.js"></script>+<link rel="modulepreload" crossorigin href="/assets/react-bbb.js">+<link rel="stylesheet" crossorigin href="/assets/index-ccc.css">+</head><body><div id="root"></div></body></html>`;++/** A checkout-shaped directory: the script, and a dist/ beside it. */+function fixture(+ options: { html?: string | null; bigChunk?: boolean } = {},+): string {+ const root = mkdtempSync(join(tmpdir(), "bundle-budget-"));+ mkdirSync(join(root, "scripts"), { recursive: true });+ copyFileSync(SCRIPT, join(root, "scripts", "check-bundle-budget.ts"));+ const html = options.html === undefined ? INDEX_HTML : options.html;+ if (html !== null) {+ mkdirSync(join(root, "dist", "assets"), { recursive: true });+ writeFileSync(join(root, "dist", "index.html"), html);+ writeFileSync(+ join(root, "dist", "assets", "index-aaa.js"),+ "console.log(1)\n",+ );+ writeFileSync(+ join(root, "dist", "assets", "react-bbb.js"),+ // Incompressible, so raw and gzip both clear the budget when asked to.+ options.bigChunk ? randomBytes(6 * 1024 * 1024) : "export const a = 1\n",+ );+ }+ return root;+}++function runIn(root: string, scriptDir = root) {+ const r = spawnSync(+ process.execPath,+ [...TS_FLAGS, join(scriptDir, "scripts", "check-bundle-budget.ts")],+ { encoding: "utf8" },+ );+ return { code: r.status, out: r.stdout ?? "", err: r.stderr ?? "" };+}++test("a passing run prints the measurement it passed on", () => {+ const { code, out } = runIn(fixture());+ assert.equal(code, 0);+ assert.ok(MEASURED_TWO.test(out), out);+ assert.ok(out.includes("within budget"), out);+});++test("running through a symlinked checkout still runs the check", () => {+ // `import.meta.url` is the real path and `process.argv[1]` is the path as typed,+ // so comparing them literally turned the whole script into a silent exit 0 for+ // anyone whose checkout is reached through a symlink -- which on macOS includes+ // anything under /tmp.+ const root = fixture();+ const link = `${root}-link`;+ try {+ symlinkSync(root, link, "junction");+ } catch {+ return; // Unprivileged Windows without developer mode; nothing to assert.+ }+ const { code, out } = runIn(root, link);+ assert.equal(code, 0);+ assert.ok(+ out.includes("eager startup JS"),+ "the script ran but measured nothing",+ );+});++test("an entry with no modulepreload links is a shape change, not a small app", () => {+ // What `build.modulePreload: false` emits. Flattened into one list it reads as a+ // one-chunk app comfortably inside budget, which is the worst available answer.+ const html = INDEX_HTML.replace(/<link rel="modulepreload"[^>]*>\n?/, "");+ const { code, err } = runIn(fixture({ html }));+ assert.equal(code, 2);+ assert.ok(err.includes("modulepreload"), err);+ assert.ok(err.includes("nothing trustworthy to measure"), err);+});++test("the inlined-entry layout is measured, not rejected", () => {+ // When the entry module is nothing but imports, Vite drops the entry chunk and+ // emits one `<script type="module">` per imported chunk with no preload links.+ // That is a complete eager set, so it has to pass rather than trip the guard.+ const html = `<!doctype html><html><head>+<script type="module" crossorigin src="/assets/index-aaa.js"></script>+<script type="module" crossorigin src="/assets/react-bbb.js"></script>+</head><body></body></html>`;+ const { code, out } = runIn(fixture({ html }));+ assert.equal(code, 0);+ assert.ok(out.includes("2 chunks"), out);+});++test("preload links without a module entry are a shape change, not a measurement", () => {+ // A modulepreload link announces the entry's static import closure, so links+ // surviving while the entry does not means the entry was misread. The links are+ // numerous enough to carry a total-only guard on their own, and the chunk that+ // goes missing is the largest one on the startup path.+ const html = INDEX_HTML.replace(/<script type="module"[^>]*><\/script>\n?/, "");+ const { code, err } = runIn(fixture({ html }));+ assert.equal(code, 2);+ assert.ok(err.includes("no module entry"), err);+ assert.ok(err.includes("nothing trustworthy to measure"), err);+});++test("hrefs that are not site-root asset paths are reported, not silently skipped", () => {+ // `base: "./"` or `base: "/studio/"` emits every href in a form this does not+ // read. Measuring the empty remainder as 0 bytes would pass forever.+ const html = INDEX_HTML.replace(/"\/assets\//g, '"./assets/');+ const { code, err } = runIn(fixture({ html }));+ assert.equal(code, 2);+ assert.ok(err.includes("`base`"), err);+});++test("a referenced chunk missing from the build fails cleanly, not with a stack", () => {+ const html = INDEX_HTML.replace("react-bbb.js", "react-does-not-exist.js");+ const { code, err } = runIn(fixture({ html }));+ assert.equal(code, 2);+ assert.ok(err.includes("react-does-not-exist.js"), err);+ assert.ok(!err.includes("at Object."), "should not be an uncaught exception");+});++test("no build at all exits 2 rather than passing at zero bytes", () => {+ const { code, err } = runIn(fixture({ html: null }));+ assert.equal(code, 2);+ assert.ok(err.includes("npm run build"), err);+});++test("over the budget exits 1 and says what to do about it", () => {+ const { code, out, err } = runIn(fixture({ bigChunk: true }));+ assert.equal(code, 1);+ assert.ok(out.includes("eager startup JS"), out);+ assert.ok(err.includes("over the startup budget"), err);+ assert.ok(err.includes("raise BUDGET"), err);+});diff --git a/studio/frontend/tests/bundle-budget-closure.test.ts b/studio/frontend/tests/bundle-budget-closure.test.tsnew file mode 100644index 00000000000..55781952a23--- /dev/null+++ b/studio/frontend/tests/bundle-budget-closure.test.ts@@ -0,0 +1,342 @@+// 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 startup budget is only worth having if it can fail. These pin the part that+ * decides what counts: a gate that silently measured nothing would pass forever.+ */++import assert from "node:assert/strict";+import { test } from "node:test";++import {+ BUDGET,+ eagerChunksFromHtml,+ eagerSetFromHtml,+} from "../scripts/check-bundle-budget.ts";++const HTML = `<!doctype html><html><head>+<link rel="modulepreload" crossorigin href="/assets/react-DYHJPYbT.js">+<link rel="modulepreload" crossorigin href="/assets/katex-QVq56Mr3.js">+<link rel="stylesheet" href="/assets/index-abc.css">+<script type="module" crossorigin src="/assets/index-DZBgT93Y.js"></script>+</head><body></body></html>`;++test("the eager set is the entry script plus its preloaded chunks", () => {+ assert.deepEqual(eagerChunksFromHtml(HTML), [+ "assets/index-DZBgT93Y.js",+ "assets/react-DYHJPYbT.js",+ "assets/katex-QVq56Mr3.js",+ ]);+});++test("a chunk reached only by import() is not charged to startup", () => {+ // Vite emits no preload link for a dynamic-only chunk, which is the whole+ // mechanism this budget rewards. Naming one in the document body must not+ // pull it in.+ const withDynamic = HTML.replace(+ "</head>",+ '</head><body><script>import("/assets/settings-lazy.js")</script>',+ );+ assert.ok(+ !eagerChunksFromHtml(withDynamic).includes("assets/settings-lazy.js"),+ );+});++test("a classic script is charged to startup, but not as the entry", () => {+ // Parser-blocking, so the browser fetches and runs it before the module graph.+ // public/theme-boot.js is one, and it is not under assets/.+ const html = '<script src="/theme-boot.js"></script>';+ assert.deepEqual(eagerSetFromHtml(html), {+ entry: [],+ preloads: [],+ blocking: ["theme-boot.js"],+ });+});++test("a deferred script is on the startup path, an async one is not", () => {+ // defer runs after parsing but before DOMContentLoaded, in document order with+ // the module entry, which is deferred too. async has no such relationship, and+ // async wins when a tag carries both.+ const html =+ '<script defer src="/late.js"></script>' ++ '<script async src="/whenever.js"></script>' ++ '<script async defer src="/also-whenever.js"></script>';+ assert.deepEqual(eagerChunksFromHtml(html), ["late.js"]);+});++test("an async script that blocks rendering is on the startup path", () => {+ // `blocking="render"` holds the first paint until the script has been fetched and+ // run, which is the timeline this budgets, and it is the documented way to take a+ // boot script off the parser without letting the unthemed page paint. Measured in+ // Chromium 151 and WebKit 26.5: a two-second script moved first contentful paint+ // from ~20 ms to ~2,020 ms. Excluded for being async, it could grow without limit.+ const html =+ '<script async blocking="render" src="/theme-boot.js"></script>' ++ '<script async src="/whenever.js"></script>';+ assert.deepEqual(eagerSetFromHtml(html).blocking, ["theme-boot.js"]);+});++test("the blocking attribute is a token list, matched like the spec matches it", () => {+ // "converted to ASCII lowercase... split on ASCII whitespace", then the set is+ // asked whether it contains "render". So case and neighbouring tokens do not+ // matter, and a token that merely CONTAINS render is a different token.+ const html =+ '<script async blocking=" RENDER " src="/shouty.js"></script>' ++ '<script async blocking="render full" src="/two-tokens.js"></script>' ++ '<script async blocking="rendering" src="/not-a-token.js"></script>' ++ '<script async blocking="prerender" src="/also-not.js"></script>' ++ '<script async blocking="" src="/empty.js"></script>' ++ '<script async data-blocking="render" src="/decoy.js"></script>';+ assert.deepEqual(eagerSetFromHtml(html).blocking, [+ "shouty.js",+ "two-tokens.js",+ ]);+});++test("blocking=render on a non-async script changes nothing", () => {+ // It is already counted for being parser-blocking; saying so twice must not+ // duplicate it, and the attribute must not pull in a type the browser never runs.+ const html =+ '<script blocking="render" src="/theme-boot.js"></script>' ++ '<script blocking="render" src="/theme-boot.js"></script>' ++ '<script type="application/json" blocking="render" src="/data.js"></script>';+ assert.deepEqual(eagerSetFromHtml(html).blocking, ["theme-boot.js"]);+});++test("a script type is judged on whether the browser runs it", () => {+ const html =+ '<script type="application/javascript" src="/legacy.js"></script>' ++ '<script type="importmap" src="/map.js"></script>' ++ '<script type="application/json" src="/data.js"></script>';+ assert.deepEqual(eagerChunksFromHtml(html), ["legacy.js"]);+});++test("a MIME type with parameters is not a script the browser runs", () => {+ // The type attribute is matched on JavaScript MIME type ESSENCE, so a parameter+ // makes it match nothing. Chromium, Firefox and WebKit all decline to fetch it,+ // and bytes the browser never requests are not startup cost.+ const html = '<script type="text/javascript; charset=utf-8" src="/never.js">';+ assert.deepEqual(eagerChunksFromHtml(html), []);+});++test("every JavaScript MIME essence the browser still runs is counted", () => {+ // The legacy spellings are not dead letters: measured in Chromium 151, every one+ // of these executes. Counting only the four anyone writes today dropped the rest+ // while the entry and preloads kept the shape guard satisfied.+ const essences = [+ "application/ecmascript",+ "application/javascript",+ "application/x-ecmascript",+ "application/x-javascript",+ "text/ecmascript",+ "text/javascript",+ "text/javascript1.0",+ "text/javascript1.1",+ "text/javascript1.2",+ "text/javascript1.3",+ "text/javascript1.4",+ "text/javascript1.5",+ "text/jscript",+ "text/livescript",+ "text/x-ecmascript",+ "text/x-javascript",+ ];+ for (const [i, essence] of essences.entries()) {+ const html = `<script type="${essence}" src="/boot-${i}.js"></script>`;+ assert.deepEqual(+ eagerChunksFromHtml(html),+ [`boot-${i}.js`],+ `${essence} should be counted`,+ );+ assert.deepEqual(+ eagerChunksFromHtml(html.replace(essence, essence.toUpperCase())),+ [`boot-${i}.js`],+ `${essence} should match case-insensitively`,+ );+ }+});++test("a type that only looks like JavaScript is not counted", () => {+ // The guard against the list above turning into "anything with `script` in it".+ for (const type of [+ "text/javascript1.6",+ "application/javascript-ish",+ "text/jscript.encode",+ "application/json",+ "importmap",+ ]) {+ assert.deepEqual(+ eagerChunksFromHtml(`<script type="${type}" src="/nope.js"></script>`),+ [],+ `${type} should not be counted`,+ );+ }+});++test("a decoy data- attribute cannot shadow the real one", () => {+ // A hyphen is a word boundary, so a `\b`-anchored `type` reads `data-type`+ // first, drops the entry, and leaves the preloads to satisfy the shape guard.+ const html =+ '<script data-type="metadata" type="module" src="/assets/entry.js"></script>' ++ '<script data-src="/decoy.js" type="module" src="/assets/second.js"></script>' ++ '<link data-rel="x" rel="modulepreload" data-href="/assets/no.js" href="/assets/yes.js">';+ assert.deepEqual(eagerSetFromHtml(html), {+ entry: ["assets/entry.js", "assets/second.js"],+ preloads: ["assets/yes.js"],+ blocking: [],+ });+});++test("`async` inside a value is not an async attribute", () => {+ // An attribute begins only after whitespace, so `async` can only be read from a+ // NAME. Searching the tag text found it in this value, dropped the only+ // parser-blocking script, and left the entry and preloads to pass the shape+ // guard -- so theme-boot.js could grow without ever showing up.+ const html =+ '<script data-mode="load async later" src="/theme-boot.js"></script>' ++ '<script data-flags="async defer" src="/also-blocking.js"></script>';+ assert.deepEqual(eagerSetFromHtml(html).blocking, [+ "theme-boot.js",+ "also-blocking.js",+ ]);+});++test("an attribute whose name ends in async is not async", () => {+ const html = '<script data-async src="/theme-boot.js"></script>';+ assert.deepEqual(eagerSetFromHtml(html).blocking, ["theme-boot.js"]);+});++test("a quoted value containing `>` does not end the tag", () => {+ // `>` is ordinary text inside a quoted value; the tag really does continue. Read+ // as the end of the tag, `type` and `src` fall off the entry, and the preloads+ // alone still satisfy the shape guard -- a pass measured without the entry chunk.+ const html =+ '<script data-note="a > b" type="module" src="/assets/entry.js"></script>' ++ "<script data-note='b > c' src='/theme-boot.js'></script>" ++ '<link data-note="x > y" rel="modulepreload" href="/assets/react-x.js">';+ assert.deepEqual(eagerSetFromHtml(html), {+ entry: ["assets/entry.js"],+ preloads: ["assets/react-x.js"],+ blocking: ["theme-boot.js"],+ });+});++test("an unquoted value ends at whitespace, not at the first likely-looking token", () => {+ const html =+ "<script type=module src=/assets/entry.js></script>" ++ "<link rel=modulepreload href=/assets/react-x.js>";+ assert.deepEqual(eagerSetFromHtml(html), {+ entry: ["assets/entry.js"],+ preloads: ["assets/react-x.js"],+ blocking: [],+ });+});++test("a tag name is matched whole, so scriptx is not a script", () => {+ const html =+ '<scriptx src="/nope.js"></scriptx><linkx rel="modulepreload" href="/assets/nope.js">';+ assert.deepEqual(eagerChunksFromHtml(html), []);+});++test("a commented-out tag is not downloaded, so it is not charged", () => {+ const html =+ '<!-- <script src="/disabled.js"></script> -->' ++ '<script src="/theme-boot.js"></script>';+ assert.deepEqual(eagerSetFromHtml(html).blocking, ["theme-boot.js"]);+});++test("a tag written inside an inline script is text, not a tag", () => {+ const html =+ '<script>document.write(\'<link rel="modulepreload" href="/assets/nope.js">\')</script>' ++ '<link rel="modulepreload" href="/assets/react-x.js">';+ assert.deepEqual(eagerSetFromHtml(html).preloads, ["assets/react-x.js"]);+});++test("a truncated file does not invent a tag out of its last line", () => {+ // EOF inside a tag is a parse error and the tag token is never emitted, so the+ // browser does not fetch it either.+ assert.deepEqual(eagerChunksFromHtml('<script src="/half-written.js'), []);+});++test("a cross-origin classic script is not ours to budget", () => {+ const html =+ '<script src="https://cdn.example/x.js"></script>' ++ '<script src="//cdn.example/y.js"></script>';+ assert.deepEqual(eagerChunksFromHtml(html), []);+});++test("stylesheets and non-asset hrefs are not counted", () => {+ const html =+ '<link rel="modulepreload" href="https://cdn.example/x.js">' ++ '<link rel="stylesheet" href="/assets/index.css">';+ assert.deepEqual(eagerChunksFromHtml(html), []);+});++test("a chunk preloaded twice is counted once", () => {+ const html = `${HTML}<link rel="modulepreload" href="/assets/react-DYHJPYbT.js">`;+ const names = eagerChunksFromHtml(html);+ assert.equal(new Set(names).size, names.length);+});++test("an unrecognisable document yields nothing, so the gate reports a shape change", () => {+ // check-bundle-budget exits 2 on an empty set rather than passing at 0 bytes.+ assert.deepEqual(eagerChunksFromHtml("<!doctype html><html></html>"), []);+});++test("the budget is a real number, not a placeholder", () => {+ assert.ok(BUDGET.transferBytes > 0 && BUDGET.rawBytes > BUDGET.transferBytes);+});++test("the entry and its preloads stay distinguishable", () => {+ // check-bundle-budget refuses to report a number when either half is missing,+ // which it cannot do if the two are flattened together before it looks.+ assert.deepEqual(eagerSetFromHtml(HTML), {+ entry: ["assets/index-DZBgT93Y.js"],+ preloads: ["assets/react-DYHJPYbT.js", "assets/katex-QVq56Mr3.js"],+ blocking: [],+ });+});++test("a build with no preload links is not mistaken for a one-chunk app", () => {+ // `build.modulePreload: false` emits exactly this: the entry, no links. Read as+ // a flat list it looks like a 424 KB startup path with 4.8 MB to spare.+ const entryOnly = HTML.replace(/<link rel="modulepreload"[^>]*>\n?/g, "");+ assert.deepEqual(eagerSetFromHtml(entryOnly).preloads, []);+ assert.equal(eagerSetFromHtml(entryOnly).entry.length, 1);+});++test("tag and attribute matching is case-insensitive, as HTML is", () => {+ const shouty = HTML.replace(+ /<link rel="modulepreload" crossorigin href="([^"]+)">/g,+ '<LINK REL="MODULEPRELOAD" CROSSORIGIN HREF="$1">',+ ).replace(/<script type="module"/, '<SCRIPT TYPE="Module"');+ assert.deepEqual(eagerChunksFromHtml(shouty), eagerChunksFromHtml(HTML));+});++test("attribute order, quoting and self-closing syntax do not matter", () => {+ const rewritten = HTML.replace(+ /<link rel="modulepreload" crossorigin href="([^"]+)">/g,+ "<link href='$1' crossorigin rel='modulepreload' />",+ ).replace(+ /<script type="module" crossorigin src="([^"]+)"><\/script>/,+ "<script crossorigin src=$1 type=module></script>",+ );+ assert.deepEqual(eagerChunksFromHtml(rewritten), eagerChunksFromHtml(HTML));+});++test("rel is a token list, so a second token does not hide the preload", () => {+ const html = '<link rel="preload modulepreload" href="/assets/react-x.js">';+ assert.deepEqual(eagerSetFromHtml(html).preloads, ["assets/react-x.js"]);+});++test("a tag broken across lines is still read", () => {+ const html = '<link\n rel="modulepreload"\n href="/assets/react-x.js"\n>';+ assert.deepEqual(eagerSetFromHtml(html).preloads, ["assets/react-x.js"]);+});++test("the chunk count is not budgeted", () => {+ // Splitting a page out of the entry raises the count while lowering the bytes.+ // A cap here would fail the very change the gate exists to encourage.+ assert.ok(!("chunks" in BUDGET));+});