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
Share the frontend source readers and the shell test harness (#10500)
Daniel Han502ace800f48
diff --git a/studio/frontend/tests/advanced-settings-preference.test.ts b/studio/frontend/tests/advanced-settings-preference.test.tsindex b1a390c3abe..7a65d029763 100644--- a/studio/frontend/tests/advanced-settings-preference.test.ts+++ b/studio/frontend/tests/advanced-settings-preference.test.ts@@ -2,11 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {installLocalStorageFake,+ readSrcAsync,registerBundlerResolver,} from "./helpers/kit.ts";@@ -195,10 +195,7 @@ test("a toggle in another tab lands even with no panel mounted to hear it", () =});test("the reset in Settings > General clears it", async () => {- const source = await readFile(- new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("features/settings/tabs/general-tab.tsx");const start = source.indexOf("const PREFS_KEYS");const keys = source.slice(start, source.indexOf("];", start));assert.ok(diff --git a/studio/frontend/tests/api-load-settings-refetch-sequencing.test.ts b/studio/frontend/tests/api-load-settings-refetch-sequencing.test.tsindex d9ef78135ec..cd0ffee46d6 100644--- a/studio/frontend/tests/api-load-settings-refetch-sequencing.test.ts+++ b/studio/frontend/tests/api-load-settings-refetch-sequencing.test.ts@@ -8,18 +8,12 @@// server no longer has, and it stays there until the panel remounts. Last issued wins.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";--const SOURCE = readFileSync(- fileURLToPath(- new URL(- "../src/features/api-monitor/components/saved-model-settings.tsx",- import.meta.url,- ),- ),- "utf8",++import { readSrc } from "./helpers/kit.ts";++const SOURCE = readSrc(+ "features/api-monitor/components/saved-model-settings.tsx",);const LOAD = SOURCE.slice(diff --git a/studio/frontend/tests/appearance-accent-vars.test.ts b/studio/frontend/tests/appearance-accent-vars.test.tsindex 80731cae34c..64acf7d1b20 100644--- a/studio/frontend/tests/appearance-accent-vars.test.ts+++ b/studio/frontend/tests/appearance-accent-vars.test.ts@@ -2,9 +2,10 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";+import { readSrc } from "./helpers/kit.ts";+/** Minimal <html> stand-in: the applier only needs style, attributes, classes. */function stubDocument() {const vars = new Map<string, string>();@@ -253,10 +254,7 @@ test("a narrow valid band between custom and elevated surfaces is not skipped",});test("resize-handle glows follow the primary token", () => {- const source = readFileSync(- new URL("../src/components/ui/resizable.tsx", import.meta.url),- "utf8",- );+ const source = readSrc("components/ui/resizable.tsx");assert.doesNotMatch(source, /rgba\(23,\s*184,\s*139/);assert.equal(source.match(/color-mix\(in_srgb,var\(--primary\)_[0-9]+%,transparent\)/g)diff --git a/studio/frontend/tests/attachment-source-cost.test.ts b/studio/frontend/tests/attachment-source-cost.test.tsindex 4f5c9c08418..e859fb5a5be 100644--- a/studio/frontend/tests/attachment-source-cost.test.ts+++ b/studio/frontend/tests/attachment-source-cost.test.ts@@ -8,10 +8,9 @@// AttachmentThumb and AttachmentPreviewDialog each mount the hook.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -29,10 +28,6 @@ const ATTACHMENT_ID_ROOT_KEY_RE =const PASTED_TEXT_ID_KEY_RE =/<PastedTextAttachmentUI\s+key=\{attachmentId\}/;-function source(path: string): string {- return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");-}-function audioAttachment(payload: string) {return {attachment: {@@ -75,7 +70,7 @@ test("the attachment selector does not rebuild the audio payload per run", () =>* DialogContent once the dialog opens, which is where the join belongs.*/test("the audio data URL is built in the dialog, not on every attachment tile", () => {- const hook = source("components/assistant-ui/use-attachment-source.ts");+ const hook = readSrc("components/assistant-ui/use-attachment-source.ts");assert.doesNotMatch(hook,/attachmentAudioSrc/,@@ -83,7 +78,7 @@ test("the audio data URL is built in the dialog, not on every attachment tile",);assert.match(hook, /audio: source\.audio/);- const preview = source("components/assistant-ui/attachment-preview.tsx");+ const preview = readSrc("components/assistant-ui/attachment-preview.tsx");const body = preview.indexOf("const AttachmentAudioBody");assert.notEqual(body, -1, "no component owns the audio data URL");assert.equal(@@ -125,7 +120,7 @@ test("the attachment selector still resolves text and image attachments", () =>// every stateful preview/source branch needs the attachment identity as its own// reset boundary.test("attachment previews reset when an index is reused for another attachment", () => {- const attachment = source("components/assistant-ui/attachment.tsx");+ const attachment = readSrc("components/assistant-ui/attachment.tsx");const ui = attachment.slice(attachment.indexOf("const AttachmentUI"),attachment.indexOf("const AttachmentRemove"),@@ -151,7 +146,7 @@ test("attachment previews reset when an index is reused for another attachment",// throw leaves the user with no file and no reason, as the audio adapter's// toast avoids.test("the pdf and docx adapters refuse an oversized file at add, with a toast", () => {- const provider = source("features/chat/runtime-provider.tsx");+ const provider = readSrc("features/chat/runtime-provider.tsx");// DOCX also has to clear its per-part bound at add: a small archive can// still declare a part mammoth would inflate past the cap.diff --git a/studio/frontend/tests/audio-catalog-decodable.test.ts b/studio/frontend/tests/audio-catalog-decodable.test.tsindex 0c773678d7c..3d8c8e85b33 100644--- a/studio/frontend/tests/audio-catalog-decodable.test.ts+++ b/studio/frontend/tests/audio-catalog-decodable.test.ts@@ -9,23 +9,12 @@// codec, which is the same shape as the Orpheus defect this PR was opened to fix.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const catalog = readFileSync(- new URL(- "../src/features/model-picker/components/model-selector/model-catalog.ts",- import.meta.url,- ),- "utf8",-);-const policy = readFileSync(- new URL(- "../src/features/model-picker/components/model-selector/audio-picker-policy.ts",- import.meta.url,- ),- "utf8",-);+import { readSrc, readText } from "./helpers/kit.ts";++const catalog = readSrc("features/model-picker/components/model-selector/model-catalog.ts");+const policy = readSrc("features/model-picker/components/model-selector/audio-picker-policy.ts");// The codec-backed families decoded by the legacy main-slot backend. Native// architecture families are checked against their dedicated backend below.@@ -53,10 +42,7 @@ test("the curated audio catalog offers no model the backend cannot decode", () =});test("the five native catalog rows are wired to native backend architectures", () => {- const backend = readFileSync(- new URL("../../backend/core/inference/native_audio.py", import.meta.url),- "utf8",- ).toLowerCase();+ const backend = readText("../../backend/core/inference/native_audio.py").toLowerCase();for (const repo of ["bosonai/higgs-tts-2-3b-base","openmoss-team/moss-tts-local-transformer-v1.5",diff --git a/studio/frontend/tests/audio-generation-stop.test.ts b/studio/frontend/tests/audio-generation-stop.test.tsindex 45982b264cc..e305f27e219 100644--- a/studio/frontend/tests/audio-generation-stop.test.ts+++ b/studio/frontend/tests/audio-generation-stop.test.ts@@ -2,13 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const source = readFileSync(- new URL("../src/features/audio/audio-page.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/audio/audio-page.tsx");test("generation exposes Stop only while the request controller can abort", () => {assert.match(diff --git a/studio/frontend/tests/audio-hidden-stt-seed.test.ts b/studio/frontend/tests/audio-hidden-stt-seed.test.tsindex 3ae76083cfd..6cd0f8fd0fc 100644--- a/studio/frontend/tests/audio-hidden-stt-seed.test.ts+++ b/studio/frontend/tests/audio-hidden-stt-seed.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -10,12 +9,10 @@ import {taskPickerRowMatches,} from "../src/features/model-picker/components/model-selector/audio-picker-policy.ts";-const pickerSource = readFileSync(- new URL(- "../src/features/model-picker/components/model-selector/pickers.tsx",- import.meta.url,- ),- "utf8",+import { readSrc } from "./helpers/kit.ts";++const pickerSource = readSrc(+ "features/model-picker/components/model-selector/pickers.tsx",);const row = {diff --git a/studio/frontend/tests/audio-mode-task-filter.test.ts b/studio/frontend/tests/audio-mode-task-filter.test.tsindex 0a20cb8a206..2dd00e40687 100644--- a/studio/frontend/tests/audio-mode-task-filter.test.ts+++ b/studio/frontend/tests/audio-mode-task-filter.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {sttEngineForRepoId,@@ -11,14 +10,10 @@ import {} from "../src/features/audio/stt-artifacts.ts";import { detectCapabilities } from "../src/features/model-picker/components/model-selector/model-capabilities.ts";-const pageSource = readFileSync(- new URL("../src/features/audio/audio-page.tsx", import.meta.url),- "utf8",-);-const catalogSource = readFileSync(- new URL("../src/features/audio/catalog.ts", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const pageSource = readSrc("features/audio/audio-page.tsx");+const catalogSource = readSrc("features/audio/catalog.ts");test("Hub discovery follows the active audio mode", () => {assert.match(diff --git a/studio/frontend/tests/audio-model-eject.test.ts b/studio/frontend/tests/audio-model-eject.test.tsindex ef6b1f542c2..5a961a916e5 100644--- a/studio/frontend/tests/audio-model-eject.test.ts+++ b/studio/frontend/tests/audio-model-eject.test.ts@@ -2,20 +2,12 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const source = readFileSync(- new URL("../src/features/audio/audio-page.tsx", import.meta.url),- "utf8",-);-const adapterSource = readFileSync(- new URL(- "../src/features/chat/adapters/studio-model-dictation-adapter.ts",- import.meta.url,- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/audio/audio-page.tsx");+const adapterSource = readSrc("features/chat/adapters/studio-model-dictation-adapter.ts");test("Audio exposes the shared picker eject action only while idle", () => {assert.match(diff --git a/studio/frontend/tests/audio-page-policy.test.ts b/studio/frontend/tests/audio-page-policy.test.tsindex 49dcf2de7f3..c1e6029cf1f 100644--- a/studio/frontend/tests/audio-page-policy.test.ts+++ b/studio/frontend/tests/audio-page-policy.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -30,14 +29,10 @@ import {sttSelectionReady,} from "../src/features/audio/audio-page-policy.ts";-const audioPageSource = readFileSync(- new URL("../src/features/audio/audio-page.tsx", import.meta.url),- "utf8",-);-const chatApiSource = readFileSync(- new URL("../src/features/chat/api/chat-api.ts", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const audioPageSource = readSrc("features/audio/audio-page.tsx");+const chatApiSource = readSrc("features/chat/api/chat-api.ts");test("mode transitions cancel generation but wait for non-cancellable work", () => {assert.equal(canTransitionAudioMode(null), true);diff --git a/studio/frontend/tests/audio-picker-policy.test.ts b/studio/frontend/tests/audio-picker-policy.test.tsindex aaca8a73a69..b41451f36bd 100644--- a/studio/frontend/tests/audio-picker-policy.test.ts+++ b/studio/frontend/tests/audio-picker-policy.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -118,13 +117,9 @@ import {groupForRepoId,} from "../src/features/model-picker/components/model-selector/model-catalog.ts";-const pickerSource = readFileSync(- new URL(- "../src/features/model-picker/components/model-selector/pickers.tsx",- import.meta.url,- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const pickerSource = readSrc("features/model-picker/components/model-selector/pickers.tsx");test("fresh Hub pipeline metadata routes media picks before stale inventory", () => {assert.equal(@@ -775,13 +770,7 @@ test("the audio page asks the GGUF-aware TTS predicate for trained rows", () =>// GGUF_TTS_AUDIO_TYPES leaves csm out because llama.cpp has no CSM decoder. Calling// isTtsAudioType without the flag answered off the wider Transformers list and offered// a csm GGUF export that fails at load.- const source = readFileSync(- new URL(- "../src/features/audio/audio-page.tsx",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("features/audio/audio-page.tsx");assert.match(source,/isTtsAudioType\(\s*lora\.audio_type,\s*lora\.export_type === "gguf",?\s*\)/,diff --git a/studio/frontend/tests/audio-stt-download-fallback.test.ts b/studio/frontend/tests/audio-stt-download-fallback.test.tsindex 4463219c913..856f4d644b4 100644--- a/studio/frontend/tests/audio-stt-download-fallback.test.ts+++ b/studio/frontend/tests/audio-stt-download-fallback.test.ts@@ -2,20 +2,12 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const source = readFileSync(- new URL("../src/features/audio/audio-page.tsx", import.meta.url),- "utf8",-);-const mirrorSource = readFileSync(- new URL(- "../src/features/settings/lib/stt-download-mirror.ts",- import.meta.url,- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/audio/audio-page.tsx");+const mirrorSource = readSrc("features/settings/lib/stt-download-mirror.ts");test("STT download polling uses the available engine fallback", () => {assert.match(diff --git a/studio/frontend/tests/audio-transcript-lifecycle.test.ts b/studio/frontend/tests/audio-transcript-lifecycle.test.tsindex e1f3958aa38..6ade4dc889f 100644--- a/studio/frontend/tests/audio-transcript-lifecycle.test.ts+++ b/studio/frontend/tests/audio-transcript-lifecycle.test.ts@@ -2,13 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const source = readFileSync(- new URL("../src/features/audio/audio-page.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/audio/audio-page.tsx");test("a transcription run clears the previous result before it awaits", () => {// Download .txt used to save A's words under B's name.diff --git a/studio/frontend/tests/audio-tts-download-manager.test.ts b/studio/frontend/tests/audio-tts-download-manager.test.tsindex 8fd87ece04b..a3cee716446 100644--- a/studio/frontend/tests/audio-tts-download-manager.test.ts+++ b/studio/frontend/tests/audio-tts-download-manager.test.ts@@ -2,13 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const source = readFileSync(- new URL("../src/features/audio/audio-page.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/audio/audio-page.tsx");test("uncached remote TTS GGUFs stage the exact file through the shared manager", () => {assert.match(source, /useStagedDownload\(\{\s*scopeId: "audio"/);diff --git a/studio/frontend/tests/audio-utils.test.ts b/studio/frontend/tests/audio-utils.test.tsindex b5e77e05686..3843d16b253 100644--- a/studio/frontend/tests/audio-utils.test.ts+++ b/studio/frontend/tests/audio-utils.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -11,11 +10,10 @@ import {getAudioSizeError,} from "../src/lib/audio-utils.ts";+import { readText } from "./helpers/kit.ts";+test("chat audio uses the backend's raw upload limit", () => {- const backendLimits = readFileSync(- new URL("../../backend/utils/upload_limits.py", import.meta.url),- "utf8",- );+ const backendLimits = readText("../../backend/utils/upload_limits.py");const limitMb = Number(backendLimits.match(/STT_AUDIO_RAW_MAX_BYTES\s*=\s*(\d+)\s*\*\s*_BYTES_PER_MB/,diff --git a/studio/frontend/tests/auto-compaction-settings.test.ts b/studio/frontend/tests/auto-compaction-settings.test.tsindex c58b29dccbf..746e2351e66 100644--- a/studio/frontend/tests/auto-compaction-settings.test.ts+++ b/studio/frontend/tests/auto-compaction-settings.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {DEFAULT_CONTEXT_POLICY,@@ -12,6 +11,8 @@ import {sanitizeCompactionHeadroomRatio,} from "../src/features/chat/utils/auto-compaction.ts";+import { readSrc } from "./helpers/kit.ts";+test("the default preserves the server context policy", () => {assert.equal(DEFAULT_CONTEXT_POLICY, "inherit");assert.equal(compactionStyleValue("inherit", 0.25), "inherit");@@ -111,9 +112,6 @@ test("unsupported headroom ratios snap to an exposed choice", () => {});test("the chat adapter sends compaction fields through the shared helper", () => {- const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );+ const adapter = readSrc("features/chat/api/chat-adapter.ts");assert.match(adapter, /ggufCompactionRequestFields\(/);});diff --git a/studio/frontend/tests/auto-load-cpu-fallback-toast.test.ts b/studio/frontend/tests/auto-load-cpu-fallback-toast.test.tsindex 00e14bad1ec..53c6ec84c14 100644--- a/studio/frontend/tests/auto-load-cpu-fallback-toast.test.ts+++ b/studio/frontend/tests/auto-load-cpu-fallback-toast.test.ts@@ -2,11 +2,9 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -25,12 +23,7 @@ const CALL_SITES = /\n\s*showAutoLoadSuccess\([\s\S]*?\);/g;// Asserted against the source like the other chat-adapter tests: importing the// module would drag in the stores and the toast layer for one closure.-const source = readFileSync(- fileURLToPath(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- ),- "utf8",-);+const source = readSrc("features/chat/api/chat-adapter.ts");// The wording and the warn-vs-success choice used to be written inline in// showAutoLoadSuccess, and this file matched them there by substring. Both nowdiff --git a/studio/frontend/tests/cancelled-turn-history-prune.test.ts b/studio/frontend/tests/cancelled-turn-history-prune.test.tsindex b1e92a78f1b..1a67dee378a 100644--- a/studio/frontend/tests/cancelled-turn-history-prune.test.ts+++ b/studio/frontend/tests/cancelled-turn-history-prune.test.ts@@ -2,13 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const adapter = readSrc("features/chat/api/chat-adapter.ts");test("a Stop with no output is recognised by what it puts on the wire", () => {assert.match(adapter, /function isAbandonedAssistantTurn\(/);diff --git a/studio/frontend/tests/chat-adapter-scan-cost.test.ts b/studio/frontend/tests/chat-adapter-scan-cost.test.tsindex 173345df90d..234cbbc9aaf 100644--- a/studio/frontend/tests/chat-adapter-scan-cost.test.ts+++ b/studio/frontend/tests/chat-adapter-scan-cost.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { createSegmentedAssistantText } from "../src/features/chat/utils/incremental-assistant-content.ts";@@ -16,6 +15,8 @@ import {stripTrailingTemplatePlaceholder,} from "../src/features/chat/utils/trailing-template-placeholder.ts";+import { readSrc } from "./helpers/kit.ts";+/*** Complexity tests, not timing tests: they count the characters the scans look* at, so they say the same thing on an idle laptop and a loaded CI box. Every@@ -363,10 +364,7 @@ test("the whole per-arrival path is linear in the reply length", () => {// ------------------------------------------------------------ source pins ----const ADAPTER = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",-);+const ADAPTER = readSrc("features/chat/api/chat-adapter.ts");/** Drop comments, so a commented-out call cannot satisfy a search. */function withoutComments(source: string): string {diff --git a/studio/frontend/tests/chat-autoscroll-frame-budget.test.ts b/studio/frontend/tests/chat-autoscroll-frame-budget.test.tsindex f367343a625..dbd949b1c61 100644--- a/studio/frontend/tests/chat-autoscroll-frame-budget.test.ts+++ b/studio/frontend/tests/chat-autoscroll-frame-budget.test.ts@@ -12,16 +12,11 @@// assert the cheap path, and assert the expensive one is gone.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const HOOK = readFileSync(- new URL(- "../src/components/assistant-ui/use-intent-aware-autoscroll.tsx",- import.meta.url,- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const HOOK = readSrc("components/assistant-ui/use-intent-aware-autoscroll.tsx");/** The body of `tick`, which is the only place the chain re-arms. */function tickBody(): string {diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.tsindex 4bc90008edb..6052d78525e 100644--- a/studio/frontend/tests/chat-continuation.test.ts+++ b/studio/frontend/tests/chat-continuation.test.ts@@ -2,13 +2,16 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();+const THREAD = readSrc("components/assistant-ui/thread.tsx");+const CHAT_ADAPTER = readSrc("features/chat/api/chat-adapter.ts");+const AUTO_CONTINUE_RUN_KEEPER = readSrc("features/chat/utils/auto-continue-run-keeper.ts");+const {AUTO_CONTINUE_CONTINUED_TTL_MS,AUTO_CONTINUE_LEASE_KEY,@@ -1406,17 +1409,13 @@ test("a claim whose run was never issued is left to lapse, not held", async () =// the message until this one closes. So the message has to still be there before anything// is held. Pinned at the source, since there is no renderer here -- the same way// composer-keystroke-subscription-budget.test.ts pins its seams.- const thread = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );- const claimed = thread.indexOf(+ const claimed = THREAD.indexOf('claimAutoContinue(messageId, runThreadId ?? "")',);assert.notEqual(claimed, -1, "the claim moved; this test needs rewriting");- const branch = thread.slice(+ const branch = THREAD.slice(claimed,- thread.indexOf("held-elsewhere", claimed),+ THREAD.indexOf("held-elsewhere", claimed),);const guard = branch.search(/messages\.some\(/);@@ -1455,28 +1454,18 @@ test("a losing claim does not follow the row onto the next branch", () => {// re-renders this component rather than remounting it, and the flag set for the message// that lost carried over onto a message nobody has claimed at all -- no automatic// continuation for it, for as long as that row lives.- const rows = readFileSync(- new URL(- "../src/components/assistant-ui/progressive-messages.tsx",- import.meta.url,- ),- "utf8",- );+ const rows = readSrc("components/assistant-ui/progressive-messages.tsx");assert.match(rows,/<MessageByIndexProvider key=\{index\}/,"rows are no longer keyed by index; this test needs rewriting",);- const thread = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );- const start = thread.indexOf("const ContinueMessageBarForLastMessage");+ const start = THREAD.indexOf("const ContinueMessageBarForLastMessage");assert.notEqual(start, -1, "the bar moved; this test needs rewriting");- const component = thread.slice(+ const component = THREAD.slice(start,- thread.indexOf("const WebSearchToolUIConfirmable", start),+ THREAD.indexOf("const WebSearchToolUIConfirmable", start),);const state =/const \[(\w+), (set\w+)\] = useState<string \| null>\(null\)/.exec(@@ -1536,17 +1525,13 @@ test("a claim taken for a run that was never issued is given back", async () =>test("the bar rolls its claim back when it issues no run", () => {// The behaviour above, pinned where it has to be called from: the early return that// decided no run would be issued.- const thread = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );- const claimed = thread.indexOf(+ const claimed = THREAD.indexOf('claimAutoContinue(messageId, runThreadId ?? "")',);assert.notEqual(claimed, -1, "the claim moved; this test needs rewriting");- const branch = thread.slice(+ const branch = THREAD.slice(claimed,- thread.indexOf("held-elsewhere", claimed),+ THREAD.indexOf("held-elsewhere", claimed),);const guard = branch.search(/messages\.some\(/);const hold = branch.indexOf("holdAutoContinueRun(");@@ -1667,36 +1652,25 @@ test("the keeper is wired to the failure the adapter already reports", () => {// There is exactly one signal for a run that failed on its way out, and it is not a// deadline: the adapter wrapper catches everything `adapter.run` throws and announces it// per thread. Pinned at both ends, since neither side is exercised by a unit test.- const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );- const wrapper = adapter.slice(adapter.indexOf("yield* adapter.run(args)"));+ const wrapper = CHAT_ADAPTER.slice(CHAT_ADAPTER.indexOf("yield* adapter.run(args)"));assert.match(wrapper,/catch \(error\) \{[\s\S]*notifyPromptQueueRunFailed\(/,"the adapter no longer reports a failed run per thread; this test needs rewriting",);- const wiring = readFileSync(- new URL(- "../src/features/chat/utils/auto-continue-run-keeper.ts",- import.meta.url,- ),- "utf8",- );assert.match(- wiring,+ AUTO_CONTINUE_RUN_KEEPER,/PROMPT_QUEUE_RUN_FAILED_EVENT/,"nothing settles a hold whose run failed before it started",);assert.match(- wiring,+ AUTO_CONTINUE_RUN_KEEPER,/keeper\.failed\(/,"the failure has to reach the keeper",);assert.doesNotMatch(- wiring,+ AUTO_CONTINUE_RUN_KEEPER,/setTimeout\(/,"a deadline here is the arming timeout coming back, which lapses live continuations",);@@ -1890,11 +1864,7 @@ test("only the gate's own tokens are read as a refusal", () => {test("the gate's pulse is tagged where it is fired and read where it matters", () => {// Neither end is exercised by a unit test: the adapter's gate is deep inside a run, and// the keeper's real signal reads a zustand store. Pinned at both ends instead.- const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );- const gate = adapter.slice(adapter.indexOf("const imageGateReason ="));+ const gate = CHAT_ADAPTER.slice(CHAT_ADAPTER.indexOf("const imageGateReason ="));assert.match(gate,/const gateOwner = createImageGateRunOwner\(\)/,@@ -1906,20 +1876,13 @@ test("the gate's pulse is tagged where it is fired and read where it matters", ("the pulse compare mode waits on is still fired under that token",);- const wiring = readFileSync(- new URL(- "../src/features/chat/utils/auto-continue-run-keeper.ts",- import.meta.url,- ),- "utf8",- );assert.match(- wiring,+ AUTO_CONTINUE_RUN_KEEPER,/isImageGateRunOnly\(state\.runOwnerByThreadId\[threadId\]\)/,"the keeper is arming holds on a request the gate refused to send",);assert.doesNotMatch(- wiring,+ AUTO_CONTINUE_RUN_KEEPER,/setTimeout\(/,"a deadline here is the arming timeout coming back, which lapses live continuations",);@@ -1945,6 +1908,7 @@ const { createContinuationMerger } = await import("../src/features/chat/utils/continuation.ts");+const REASONING ="Okay, so the user is asking about how to structure the migration. " +"Let me think through this carefully step by step before answering. " +diff --git a/studio/frontend/tests/chat-menus-nonmodal.test.ts b/studio/frontend/tests/chat-menus-nonmodal.test.tsindex 11d57a38c0c..325076fbd6a 100644--- a/studio/frontend/tests/chat-menus-nonmodal.test.ts+++ b/studio/frontend/tests/chat-menus-nonmodal.test.ts@@ -11,6 +11,8 @@ import test from "node:test";import ts from "typescript";+import { readSrc } from "./helpers/kit.ts";+/** Keyed by a marker on the menu's trigger. */const NON_MODAL = [["components/assistant-ui/thread.tsx", "thinkEffortAriaLabel({"],@@ -114,9 +116,6 @@ test("the dismiss guard is mounted only while the menu is open", () => {test("the menu content still animates out, which is why the guard is gated", () => {// Without the animation the gate above is merely harmless; revisit it rather than drop it.- const content = readFileSync(- new URL("../src/components/ui/dropdown-menu.tsx", import.meta.url),- "utf8",- );+ const content = readSrc("components/ui/dropdown-menu.tsx");assert.match(content, /data-closed:animate-out/);});diff --git a/studio/frontend/tests/chat-model-residency.test.ts b/studio/frontend/tests/chat-model-residency.test.tsindex 044ab7a3b91..6883ce7e9cd 100644--- a/studio/frontend/tests/chat-model-residency.test.ts+++ b/studio/frontend/tests/chat-model-residency.test.ts@@ -7,11 +7,14 @@// prompt came back a bare 400. These pin the rule the header now uses.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { chatModelLoaded } from "../src/features/chat/lib/chat-model-loaded.ts";+import { readSrc } from "./helpers/kit.ts";++const USE_CHAT_MODEL_RUNTIME = readSrc("features/chat/hooks/use-chat-model-runtime.ts");+const PICKED = "unsloth/Qwen3.5-9B-GGUF";test("a resident model reads as loaded", () => {@@ -81,21 +84,12 @@ test("nothing picked is never loaded", () => {// Reading the rule out of the source keeps the prop wired to the fix: the first// attempt at this changed a different modelLoaded and the tick never moved.test("the selector's tick asks the caller, and defaults to the old rule", () => {- const source = readFileSync(- new URL(- "../src/features/model-picker/components/model-selector.tsx",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("features/model-picker/components/model-selector.tsx");assert.match(source,/const isLoaded = selected !== "" && \(loaded \?\? true\)/,);- const page = readFileSync(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );+ const page = readSrc("features/chat/chat-page.tsx");assert.match(page,/loaded=\{chatModelLoaded\(\{/,@@ -121,13 +115,7 @@ test("a model still loading is not loaded yet", () => {// Model hub cards kept it after an eviction, which is the same lie in a second// and third spot.test("the picker's Loaded badge asks residency, not the selection", () => {- const pickers = readFileSync(- new URL(- "../src/features/model-picker/components/model-selector/pickers.tsx",- import.meta.url,- ),- "utf8",- );+ const pickers = readSrc("features/model-picker/components/model-selector/pickers.tsx");assert.match(pickers, /const chatLoadedModelId = chatModelLoaded\(\{/);assert.match(pickers,@@ -152,49 +140,35 @@ test("the picker's Loaded badge asks residency, not the selection", () => {// and sending to the model the picker still named answered 400 "No model// loaded". Waiting for the settle left that gap open for the whole load.test("another runtime loading re-reads the chat status", () => {- const hook = readFileSync(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- "utf8",- );- assert.match(hook, /subscribeModelLifecycle\(\(\{ runtime \}\) => \{/);+ assert.match(USE_CHAT_MODEL_RUNTIME, /subscribeModelLifecycle\(\(\{ runtime \}\) => \{/);// Dictation holds no GPU ownership, so it is the one that stays excluded.- assert.match(hook, /if \(runtime === "chat" \|\| runtime === "stt"\) return;/);+ assert.match(USE_CHAT_MODEL_RUNTIME, /if \(runtime === "chat" \|\| runtime === "stt"\) return;/);assert.doesNotMatch(- hook,+ USE_CHAT_MODEL_RUNTIME,/if \(loading \|\| runtime === "chat"\) return;/,"the settle-only guard is what left the picker naming an evicted model",);assert.match(- hook,+ USE_CHAT_MODEL_RUNTIME,/void refresh\(\{\s*includeLoras: false,\s*externalChatSlotLoad: runtime === "tts",\s*\}\)/,);// And the branch it feeds still clears residency.- assert.match(hook, /residentCheckpoint: null,/);+ assert.match(USE_CHAT_MODEL_RUNTIME, /residentCheckpoint: null,/);});// Dimming the tick and the badges was not enough: the model's name on its own// reads as "this is my model", and sending to it returns a bare 400. An// eviction now drops the pick, exactly as a server-side unload already did.test("an eviction drops the pick, not just the loaded marks", () => {- const hook = readFileSync(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- "utf8",- );// Anchored on the branch, not on the file: other catches sit above it now.// chatActiveModel, not status.active_model: this branch owns the resident-TTS case too.// Matched loosely: the guard has been reflowed across lines, and a literal that// stopped matching would slice nothing and fail on an empty string instead.- const branchStart = hook.search(/\} else if \(\s*!chatActiveModel/);+ const branchStart = USE_CHAT_MODEL_RUNTIME.search(/\} else if \(\s*!chatActiveModel/);assert.notEqual(branchStart, -1, "the eviction branch anchor no longer matches");- const branch = hook.slice(+ const branch = USE_CHAT_MODEL_RUNTIME.slice(branchStart,- hook.indexOf("} catch (error) {", branchStart),+ USE_CHAT_MODEL_RUNTIME.indexOf("} catch (error) {", branchStart),);assert.match(branch, /clearCheckpoint\(\)/);// A first speech-only status is definitive too: it must clear a persisted@@ -207,13 +181,7 @@ test("an eviction drops the pick, not just the loaded marks", () => {// The pick survives a load, which also reports no active model while it runs.test("the eviction clear reads the store's loading flag", () => {- const store = readFileSync(- new URL(- "../src/features/chat/stores/chat-runtime-store.ts",- import.meta.url,- ),- "utf8",- );+ const store = readSrc("features/chat/stores/chat-runtime-store.ts");assert.match(store, /modelLoading: boolean;/);assert.match(store, /set\(\{ modelLoading: true \}\)/);});diff --git a/studio/frontend/tests/chat-only-route-guard.test.ts b/studio/frontend/tests/chat-only-route-guard.test.tsindex 37558008903..423b1d6a905 100644--- a/studio/frontend/tests/chat-only-route-guard.test.ts+++ b/studio/frontend/tests/chat-only-route-guard.test.ts@@ -15,10 +15,11 @@// message unreachable in the only cases it exists for.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-const src = await readFile(new URL("../src/app/routes/__root.tsx", import.meta.url), "utf8");+import { readSrcAsync } from "./helpers/kit.ts";++const src = await readSrcAsync("app/routes/__root.tsx");function lift(pattern: RegExp, what: string): string {const found = pattern.exec(src);diff --git a/studio/frontend/tests/chat-remembers-its-model.test.ts b/studio/frontend/tests/chat-remembers-its-model.test.tsindex b51d79d3cc3..e48f0f689aa 100644--- a/studio/frontend/tests/chat-remembers-its-model.test.ts+++ b/studio/frontend/tests/chat-remembers-its-model.test.ts@@ -8,11 +8,11 @@// be honoured.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {installLocalStorageFake,+ readText,registerBundlerResolver,} from "./helpers/kit.ts";@@ -39,22 +39,18 @@ const { wantsDownloadManagerStaging } = await import("../src/features/chat/utils/model-download-staging.ts");-function read(path: string): string {- return readFileSync(new URL(path, import.meta.url), "utf8");-}--const notice = read("../src/features/chat/components/chat-model-notice.tsx");-const page = read("../src/features/chat/chat-page.tsx");-const runtimeProvider = read("../src/features/chat/runtime-provider.tsx");-const adapter = read("../src/features/chat/api/chat-adapter.ts");-const chatApi = read("../src/features/chat/api/chat-api.ts");-const types = read("../src/features/chat/types.ts");-const thread = read("../src/components/assistant-ui/thread.tsx");-const researchPanel = read(+const notice = readText("../src/features/chat/components/chat-model-notice.tsx");+const page = readText("../src/features/chat/chat-page.tsx");+const runtimeProvider = readText("../src/features/chat/runtime-provider.tsx");+const adapter = readText("../src/features/chat/api/chat-adapter.ts");+const chatApi = readText("../src/features/chat/api/chat-api.ts");+const types = readText("../src/features/chat/types.ts");+const thread = readText("../src/components/assistant-ui/thread.tsx");+const researchPanel = readText("../src/features/chat/components/research-activity-panel.tsx",);-const artifact = read("../src/features/chat/artifacts/artifact-surface.tsx");-const switchSource = read(+const artifact = readText("../src/features/chat/artifacts/artifact-surface.tsx");+const switchSource = readText("../src/features/chat/components/chat-model-notice-switch.ts",);@@ -382,7 +378,7 @@ test("a queued empty-model send backfills its resolved GGUF variant", () => {/queuedEmptyModelRuntime !== null[\s\S]{0,100}queuedEmptyModelRuntime\.activeGgufVariant[\s\S]{0,80}liveRuntime\.activeGgufVariant/,);assert.match(adapter, /params\.checkpoint,\s*runtime\.activeGgufVariant/);- const queuedSettings = read(+ const queuedSettings = readText("../src/features/chat/utils/queued-chat-run-settings.ts",);assert.match(queuedSettings, /"activeGgufVariant"/);diff --git a/studio/frontend/tests/chat-run-checkpoint-lifecycle.test.ts b/studio/frontend/tests/chat-run-checkpoint-lifecycle.test.tsindex 78fdbce62e8..d5ce41090ef 100644--- a/studio/frontend/tests/chat-run-checkpoint-lifecycle.test.ts+++ b/studio/frontend/tests/chat-run-checkpoint-lifecycle.test.ts@@ -76,6 +76,34 @@ function createFakeTimers() {};}+function recordingScheduler(+ options: Parameters<typeof createRunCheckpointScheduler>[1] = {},+) {+ const clock = createFakeTimers();+ const saved: string[] = [];+ const scheduler = createRunCheckpointScheduler(+ async (threadId) => {+ saved.push(threadId);+ },+ { intervalMs: INTERVAL, timers: clock.timers, ...options },+ );+ return { clock, saved, scheduler };+}++/** The same, over a save the test settles by hand. */+function gatedScheduler(+ options: Parameters<typeof createRunCheckpointScheduler>[1] = {},+) {+ const clock = createFakeTimers();+ const gated = createGatedSave();+ const scheduler = createRunCheckpointScheduler(gated.save, {+ intervalMs: INTERVAL,+ timers: clock.timers,+ ...options,+ });+ return { clock, gated, scheduler };+}+/** A save whose settling the test controls. */function createGatedSave() {const releases: Array<() => void> = [];@@ -107,18 +135,9 @@ function createGatedSave() {// pin; what it may no longer do is run without any bound at all.test("omitting isActive keeps checkpointing until the staleness bound, not forever", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- {- intervalMs: INTERVAL,- timers: clock.timers,- maxDurationMs: 20 * INTERVAL,- },- );+ const { clock, saved, scheduler } = recordingScheduler({+ maxDurationMs: 20 * INTERVAL,+ });scheduler.start("thread-a");for (let i = 0; i < 12; i += 1) {@@ -144,19 +163,10 @@ test("omitting isActive keeps checkpointing until the staleness bound, not forev});test("an isActive that always returns true behaves like no isActive at all", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- {- intervalMs: INTERVAL,- timers: clock.timers,- isActive: () => true,- maxDurationMs: 20 * INTERVAL,- },- );+ const { clock, saved, scheduler } = recordingScheduler({+ isActive: () => true,+ maxDurationMs: 20 * INTERVAL,+ });scheduler.start("thread-a");for (let i = 0; i < 12; i += 1) {@@ -301,27 +311,22 @@ test("checkpoints continue while active and end with one final save when the run});test("an isActive that throws is treated as not running", async () => {- const clock = createFakeTimers();- let saves = 0;- const scheduler = createRunCheckpointScheduler(- async () => {- saves += 1;- },- {- intervalMs: INTERVAL,- timers: clock.timers,- isActive: () => {- throw new Error("thread record is gone");- },+ const { clock, saved, scheduler } = recordingScheduler({+ isActive: () => {+ throw new Error("thread record is gone");},- );+ });scheduler.start("thread-a");await clock.advance(INTERVAL);- assert.equal(saves, 1, "a throwing probe must still yield the final save");+ assert.equal(+ saved.length,+ 1,+ "a throwing probe must still yield the final save",+ );assert.equal(clock.pending(), 0, "a throwing probe must end the schedule");await clock.advance(INTERVAL * 10);- assert.equal(saves, 1);+ assert.equal(saved.length, 1);});test("a thread can be started again after it self-terminated", async () => {@@ -431,11 +436,7 @@ test("the final save is still attempted when the save itself rejects", async ()});test("a stop arriving while the final save is in flight does not rearm", async () => {- const clock = createFakeTimers();- const gated = createGatedSave();- const scheduler = createRunCheckpointScheduler(gated.save, {- intervalMs: INTERVAL,- timers: clock.timers,+ const { clock, gated, scheduler } = gatedScheduler({isActive: () => false,});@@ -452,18 +453,9 @@ test("a stop arriving while the final save is in flight does not rearm", async (});test("the final save is given the thread id that went inactive", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- {- intervalMs: INTERVAL,- timers: clock.timers,- isActive: (threadId) => threadId !== "thread-b",- },- );+ const { clock, saved, scheduler } = recordingScheduler({+ isActive: (threadId) => threadId !== "thread-b",+ });scheduler.start("thread-b");await clock.advance(INTERVAL);@@ -472,18 +464,9 @@ test("the final save is given the thread id that went inactive", async () => {});test("one thread going inactive does not stop its sibling", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- {- intervalMs: INTERVAL,- timers: clock.timers,- isActive: (threadId) => threadId === "thread-a",- },- );+ const { clock, saved, scheduler } = recordingScheduler({+ isActive: (threadId) => threadId === "thread-a",+ });scheduler.start("thread-a");scheduler.start("thread-b");@@ -694,14 +677,7 @@ test("a throwing probe and a throwing save still terminate cleanly", async () =>// D. flushAlltest("flushAll checkpoints every started thread", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");scheduler.start("thread-b");@@ -712,14 +688,7 @@ test("flushAll checkpoints every started thread", async () => {});test("flushAll does not checkpoint a stopped thread", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");scheduler.start("thread-b");@@ -731,24 +700,17 @@ test("flushAll does not checkpoint a stopped thread", async () => {});test("flushAll leaves the pending timer armed and on its original schedule", async () => {- const clock = createFakeTimers();- let saves = 0;- const scheduler = createRunCheckpointScheduler(- async () => {- saves += 1;- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");await clock.advance(INTERVAL);- assert.equal(saves, 1);+ assert.equal(saved.length, 1);const armedBefore = clock.pending();assert.equal(armedBefore, 1);scheduler.flushAll();await flushMicrotasks();- assert.equal(saves, 2, "the flush is an extra checkpoint");+ assert.equal(saved.length, 2, "the flush is an extra checkpoint");assert.equal(clock.pending(),armedBefore,@@ -757,13 +719,13 @@ test("flushAll leaves the pending timer armed and on its original schedule", asyawait clock.advance(INTERVAL - 1);assert.equal(- saves,+ saved.length,2,"the flush must not have pulled the next checkpoint forward",);await clock.advance(1);assert.equal(- saves,+ saved.length,3,"the next checkpoint must still land on its original deadline",);@@ -771,28 +733,16 @@ test("flushAll leaves the pending timer armed and on its original schedule", asy});test("flushAll with no started threads is a no-op", async () => {- const clock = createFakeTimers();- let saves = 0;- const scheduler = createRunCheckpointScheduler(- async () => {- saves += 1;- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.flushAll();await flushMicrotasks();- assert.equal(saves, 0);+ assert.equal(saved.length, 0);assert.equal(clock.pending(), 0);});test("flushAll during an in-flight checkpoint still issues the extra save", async () => {- const clock = createFakeTimers();- const gated = createGatedSave();- const scheduler = createRunCheckpointScheduler(gated.save, {- intervalMs: INTERVAL,- timers: clock.timers,- });+ const { clock, gated, scheduler } = gatedScheduler();scheduler.start("thread-a");await clock.advance(INTERVAL);@@ -818,21 +768,18 @@ test("flushAll during an in-flight checkpoint still issues the extra save", asyn});test("flushAll after stopAll saves nothing", async () => {- const clock = createFakeTimers();- let saves = 0;- const scheduler = createRunCheckpointScheduler(- async () => {- saves += 1;- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");scheduler.start("thread-b");scheduler.stopAll();scheduler.flushAll();await flushMicrotasks();- assert.equal(saves, 0, "unmount must not be followed by a flush write");+ assert.equal(+ saved.length,+ 0,+ "unmount must not be followed by a flush write",+ );});test("a synchronous throw inside flushAll does not break the scheduler", async () => {@@ -903,14 +850,7 @@ test("flushAll does not consult isActive", async () => {});test("repeated flushAll calls each write once per thread", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");scheduler.flushAll();@@ -942,14 +882,7 @@ test("flushAll ignores a thread that already self-terminated", async () => {});test("flushAll writes a thread that was restarted after stopAll", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");scheduler.stopAll();@@ -967,12 +900,7 @@ test("the checkpoint interval constant is still eight seconds", () => {});test("quiet time is measured after the checkpoint settles, not on a fixed cadence", async () => {- const clock = createFakeTimers();- const gated = createGatedSave();- const scheduler = createRunCheckpointScheduler(gated.save, {- intervalMs: INTERVAL,- timers: clock.timers,- });+ const { clock, gated, scheduler } = gatedScheduler();scheduler.start("thread-a");await clock.advance(INTERVAL);@@ -1001,12 +929,7 @@ test("quiet time is measured after the checkpoint settles, not on a fixed cadenc});test("no timer is armed while a checkpoint is in flight", async () => {- const clock = createFakeTimers();- const gated = createGatedSave();- const scheduler = createRunCheckpointScheduler(gated.save, {- intervalMs: INTERVAL,- timers: clock.timers,- });+ const { clock, gated, scheduler } = gatedScheduler();scheduler.start("thread-a");assert.equal(clock.pending(), 1);@@ -1025,14 +948,7 @@ test("no timer is armed while a checkpoint is in flight", async () => {});test("a duplicate start does not stack timers", async () => {- const clock = createFakeTimers();- let saves = 0;- const scheduler = createRunCheckpointScheduler(- async () => {- saves += 1;- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");scheduler.start("thread-a");@@ -1040,7 +956,7 @@ test("a duplicate start does not stack timers", async () => {assert.equal(clock.pending(), 1, "one timer per thread, not per start");await clock.advanceUntilQuiet(INTERVAL);assert.equal(- saves,+ saved.length,1,"a repeated runStart must not double the checkpoint rate",);@@ -1048,14 +964,7 @@ test("a duplicate start does not stack timers", async () => {});test("stopping an unknown thread is a no-op and does not disturb a live thread", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");scheduler.stop("thread-never-started");@@ -1066,56 +975,35 @@ test("stopping an unknown thread is a no-op and does not disturb a live thread",});test("stopping a thread twice is a no-op the second time", async () => {- const clock = createFakeTimers();- let saves = 0;- const scheduler = createRunCheckpointScheduler(- async () => {- saves += 1;- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");scheduler.stop("thread-a");scheduler.stop("thread-a");assert.equal(clock.pending(), 0);await clock.advance(INTERVAL * 5);- assert.equal(saves, 0, "a double stop must not resurrect anything");+ assert.equal(saved.length, 0, "a double stop must not resurrect anything");});test("start after stop restarts the schedule cleanly", async () => {- const clock = createFakeTimers();- let saves = 0;- const scheduler = createRunCheckpointScheduler(- async () => {- saves += 1;- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");await clock.advance(INTERVAL);- assert.equal(saves, 1);+ assert.equal(saved.length, 1);scheduler.stop("thread-a");await clock.advance(INTERVAL * 3);- assert.equal(saves, 1);+ assert.equal(saved.length, 1);scheduler.start("thread-a");assert.equal(clock.pending(), 1);await clock.advance(INTERVAL);- assert.equal(saves, 2, "a restarted thread must checkpoint again");+ assert.equal(saved.length, 2, "a restarted thread must checkpoint again");scheduler.stop("thread-a");});test("stopAll is idempotent and threads can restart after it", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");scheduler.start("thread-b");@@ -1132,14 +1020,7 @@ test("stopAll is idempotent and threads can restart after it", async () => {});test("threads are checkpointed independently", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");scheduler.start("thread-b");@@ -1157,32 +1038,22 @@ test("threads are checkpointed independently", async () => {});test("a run shorter than one interval produces no checkpoints", async () => {- const clock = createFakeTimers();- let saves = 0;- const scheduler = createRunCheckpointScheduler(- async () => {- saves += 1;- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("thread-a");await clock.advance(INTERVAL - 1);scheduler.stop("thread-a");await clock.advance(INTERVAL * 10);- assert.equal(saves, 0, "a short run must not write a checkpoint at all");+ assert.equal(+ saved.length,+ 0,+ "a short run must not write a checkpoint at all",+ );assert.equal(clock.pending(), 0);});test("each thread's save receives its own thread id", async () => {- const clock = createFakeTimers();- const saved: string[] = [];- const scheduler = createRunCheckpointScheduler(- async (threadId) => {- saved.push(threadId);- },- { intervalMs: INTERVAL, timers: clock.timers },- );+ const { clock, saved, scheduler } = recordingScheduler();scheduler.start("alpha");scheduler.start("beta");@@ -1213,12 +1084,7 @@ test("a custom interval is honoured for every thread", async () => {});test("stop during an in-flight checkpoint ends the schedule", async () => {- const clock = createFakeTimers();- const gated = createGatedSave();- const scheduler = createRunCheckpointScheduler(gated.save, {- intervalMs: INTERVAL,- timers: clock.timers,- });+ const { clock, gated, scheduler } = gatedScheduler();scheduler.start("thread-a");await clock.advance(INTERVAL);@@ -1237,12 +1103,7 @@ test("stop during an in-flight checkpoint ends the schedule", async () => {});test("a thread restarted while its old save is in flight keeps exactly one schedule", async () => {- const clock = createFakeTimers();- const gated = createGatedSave();- const scheduler = createRunCheckpointScheduler(gated.save, {- intervalMs: INTERVAL,- timers: clock.timers,- });+ const { clock, gated, scheduler } = gatedScheduler();scheduler.start("thread-a");await clock.advance(INTERVAL);diff --git a/studio/frontend/tests/chat-run-checkpoint.test.ts b/studio/frontend/tests/chat-run-checkpoint.test.tsindex 58079dbd1df..aae507c5b38 100644--- a/studio/frontend/tests/chat-run-checkpoint.test.ts+++ b/studio/frontend/tests/chat-run-checkpoint.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {RUN_CHECKPOINT_INTERVAL_MS,@@ -10,6 +9,8 @@ import {createRunCheckpointScheduler,} from "../src/features/chat/utils/run-checkpoint-scheduler.ts";+import { readSrcAsync } from "./helpers/kit.ts";+const INTERVAL = 1000;test("uses an eight-second production checkpoint interval", () => {@@ -199,10 +200,7 @@ test("starting a thread twice keeps one schedule, and stopAll ends every thread"});test("the chat autosave drives the scheduler from runStart to runEnd", async () => {- const src = await readFile(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",- );+ const src = await readSrcAsync("features/chat/runtime-provider.tsx");assert.match(src,/createRunCheckpointScheduler\(/,diff --git a/studio/frontend/tests/chat-sampling-seed.test.ts b/studio/frontend/tests/chat-sampling-seed.test.tsindex bf39ceece68..ce368f62fc1 100644--- a/studio/frontend/tests/chat-sampling-seed.test.ts+++ b/studio/frontend/tests/chat-sampling-seed.test.ts@@ -7,10 +7,9 @@// quietly drop a seed of 0 or a deliberate clear.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readText, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -44,10 +43,6 @@ function params(overrides: Partial<InferenceParams> = {}): InferenceParams {return { ...DEFAULT_INFERENCE_PARAMS, checkpoint: GGUF, ...overrides };}-function read(path: string): string {- return readFileSync(new URL(path, import.meta.url), "utf8");-}-function slice(source: string, from: string, to: string): string {const start = source.indexOf(from);const end = source.indexOf(to, start + from.length);@@ -119,7 +114,7 @@ test("a row written before the seed existed keeps what is on screen", () => {// graph, so pin their source the way the sibling settings tests do.test("the settings sanitizer lets a cleared seed through", () => {- const storage = read("../src/features/chat/utils/chat-settings-storage.ts");+ const storage = readText("../src/features/chat/utils/chat-settings-storage.ts");const body = slice(storage,"function sanitizeInferenceParams(",@@ -132,7 +127,7 @@ test("the settings sanitizer lets a cleared seed through", () => {});test("the request omits the seed when it is unset", () => {- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");assert.match(adapter, /params\.seed == null \|\|/);assert.match(adapter, /\{ seed: params\.seed \}/);});@@ -182,7 +177,7 @@ test("a seed reaches only the backends that read one", () => {});test("the panel offers the seed only where the backend reads it", () => {- const sheet = read("../src/features/chat/chat-settings-sheet.tsx");+ const sheet = readText("../src/features/chat/chat-settings-sheet.tsx");assert.match(sheet, /const showSeed = modelReadsSamplingSeed\(/);// type="number" reports an entry the engine cannot parse as "", which would clear// the pin with no error. chat-providers-dialog documents the same trap.@@ -207,17 +202,17 @@ test("the panel and the request body gate on the same argument", () => {match[1].replace(/\s+/g, " ").trim(),);assert.deepEqual(- gateArguments(read("../src/features/chat/chat-settings-sheet.tsx")),+ gateArguments(readText("../src/features/chat/chat-settings-sheet.tsx")),["activeModel"],);assert.deepEqual(- gateArguments(read("../src/features/chat/api/chat-adapter.ts")),+ gateArguments(readText("../src/features/chat/api/chat-adapter.ts")),["activeModel"],);});test("an over-long entry clamps rather than becoming another number", () => {- const sheet = read("../src/features/chat/chat-settings-sheet.tsx");+ const sheet = readText("../src/features/chat/chat-settings-sheet.tsx");// The clamp lives in committedSeed now, so a click on Save reads the same value blur// would have written rather than the one from before the entry.const handler = slice(sheet, "const committedSeed = useMemo", "const paramsWithCommittedSeed");@@ -230,7 +225,7 @@ test("an over-long entry clamps rather than becoming another number", () => {});test("typing is not rewritten before the entry is finished", () => {- const sheet = read("../src/features/chat/chat-settings-sheet.tsx");+ const sheet = readText("../src/features/chat/chat-settings-sheet.tsx");const field = slice(sheet, "{showSeed ? (", "placeholder=\"Random\"");// The box shows the raw draft while it is being typed into, so a clamp cannot// rewrite it mid-entry. NumericValueInput keeps a draft for the same reason.@@ -246,7 +241,7 @@ test("an abandoned entry does not outlive the box it was typed into", () => {// Blur is the only commit and removing a focused element fires none, so both keys// matter: a model switch and the field going away each strand a draft in committedSeed.// Shape only: there is no DOM here, so the no-blur premise was measured in a browser.- const sheet = read("../src/features/chat/chat-settings-sheet.tsx");+ const sheet = readText("../src/features/chat/chat-settings-sheet.tsx");const reset = slice(sheet, "useEffect(() => {\n setSeedDraft(null);", ");");assert.match(reset, /\[currentCheckpoint, showSeed\]/);});@@ -275,7 +270,7 @@ test("moving the seed marks the preset modified", () => {});test("the stored seed is range-checked, not just the keystroke", () => {- const storage = read("../src/features/chat/utils/chat-settings-storage.ts");+ const storage = readText("../src/features/chat/utils/chat-settings-storage.ts");const body = slice(storage,"function sanitizeInferenceParams(",@@ -288,7 +283,7 @@ test("the stored seed is range-checked, not just the keystroke", () => {});test("the request drops a seed the loaded model cannot use", () => {- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");// A pin set on a GGUF outlives a switch to transformers, where the panel hides the// field: without this the user would keep sending a seed they can no longer see.assert.match(adapter, /!modelReadsSamplingSeed\(/);@@ -320,7 +315,7 @@ test("a chat stores a cleared seed rather than dropping the key", () => {});test("a cleared seed is not read as a missing key", () => {- const store = read("../src/features/chat/stores/chat-runtime-store.ts");+ const store = readText("../src/features/chat/stores/chat-runtime-store.ts");const helper = slice(store, "function firstSetThreadScopedValue", "\n}");// `??` would fall through a cleared seed's null to the installation default, putting// the pin back on the one chat that dropped it. Only undefined means "not set".@@ -359,7 +354,7 @@ test("a models[] row states every flag the seed gate reads", () => {});test("saving a preset takes the seed being typed, not the one before it", () => {- const panel = read("../src/features/chat/chat-settings-sheet.tsx");+ const panel = readText("../src/features/chat/chat-settings-sheet.tsx");// Clicking Save blurs the box during mousedown, but React has not re-rendered by the// time onClick runs, so a save reading `params` writes the pre-entry seed and, over an// otherwise-unmodified preset, the button is still disabled and the click does nothing.diff --git a/studio/frontend/tests/chat-settings-hydration-shadows.test.ts b/studio/frontend/tests/chat-settings-hydration-shadows.test.tsindex 3295c45f83d..cb0aac8ed36 100644--- a/studio/frontend/tests/chat-settings-hydration-shadows.test.ts+++ b/studio/frontend/tests/chat-settings-hydration-shadows.test.ts@@ -11,15 +11,13 @@// imported (a .tsx barrel in its graph), so the wiring is pinned against the source.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { loadShadowOwnsMirroredSetting } from "../src/features/chat/utils/mirrored-chat-settings.ts";-const store = readFileSync(- new URL("../src/features/chat/stores/chat-runtime-store.ts", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const store = readSrc("features/chat/stores/chat-runtime-store.ts");function slice(from: string, to: string): string {const start = store.indexOf(from);diff --git a/studio/frontend/tests/chat-speech-model-not-adopted.test.ts b/studio/frontend/tests/chat-speech-model-not-adopted.test.tsindex 6f55e563c3d..9e6bff19b80 100644--- a/studio/frontend/tests/chat-speech-model-not-adopted.test.ts+++ b/studio/frontend/tests/chat-speech-model-not-adopted.test.ts@@ -7,7 +7,6 @@// it anywhere. These pin the places that now do.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -16,10 +15,9 @@ import {isSpeechOnlyStatus,} from "../src/features/chat/lib/speech-only-status.ts";-const status = (fields: SpeechOnlyStatusInput): SpeechOnlyStatusInput => fields;+import { readText } from "./helpers/kit.ts";-const readSource = (path: string) =>- readFileSync(new URL(path, import.meta.url), "utf8");+const status = (fields: SpeechOnlyStatusInput): SpeechOnlyStatusInput => fields;test("a resident TTS model reads as speech-only", () => {for (const audioType of ["snac", "csm", "bicodec", "dac"]) {@@ -66,7 +64,7 @@ test("only an armed idle unload preserves an empty resident slot", () => {});test("chat does not adopt the server's model when it only speaks", () => {- const source = readSource(+ const source = readText("../src/features/chat/lib/apply-inference-status-to-store.ts",);// In tryAdoptServerActiveModel, not resolveInferenceCheckpointId: the loaded-models@@ -87,7 +85,7 @@ test("chat does not adopt the server's model when it only speaks", () => {});test("the mount-time status sync treats a speech model as an empty slot", () => {- const hook = readSource(+ const hook = readText("../src/features/chat/hooks/use-chat-model-runtime.ts",);assert.match(@@ -111,14 +109,14 @@ test("the mount-time status sync treats a speech model as an empty slot", () =>});test("a TTS load announces its own runtime so chat re-reads the slot", () => {- const events = readSource("../src/lib/model-lifecycle-events.ts");+ const events = readText("../src/lib/model-lifecycle-events.ts");assert.match(events, /export type ModelRuntime =[^;]*"tts"/);// Chat ignores its own loads when reconciling, so a TTS load announced as "chat" left// chat naming a model the Audio page had evicted.- const audio = readSource("../src/features/audio/audio-page.tsx");+ const audio = readText("../src/features/audio/audio-page.tsx");assert.match(audio, /runtime: "tts",/);- const hook = readSource(+ const hook = readText("../src/features/chat/hooks/use-chat-model-runtime.ts",);assert.match(@@ -139,7 +137,7 @@ test("a TTS load announces its own runtime so chat re-reads the slot", () => {});test("chat re-reads status when a different tab returns to the foreground", () => {- const hook = readSource(+ const hook = readText("../src/features/chat/hooks/use-chat-model-runtime.ts",);assert.match(hook, /subscribeResidentStatusRefresh\(\(\) => \{/);@@ -153,7 +151,7 @@ test("chat re-reads status when a different tab returns to the foreground", () =// sites resolve a resident model into the chat store on their own.test("the Hub does not pin a speech model as the chat checkpoint", () => {- const hub = readSource("../src/features/hub/hub-page.tsx");+ const hub = readText("../src/features/hub/hub-page.tsx");const adopt = hub.slice(hub.indexOf("adoptResidentModelStatus("),hub.indexOf("registerRefresh(", hub.indexOf("adoptResidentModelStatus(")),@@ -171,7 +169,7 @@ test("the Hub does not pin a speech model as the chat checkpoint", () => {});test("a queued local thread does not adopt a speech model either", () => {- const adapter = readSource("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");const queued = adapter.slice(adapter.indexOf("async function resolveQueuedEmptyLocalModel"),adapter.indexOf("export function createOpenAIStreamAdapter"),@@ -183,7 +181,7 @@ test("a queued local thread does not adopt a speech model either", () => {});test("the auto-load sweep skips every task chat cannot answer", () => {- const adapter = readSource("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");const set = adapter.slice(adapter.indexOf("const NON_CHAT_TASKS"),adapter.indexOf("]);", adapter.indexOf("const NON_CHAT_TASKS")),diff --git a/studio/frontend/tests/chat-status-refresh-sequencing.test.ts b/studio/frontend/tests/chat-status-refresh-sequencing.test.tsindex 3db14173369..62c182d4fe5 100644--- a/studio/frontend/tests/chat-status-refresh-sequencing.test.ts+++ b/studio/frontend/tests/chat-status-refresh-sequencing.test.ts@@ -13,16 +13,11 @@// the load finally settled hours later. Last issued has to win.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-const SOURCE = readFileSync(- fileURLToPath(- new URL("../src/features/chat/hooks/use-chat-model-runtime.ts", import.meta.url),- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const SOURCE = readSrc("features/chat/hooks/use-chat-model-runtime.ts");const SYNC = SOURCE.slice(SOURCE.indexOf("async function syncInferenceStatusToStore("),diff --git a/studio/frontend/tests/chat-stream-publish-gate.test.ts b/studio/frontend/tests/chat-stream-publish-gate.test.tsindex c49ef19c72c..0e7b4574402 100644--- a/studio/frontend/tests/chat-stream-publish-gate.test.ts+++ b/studio/frontend/tests/chat-stream-publish-gate.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -16,6 +15,8 @@ import {} from "../src/features/chat/utils/reasoning-duration.ts";import { parseAssistantContent } from "../src/features/chat/utils/parse-assistant-content.ts";+import { readSrc } from "./helpers/kit.ts";+type Scheduled = {frames: Array<() => void>;timers: { run: () => void; ms: number }[];@@ -244,10 +245,7 @@ test("a painting window publishes on frames, never on the cap", () => {});});-const ADAPTER = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",-);+const ADAPTER = readSrc("features/chat/api/chat-adapter.ts");/** Drop comments, so a commented-out gate cannot satisfy a search. */function withoutComments(source: string): string {diff --git a/studio/frontend/tests/chat-transfer-hidden-tab.test.ts b/studio/frontend/tests/chat-transfer-hidden-tab.test.tsindex 2bb7a4c0636..f004f383f35 100644--- a/studio/frontend/tests/chat-transfer-hidden-tab.test.ts+++ b/studio/frontend/tests/chat-transfer-hidden-tab.test.ts@@ -8,7 +8,6 @@// already drop hidden samples; this pins that the chat one does too.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -17,16 +16,12 @@ import {computeTransferStats,} from "../src/lib/transfer-stats.ts";+import { readSrc } from "./helpers/kit.ts";+const MB = 1e6;test("the chat estimator drops samples taken while the tab is hidden", () => {- const source = readFileSync(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("features/chat/hooks/use-chat-model-runtime.ts");const guard = source.indexOf("document.hidden");assert.ok(guard > 0, "the chat poller should skip a hidden tab");const clear = source.indexOf("samples.length = 0", guard);diff --git a/studio/frontend/tests/chat-user-turn-identity.test.ts b/studio/frontend/tests/chat-user-turn-identity.test.tsindex a9104e813de..2785dea5eb6 100644--- a/studio/frontend/tests/chat-user-turn-identity.test.ts+++ b/studio/frontend/tests/chat-user-turn-identity.test.ts@@ -13,17 +13,12 @@// studio/backend/tests/test_chat_message_identity.py, against the real studio_db.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",-);-const runtimeProvider = readFileSync(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const adapter = readSrc("features/chat/api/chat-adapter.ts");+const runtimeProvider = readSrc("features/chat/runtime-provider.tsx");function slice(source: string, from: string, to: string): string {const start = source.indexOf(from);diff --git a/studio/frontend/tests/chrome-icon-button-consistency.test.ts b/studio/frontend/tests/chrome-icon-button-consistency.test.tsindex a173739cb50..962991ff77f 100644--- a/studio/frontend/tests/chrome-icon-button-consistency.test.ts+++ b/studio/frontend/tests/chrome-icon-button-consistency.test.ts@@ -1,9 +1,7 @@import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-const source = (path: string) =>- readFile(new URL(`../src/${path}`, import.meta.url), "utf8");+import { readSrc } from "./helpers/kit.ts";const BUTTON_CLASS = /className="([^"]+)"/;const WHITESPACE = /\s+/;@@ -43,8 +41,8 @@ function buttonClasses(button: string): Set<string> {test("run settings uses one aligned toggle in both states", async () => {const [page, panel] = await Promise.all([- source("features/chat/chat-page.tsx"),- source("features/chat/chat-settings-sheet.tsx"),+ readSrc("features/chat/chat-page.tsx"),+ readSrc("features/chat/chat-settings-sheet.tsx"),]);const toggles = [@@ -68,8 +66,8 @@ test("run settings uses one aligned toggle in both states", async () => {test("settings chrome uses the titlebar rounded-square hover shape", async () => {const [dialog, sidebar] = await Promise.all([- source("features/settings/settings-dialog.tsx"),- source("components/app-sidebar.tsx"),+ readSrc("features/settings/settings-dialog.tsx"),+ readSrc("components/app-sidebar.tsx"),]);const dialogMain = dialog.slice(dialog.indexOf("<main"));diff --git a/studio/frontend/tests/code-fence-defer.test.ts b/studio/frontend/tests/code-fence-defer.test.tsindex 39e861b30bd..e30680e75a2 100644--- a/studio/frontend/tests/code-fence-defer.test.ts+++ b/studio/frontend/tests/code-fence-defer.test.ts@@ -5,6 +5,8 @@ import assert from "node:assert/strict";import { existsSync, readFileSync } from "node:fs";import test from "node:test";+import { readSrc } from "./helpers/kit.ts";+/*** The one property that makes this change different from the viewport gate that came before it,* pinned as source facts.@@ -20,15 +22,9 @@ import test from "node:test";* protecting is structural anyway -- "no code path sets this back to false".*/-const SOURCE = readFileSync(- new URL("../src/components/assistant-ui/code-fence-defer.tsx", import.meta.url),- "utf8",-);+const SOURCE = readSrc("components/assistant-ui/code-fence-defer.tsx");-const MARKDOWN_TEXT = readFileSync(- new URL("../src/components/assistant-ui/markdown-text.tsx", import.meta.url),- "utf8",-);+const MARKDOWN_TEXT = readSrc("components/assistant-ui/markdown-text.tsx");test("the latch is only ever set to true", () => {const writes = SOURCE.match(/setLatched\([^)]*\)/g) ?? [];@@ -398,10 +394,7 @@ test("nothing is watched once there is nothing left to defer", () => {);});-const CODE_PLUGIN = readFileSync(- new URL("../src/components/assistant-ui/code-plugin.ts", import.meta.url),- "utf8",-);+const CODE_PLUGIN = readSrc("components/assistant-ui/code-plugin.ts");test("the fence language is a language, not the whole info string", () => {// `getCodeFence` captures everything after the backticks, so ```python startLine=10 arrives asdiff --git a/studio/frontend/tests/code-fence-mode.test.ts b/studio/frontend/tests/code-fence-mode.test.tsindex 67b8e0b0cef..9fff82774ac 100644--- a/studio/frontend/tests/code-fence-mode.test.ts+++ b/studio/frontend/tests/code-fence-mode.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -10,6 +9,8 @@ import {resolveFenceMode,} from "../src/components/assistant-ui/code-fence-mode.ts";+import { readSrc } from "./helpers/kit.ts";+/*** The fence mode decision table, RUN rather than described.*@@ -106,13 +107,7 @@ test("a non-string non-boolean global is ignored rather than coerced", () => {/** JSX in the mode module makes this file unloadable and every assertion above a comment. */test("the mode module is plain TypeScript", () => {- const source = readFileSync(- new URL(- "../src/components/assistant-ui/code-fence-mode.ts",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("components/assistant-ui/code-fence-mode.ts");assert.ok(!/<[A-Za-z]/.test(source.replace(/^\s*[/*].*$/gm, "")),"no JSX in the mode module",diff --git a/studio/frontend/tests/code-plugin-engine-and-cache.test.ts b/studio/frontend/tests/code-plugin-engine-and-cache.test.tsindex 774e82c5041..2a41bdf48b6 100644--- a/studio/frontend/tests/code-plugin-engine-and-cache.test.ts+++ b/studio/frontend/tests/code-plugin-engine-and-cache.test.ts@@ -21,7 +21,6 @@*/import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import type {HighlightOptions,@@ -37,12 +36,11 @@ import {TOKENIZE_LIMITS,} from "../src/components/assistant-ui/code-plugin.ts";+import { readSrc } from "./helpers/kit.ts";+const THEMES: [ThemeInput, ThemeInput] = ["github-light", "github-dark"];-const PLUGIN_SOURCE = readFileSync(- new URL("../src/components/assistant-ui/code-plugin.ts", import.meta.url),- "utf8",-);+const PLUGIN_SOURCE = readSrc("components/assistant-ui/code-plugin.ts");const highlightOnce = (plugin: ReturnType<typeof createCodePlugin>,diff --git a/studio/frontend/tests/code-tool-placement.test.ts b/studio/frontend/tests/code-tool-placement.test.tsindex 0405cfa0b32..7667682b59d 100644--- a/studio/frontend/tests/code-tool-placement.test.ts+++ b/studio/frontend/tests/code-tool-placement.test.ts@@ -17,8 +17,6 @@// Unsloth's local python/terminal are for connections that have none.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import test from "node:test";import {@@ -26,10 +24,9 @@ import {selectCodeToolNames,} from "../src/features/chat/api/code-tool-placement.ts";-const SOURCE = readFileSync(- fileURLToPath(new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url)),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const SOURCE = readSrc("features/chat/api/chat-adapter.ts");// ── the rule itself ────────────────────────────────────────────────diff --git a/studio/frontend/tests/compare-pane-thread-shapes.test.ts b/studio/frontend/tests/compare-pane-thread-shapes.test.tsindex 0c4e47cd74a..6618634615c 100644--- a/studio/frontend/tests/compare-pane-thread-shapes.test.ts+++ b/studio/frontend/tests/compare-pane-thread-shapes.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import type { ModelType, ThreadRecord } from "../src/features/chat/types.ts";import {@@ -13,14 +12,10 @@ import {resolveComparePaneThreadIds,} from "../src/features/chat/utils/compare-pane-threads.ts";-const chatPageSource = readFileSync(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",-);-const sharedComposerSource = readFileSync(- new URL("../src/features/chat/shared-composer.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const chatPageSource = readSrc("features/chat/chat-page.tsx");+const sharedComposerSource = readSrc("features/chat/shared-composer.tsx");const LORA_PANE_SOURCE = chatPageSource.slice(chatPageSource.indexOf("const LoraCompareContent"),diff --git a/studio/frontend/tests/composer-icon-alignment.test.ts b/studio/frontend/tests/composer-icon-alignment.test.tsindex 21493b503b4..d48f55e1459 100644--- a/studio/frontend/tests/composer-icon-alignment.test.ts+++ b/studio/frontend/tests/composer-icon-alignment.test.ts@@ -5,13 +5,15 @@ import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";+import { readSrc } from "./helpers/kit.ts";+const componentSources = ["../src/components/assistant-ui/thread.tsx","../src/components/assistant-ui/chat-dictation-bar.tsx","../src/features/chat/shared-composer.tsx",].map((path) => readFileSync(new URL(path, import.meta.url), "utf8"));-const css = readFileSync(new URL("../src/index.css", import.meta.url), "utf8");+const css = readSrc("index.css");function tags(source: string, component: string): string[] {return source.match(new RegExp(`<${component}\\b[^>]*\\/>`, "g")) ?? [];diff --git a/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts b/studio/frontend/tests/composer-keystroke-subscription-budget.test.tsindex a463d886e59..3101c927917 100644--- a/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts+++ b/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts@@ -23,15 +23,12 @@// checks.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-function source(path: string): string {- return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");-}+import { readSrc } from "./helpers/kit.ts";-const markdown = source("components/assistant-ui/markdown-text.tsx");-const thread = source("components/assistant-ui/thread.tsx");+const markdown = readSrc("components/assistant-ui/markdown-text.tsx");+const thread = readSrc("components/assistant-ui/thread.tsx");/** The body of the named function or component declaration, up to its closing brace. */function body(text: string, start: string, terminator = "\n}"): string {diff --git a/studio/frontend/tests/connections-empty-opens-form.test.ts b/studio/frontend/tests/connections-empty-opens-form.test.tsindex e5da0b7b801..e8e8ead763e 100644--- a/studio/frontend/tests/connections-empty-opens-form.test.ts+++ b/studio/frontend/tests/connections-empty-opens-form.test.ts@@ -6,13 +6,11 @@// no connections. These pin the parts that make it land where a user expects.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const dialog = readFileSync(- new URL("../src/features/chat/chat-providers-dialog.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const dialog = readSrc("features/chat/chat-providers-dialog.tsx");test("an empty connection list opens the add-connection form", () => {// Both operands matter: `syncedProviders` is the backend answer, anddiff --git a/studio/frontend/tests/context-menu-item-radius.test.ts b/studio/frontend/tests/context-menu-item-radius.test.tsindex b411116e4f5..93e8c64ba06 100644--- a/studio/frontend/tests/context-menu-item-radius.test.ts+++ b/studio/frontend/tests/context-menu-item-radius.test.ts@@ -2,16 +2,13 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readText } from "./helpers/kit.ts";+const RECTANGLE_RADIUS = /rounded-\[11px\]/;const PILL_RADIUS = /\brounded-(?:full|xl)\b/;-function componentSource(path: string): Promise<string> {- return readFile(new URL(path, import.meta.url), "utf8");-}-function functionBody(source: string, name: string): string {const start = source.indexOf(`function ${name}(`);if (start === -1) throw new Error(`no ${name} component`);@@ -21,11 +18,11 @@ function functionBody(source: string, name: string): string {test("context-menu item hover matches the standard dropdown rectangle", async () => {const contextItem = functionBody(- await componentSource("../src/components/ui/context-menu.tsx"),+ await readText("../src/components/ui/context-menu.tsx"),"ContextMenuItem",);const dropdownItem = functionBody(- await componentSource("../src/components/ui/dropdown-menu.tsx"),+ await readText("../src/components/ui/dropdown-menu.tsx"),"DropdownMenuItem",);diff --git a/studio/frontend/tests/context-pin-survives-load.test.ts b/studio/frontend/tests/context-pin-survives-load.test.tsindex 568fcb3303a..9552cbf6203 100644--- a/studio/frontend/tests/context-pin-survives-load.test.ts+++ b/studio/frontend/tests/context-pin-survives-load.test.ts@@ -25,28 +25,17 @@// path has a seam (resolveCtxPinSeed) and is checked through it.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import path from "node:path";import test from "node:test";-import { fileURLToPath } from "node:url";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();-const HERE = path.dirname(fileURLToPath(import.meta.url));-const read = (relative: string) =>- readFileSync(path.join(HERE, "..", relative), "utf8");--const APPLIER = read(- "src/features/chat/lib/apply-inference-status-to-store.ts",-);-const RUNTIME = read("src/features/chat/hooks/use-chat-model-runtime.ts");-const ADAPTER = read("src/features/chat/api/chat-adapter.ts");-const COMPOSER = read("src/features/chat/shared-composer.tsx");-const CONFIG_PAGE = read(- "src/features/model-picker/components/model-config-page.tsx",-);+const APPLIER = readSrc("features/chat/lib/apply-inference-status-to-store.ts");+const RUNTIME = readSrc("features/chat/hooks/use-chat-model-runtime.ts");+const ADAPTER = readSrc("features/chat/api/chat-adapter.ts");+const COMPOSER = readSrc("features/chat/shared-composer.tsx");+const CONFIG_PAGE = readSrc("features/model-picker/components/model-config-page.tsx");const policy = await import("../src/features/chat/presets/preset-policy.ts");const { resolveCtxPinSeed } = await import(diff --git a/studio/frontend/tests/context-refusal-shared-floor.test.ts b/studio/frontend/tests/context-refusal-shared-floor.test.tsindex c2a7277085b..0e71905dd2b 100644--- a/studio/frontend/tests/context-refusal-shared-floor.test.ts+++ b/studio/frontend/tests/context-refusal-shared-floor.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {type ContextTruncation,@@ -12,6 +11,10 @@ import {mergeContextTruncation,} from "../src/features/chat/utils/context-truncation.ts";+import { readSrc } from "./helpers/kit.ts";++const CHAT_ADAPTER = readSrc("features/chat/api/chat-adapter.ts");+function refusal(extra: Partial<ContextTruncation>): ContextTruncation {return {dropped_messages: 0,@@ -251,35 +254,27 @@ test("a prompt whose floor is already over the window is never sent to a new cha});test("the third toast branch names the levers that can actually work", () => {- const source = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );// The band moved out of "this message is too long" must not fall through to "start a// new chat", the one action that provably cannot work here.- assert.match(source, /historyCannotHelp\(irreducible\)/);+ assert.match(CHAT_ADAPTER, /historyCannotHelp\(irreducible\)/);assert.match(- source,+ CHAT_ADAPTER,/Even with every earlier turn dropped, this prompt would still be/,);assert.match(- source,+ CHAT_ADAPTER,/the system prompt and any \" \+\n\s*\"tools that are enabled\./,);});test("the toast quotes the turn's own size, never the count that carries the floor", () => {- const source = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );// Printing `latest_turn_tokens` directly is the defect this guards against coming back.assert.match(- source,+ CHAT_ADAPTER,/\$\{latestTurnOwnTokens\(irreducible\)\.toLocaleString\(\)\} tokens on its own/,);assert.doesNotMatch(- source,+ CHAT_ADAPTER,/latest_turn_tokens\?\.toLocaleString\(\)\} tokens on its own/,);});diff --git a/studio/frontend/tests/context-window-visible.test.ts b/studio/frontend/tests/context-window-visible.test.tsindex 36fef62ab6e..e44d6e872ac 100644--- a/studio/frontend/tests/context-window-visible.test.ts+++ b/studio/frontend/tests/context-window-visible.test.ts@@ -6,12 +6,13 @@// a build that fell back to 0 instead of null still passed every assertion.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { deriveContextUsageBar } from "../src/features/chat/lib/context-usage-bar-state.ts";import { hasKnownContextWindow } from "../src/features/chat/lib/context-window-known.ts";+import { readSrc } from "./helpers/kit.ts";+const RESIDENT = "unsloth/Qwen3.6-35B-A3B-MTP-GGUF";const base = {@@ -145,10 +146,7 @@ test("an uncounted chat reports no per-turn rows", () => {});test("the header renders the bar on the window alone, with usage optional", () => {- const page = readFileSync(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );+ const page = readSrc("features/chat/chat-page.tsx");assert.match(page,/view\.mode === "single" && \(contextUsage \|\| contextWindowKnown\)/,diff --git a/studio/frontend/tests/conversation-markdown.test.ts b/studio/frontend/tests/conversation-markdown.test.tsindex 9782ffdaffa..f30a3e04d76 100644--- a/studio/frontend/tests/conversation-markdown.test.ts+++ b/studio/frontend/tests/conversation-markdown.test.ts@@ -9,6 +9,12 @@ import {renderConversationBlocks,} from "../src/features/chat/utils/conversation-markdown.ts";+const renderText = (text: string): string =>+ renderConversationBlocks([{ kind: "text", text }]);++const renderSource = (title: string, url: string): string =>+ renderConversationBlocks([{ kind: "source", title, url }]);+test("exports a readable markdown transcript in conversation order", () => {assert.equal(buildConversationMarkdown([@@ -347,19 +353,11 @@ test("preserves assistant citation sources in markdown exports", () => {test("does not turn unsafe citation schemes into markdown links", () => {assert.equal(- renderConversationBlocks([- { kind: "source", title: "Untrusted source", url: "javascript:alert(1)" },- ]),+ renderSource("Untrusted source", "javascript:alert(1)"),"**source:** `Untrusted source`",);assert.equal(- renderConversationBlocks([- {- kind: "source",- title: "Injected source",- url: "https://safe.test/\n[evil](https://evil.test)",- },- ]),+ renderSource("Injected source", "https://safe.test/\n[evil](https://evil.test)"),"**source:** `Injected source`",);assert.equal(@@ -413,10 +411,7 @@ test("an unclosed fence cannot swallow the message that follows it", () => {});test("an unterminated html comment cannot hide the message that follows it", () => {- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<!-- note" }]),- "<!-- note-->",- );+ assert.equal(renderText("<!-- note"), "<!-- note-->");});test("reasoning that leaves a fence open still closes its details block", () => {@@ -477,22 +472,14 @@ test("a line break in an arg key cannot end the bold label", () => {test("a line break in a citation title cannot end the link label", () => {assert.equal(- renderConversationBlocks([- {- kind: "source",- title: "ok\n\n<img src=x onerror=alert(1)>",- url: "https://good.test/",- },- ]),+ renderSource("ok\n\n<img src=x onerror=alert(1)>", "https://good.test/"),"**source:** [ok \\<img src=x onerror=alert(1)>](<https://good.test/>)",);});test("a rejected destination leaves a bare url title unlinkable", () => {assert.equal(- renderConversationBlocks([- { kind: "source", title: "https://evil.test/track", url: "javascript:alert(1)" },- ]),+ renderSource("https://evil.test/track", "javascript:alert(1)"),"**source:** `https://evil.test/track`",);});@@ -523,121 +510,70 @@ test("fences a value whose only line break is a carriage return", () => {});test("drops a fragment url that cannot be encoded instead of throwing", () => {- assert.equal(- renderConversationBlocks([- { kind: "source", title: "Broken", url: "#\ud800" },- ]),- "**source:** `Broken`",- );+ assert.equal(renderSource("Broken", "#\ud800"), "**source:** `Broken`");});test("closes a fence opened in a body that uses bare carriage returns", () => {assert.equal(- renderConversationBlocks([{ kind: "text", text: "look:\r```js\rvar a = 1;" }]),+ renderText("look:\r```js\rvar a = 1;"),"look:\r```js\rvar a = 1;\r```",);});test("leaves a paragraph that only looks like a fence alone", () => {- assert.equal(- renderConversationBlocks([{ kind: "text", text: "```a`b" }]),- "```a`b",- );+ assert.equal(renderText("```a`b"), "```a`b");});test("does not treat a fence closer carrying text as a closer", () => {- assert.equal(- renderConversationBlocks([{ kind: "text", text: "```\nx\n``` trailing" }]),- "```\nx\n``` trailing\n```",- );+ assert.equal(renderText("```\nx\n``` trailing"), "```\nx\n``` trailing\n```");});test("leaves a comment inside a fence literal", () => {- assert.equal(- renderConversationBlocks([{ kind: "text", text: "```\n<!-- literal\n```" }]),- "```\n<!-- literal\n```",- );+ assert.equal(renderText("```\n<!-- literal\n```"), "```\n<!-- literal\n```");});test("closes a list-nested fence inside the list, not at column zero", () => {// A closer at column zero ends the list first, opening a top-level fence instead.assert.equal(- renderConversationBlocks([- { kind: "text", text: "Steps:\n\n- run the install\n\n ```sh\n npm ci" },- ]),+ renderText("Steps:\n\n- run the install\n\n ```sh\n npm ci"),"Steps:\n\n- run the install\n\n ```sh\n npm ci\n ```",);- assert.equal(- renderConversationBlocks([{ kind: "text", text: "- run\n\n ~~~\n x" }]),- "- run\n\n ~~~\n x\n ~~~",- );+ assert.equal(renderText("- run\n\n ~~~\n x"), "- run\n\n ~~~\n x\n ~~~");});test("closes a raw html block a blank line cannot end", () => {// CommonMark start condition 1: only its own end tag ends the block.+ assert.equal(renderText("<pre>\nhello"), "<pre>\nhello\n</pre>");assert.equal(- renderConversationBlocks([{ kind: "text", text: "<pre>\nhello" }]),- "<pre>\nhello\n</pre>",- );- assert.equal(- renderConversationBlocks([- { kind: "text", text: '<SCRIPT src="a.js">\nvar x = 1;' },- ]),+ renderText('<SCRIPT src="a.js">\nvar x = 1;'),'<SCRIPT src="a.js">\nvar x = 1;\n</script>',);// Conditions 3, 4 and 5 run to the end of the document just the same.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<?php\necho 1;" }]),- "<?php\necho 1;\n?>",- );- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<![CDATA[\nraw" }]),- "<![CDATA[\nraw\n]]>",- );+ assert.equal(renderText("<?php\necho 1;"), "<?php\necho 1;\n?>");+ assert.equal(renderText("<![CDATA[\nraw"), "<![CDATA[\nraw\n]]>");});test("leaves a raw html block that closes itself alone", () => {- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<pre>\nhello\n</pre>" }]),- "<pre>\nhello\n</pre>",- );- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<pre>hello</pre>" }]),- "<pre>hello</pre>",- );+ assert.equal(renderText("<pre>\nhello\n</pre>"), "<pre>\nhello\n</pre>");+ assert.equal(renderText("<pre>hello</pre>"), "<pre>hello</pre>");// A blank line ends start conditions 6 and 7, and every turn is followed by one.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<div>\nhello" }]),- "<div>\nhello",- );+ assert.equal(renderText("<div>\nhello"), "<div>\nhello");// Indented four spaces it is a code block, not a raw html block.- assert.equal(- renderConversationBlocks([{ kind: "text", text: " <pre>\n hello" }]),- " <pre>\n hello",- );+ assert.equal(renderText(" <pre>\n hello"), " <pre>\n hello");});test("keeps a raw html start inside a fence literal", () => {- assert.equal(- renderConversationBlocks([{ kind: "text", text: "```\n<pre>\nhello\n```" }]),- "```\n<pre>\nhello\n```",- );+ assert.equal(renderText("```\n<pre>\nhello\n```"), "```\n<pre>\nhello\n```");// And the other way round: a fence inside a raw html block is not a fence.assert.equal(- renderConversationBlocks([{ kind: "text", text: "<pre>\n```js\nvar a = 1;" }]),+ renderText("<pre>\n```js\nvar a = 1;"),"<pre>\n```js\nvar a = 1;\n</pre>",);});test("collapses line breaks inside a code span so it cannot be escaped", () => {assert.equal(- renderConversationBlocks([- {- kind: "source",- title: "ok\n\n<img src=x onerror=alert(1)>",- url: "javascript:alert(1)",- },- ]),+ renderSource("ok\n\n<img src=x onerror=alert(1)>", "javascript:alert(1)"),"**source:** `ok <img src=x onerror=alert(1)>`",);});@@ -679,117 +615,74 @@ test("escapes a details opener carrying attributes", () => {test("a comment delimiter inside a code span opens nothing", () => {assert.equal(- renderConversationBlocks([- { kind: "text", text: "Prefix it with `<!--` to comment it out." },- ]),+ renderText("Prefix it with `<!--` to comment it out."),"Prefix it with `<!--` to comment it out.",);});test("still closes a comment opened mid-line outside a code span", () => {- assert.equal(- renderConversationBlocks([{ kind: "text", text: "see <div><!-- note" }]),- "see <div><!-- note-->",- );+ assert.equal(renderText("see <div><!-- note"), "see <div><!-- note-->");});test("closes an unmatched details element a later turn would fall inside", () => {assert.equal(- renderConversationBlocks([- { kind: "text", text: "<details>\n<summary>Steps</summary>\n\nfirst" },- ]),+ renderText("<details>\n<summary>Steps</summary>\n\nfirst"),"<details>\n<summary>Steps</summary>\n\nfirst\n\n</details>",);// Mid-line, in the case shape the tokenizer accepts but a <details ...> does not.assert.equal(- renderConversationBlocks([{ kind: "text", text: "hello <DETAILS/>" }]),+ renderText("hello <DETAILS/>"),"hello <DETAILS/>\n\n</details>",);});test("leaves a details element the message already matched alone", () => {const matched = "<details>\n<summary>FAQ</summary>\n\nbody\n\n</details>";- assert.equal(- renderConversationBlocks([{ kind: "text", text: matched }]),- matched,- );+ assert.equal(renderText(matched), matched);const nested = `<details>\n<summary>outer</summary>\n\n${matched}\n\n</details>`;- assert.equal(- renderConversationBlocks([{ kind: "text", text: nested }]),- nested,- );+ assert.equal(renderText(nested), nested);});test("counts details tags in order so a stray closer licenses no opener", () => {assert.equal(- renderConversationBlocks([- { kind: "text", text: "</details>\n\n<details>" },- ]),+ renderText("</details>\n\n<details>"),"</details>\n\n<details>\n\n</details>",);});test("keeps a details tag inside a fence, a code span or a comment literal", () => {const fenced = "```html\n<details>\n```";+ assert.equal(renderText(fenced), fenced);assert.equal(- renderConversationBlocks([{ kind: "text", text: fenced }]),- fenced,- );- assert.equal(- renderConversationBlocks([- { kind: "text", text: "use `<details>` for this" },- ]),+ renderText("use `<details>` for this"),"use `<details>` for this",);- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<!-- <details> -->" }]),- "<!-- <details> -->",- );+ assert.equal(renderText("<!-- <details> -->"), "<!-- <details> -->");});test("keeps a citation destination from decoding into another host", () => {// @ is an entity reference in a destination: a viewer resolves this to// [email protected], which is credentials on evil.test.assert.equal(- renderConversationBlocks([- {- kind: "source",- title: "Docs",- url: "https://docs.unsloth.ai@evil.test/",- },- ]),+ renderSource("Docs", "https://docs.unsloth.ai@evil.test/"),"**source:** [Docs](<https://docs.unsloth.ai&commat;evil.test/>)",);assert.equal(- renderConversationBlocks([- {- kind: "source",- title: "Numeric",- url: "https://x.test/?a=@evil.test/",- },- ]),+ renderSource("Numeric", "https://x.test/?a=@evil.test/"),"**source:** [Numeric](<https://x.test/?a=&#64;evil.test/>)",);});test("keeps a backslash in a citation destination from being eaten", () => {assert.equal(- renderConversationBlocks([- { kind: "source", title: "Query", url: "https://x.test/?q=\\*" },- ]),+ renderSource("Query", "https://x.test/?q=\\*"),"**source:** [Query](<https://x.test/?q=%5C*>)",);});test("leaves an ordinary query separator in a citation readable", () => {assert.equal(- renderConversationBlocks([- {- kind: "source",- title: "Search",- url: "https://x.test/search?q=lora&page=2&sort=new",- },- ]),+ renderSource("Search", "https://x.test/search?q=lora&page=2&sort=new"),"**source:** [Search](<https://x.test/search?q=lora&page=2&sort=new>)",);});@@ -797,106 +690,66 @@ test("leaves an ordinary query separator in a citation readable", () => {test("neutralises an opener the message never finished writing", () => {// A synthesized </script> after a bare <script> is read as that tag's attributes,// so the element stays open; escaping the < opens nothing at all.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<script" }]),- "<script",- );+ assert.equal(renderText("<script"), "<script");// Any tag: an unterminated attribute value runs to the first > in the document.- assert.equal(- renderConversationBlocks([{ kind: "text", text: '<div class="x' }]),- '<div class="x',- );+ assert.equal(renderText('<div class="x'), '<div class="x');// Handing back what an unfinished tag swallowed can reveal an opener, so repeat.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<details\n<script" }]),- "<details\n<script",- );+ assert.equal(renderText("<details\n<script"), "<details\n<script");// plaintext has no end tag in any parser, so it can only be neutralised.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<plaintext>" }]),- "<plaintext>",- );+ assert.equal(renderText("<plaintext>"), "<plaintext>");});test("closes the element that was opened, not the one markdown ended on", () => {// CommonMark 4.6 condition 1 ends the block at any of the four end tags, "it need// not match the start tag"; the tokenizer needs this element's own (WHATWG 13.2.5).assert.equal(- renderConversationBlocks([- { kind: "text", text: "<script>\nvar x = 1;\n</pre>" },- ]),+ renderText("<script>\nvar x = 1;\n</pre>"),"<script>\nvar x = 1;\n</pre>\n</script>",);// A </script> in a code span renders as escaped <code>: never a closer.assert.equal(- renderConversationBlocks([- { kind: "text", text: "hello <script> world `</script>`" },- ]),+ renderText("hello <script> world `</script>`"),"hello <script> world `</script>`\n</script>",);});test("closes a persistent element opened part way through a line", () => {// CommonMark starts no block here, but the browser is in script data to EOF.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "hello <script>" }]),- "hello <script>\n</script>",- );+ assert.equal(renderText("hello <script>"), "hello <script>\n</script>");// The tokenizer's raw text set is wider than condition 1: iframe and xmp too.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<iframe>" }]),- "<iframe>\n</iframe>",- );- assert.equal(- renderConversationBlocks([{ kind: "text", text: "see <xmp>" }]),- "see <xmp>\n</xmp>",- );+ assert.equal(renderText("<iframe>"), "<iframe>\n</iframe>");+ assert.equal(renderText("see <xmp>"), "see <xmp>\n</xmp>");});test("leaves an indented code block exactly as the message wrote it", () => {// Four spaces is code, so the delimiter opens nothing and a repair would alter it.assert.equal(- renderConversationBlocks([- { kind: "text", text: "Template:\n\n <!-- TODO fill this in" },- ]),+ renderText("Template:\n\n <!-- TODO fill this in"),"Template:\n\n <!-- TODO fill this in",);assert.equal(- renderConversationBlocks([- { kind: "text", text: "Example:\n\n <details>" },- ]),+ renderText("Example:\n\n <details>"),"Example:\n\n <details>",);// It cannot interrupt a paragraph, so this one really is prose.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "note\n <!-- x" }]),- "note\n <!-- x-->",- );+ assert.equal(renderText("note\n <!-- x"), "note\n <!-- x-->");});test("reads a fence opener whose info string carries a line separator", () => {// U+2028 is ordinary to markdown but a line terminator to a JavaScript dot.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "```js x\nvar a = 1;" }]),- "```js x\nvar a = 1;\n```",- );- assert.equal(- renderConversationBlocks([{ kind: "text", text: "~~~a b\nsketch" }]),- "~~~a b\nsketch\n~~~",- );+ assert.equal(renderText("```js x\nvar a = 1;"), "```js x\nvar a = 1;\n```");+ assert.equal(renderText("~~~a b\nsketch"), "~~~a b\nsketch\n~~~");});test("does not read a block quote marker as the end of a tag", () => {// The renderer strips the marker, so its > is not one the tokenizer sees: the start// tag runs on and swallows the message's own </script> as attributes.assert.equal(- renderConversationBlocks([- { kind: "text", text: "> <script\n> </script>" },- ]),+ renderText("> <script\n> </script>"),"> <script\n> </script>\n</script>",);assert.equal(- renderConversationBlocks([{ kind: "text", text: "> <script>\n> body" }]),+ renderText("> <script>\n> body"),"> <script>\n> body\n</script>",);});@@ -905,72 +758,40 @@ test("waits for the terminator the raw block is actually waiting for", () => {// The tokenizer ends a bogus comment at the first >, but CommonMark conditions 3// and 5 end at ?> and ]]>: stopping at the > in the php comparison loses the rest.assert.equal(- renderConversationBlocks([- { kind: "text", text: "<?php\nif ($a > $b) { echo 1; }" },- ]),+ renderText("<?php\nif ($a > $b) { echo 1; }"),"<?php\nif ($a > $b) { echo 1; }\n?>",);- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<![CDATA[\na > b" }]),- "<![CDATA[\na > b\n]]>",- );+ assert.equal(renderText("<![CDATA[\na > b"), "<![CDATA[\na > b\n]]>");// Condition 4 really does end at a >, and a self-closed block needs nothing.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<!DOCTYPE html>\nhi" }]),- "<!DOCTYPE html>\nhi",- );- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<?php echo 1; ?>\nhi" }]),- "<?php echo 1; ?>\nhi",- );+ assert.equal(renderText("<!DOCTYPE html>\nhi"), "<!DOCTYPE html>\nhi");+ assert.equal(renderText("<?php echo 1; ?>\nhi"), "<?php echo 1; ?>\nhi");});test("leaves a backslash-escaped tag out of the repair scan", () => {// CommonMark 2.4: \< is a literal <, so it opens nothing and needs no closer.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "\\<script>" }]),- "\\<script>",- );- assert.equal(- renderConversationBlocks([{ kind: "text", text: "\\<!-- note" }]),- "\\<!-- note",- );+ assert.equal(renderText("\\<script>"), "\\<script>");+ assert.equal(renderText("\\<!-- note"), "\\<!-- note");// And the element it hid is found again: reading the escape as live markup// swallowed the details opener as raw text.assert.equal(- renderConversationBlocks([- { kind: "text", text: "\\<script>\n\n<details>\n\nhi" },- ]),+ renderText("\\<script>\n\n<details>\n\nhi"),"\\<script>\n\n<details>\n\nhi\n\n</details>",);// A doubled backslash escapes itself, so the < after it is live.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "\\\\<script>" }]),- "\\\\<script>\n</script>",- );+ assert.equal(renderText("\\\\<script>"), "\\\\<script>\n</script>");// The escape is markdown's, so it does not apply where inlines are not read.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "```\n\\<script>" }]),- "```\n\\<script>\n```",- );+ assert.equal(renderText("```\n\\<script>"), "```\n\\<script>\n```");});test("closes a template element before emitting the next turn", () => {// Children land in a DocumentFragment that is never rendered, so later turns go too.+ assert.equal(renderText("<template>"), "<template>\n</template>");assert.equal(- renderConversationBlocks([{ kind: "text", text: "<template>" }]),- "<template>\n</template>",- );- assert.equal(- renderConversationBlocks([- { kind: "text", text: "SFC:\n\n<template>\n <div>{{ msg }}</div>" },- ]),+ renderText("SFC:\n\n<template>\n <div>{{ msg }}</div>"),"SFC:\n\n<template>\n <div>{{ msg }}</div>\n</template>",);assert.equal(- renderConversationBlocks([- { kind: "text", text: "<template>\n<td>a</td>\n</template>" },- ]),+ renderText("<template>\n<td>a</td>\n</template>"),"<template>\n<td>a</td>\n</template>",);});@@ -978,13 +799,10 @@ test("closes a template element before emitting the next turn", () => {test("keeps scanning the line a literal block ended part way through", () => {// The terminator ends the block, not the line: a details opened after it is live.assert.equal(- renderConversationBlocks([{ kind: "text", text: "<!--\n--> <details>" }]),+ renderText("<!--\n--> <details>"),"<!--\n--> <details>\n\n</details>",);- assert.equal(- renderConversationBlocks([{ kind: "text", text: "<?\n?> <script>" }]),- "<?\n?> <script>\n</script>",- );+ assert.equal(renderText("<?\n?> <script>"), "<?\n?> <script>\n</script>");});test("reduces an imported role to one line of plain text", () => {@@ -1007,22 +825,16 @@ test("reduces an imported role to one line of plain text", () => {test("keeps every line of an indented code block literal", () => {// Only the first line follows a blank one, so without state the rest is scanned live.assert.equal(- renderConversationBlocks([- { kind: "text", text: "look:\n\n first\n <script>" },- ]),+ renderText("look:\n\n first\n <script>"),"look:\n\n first\n <script>",);assert.equal(- renderConversationBlocks([- { kind: "text", text: "look:\n\n first\n <div class=\"x" },- ]),+ renderText("look:\n\n first\n <div class=\"x"),"look:\n\n first\n <div class=\"x",);// A closer in there must not spend the closer of a real open element.assert.equal(- renderConversationBlocks([- { kind: "text", text: "<details>\nreal\n\ntext\n\n a\n </details>" },- ]),+ renderText("<details>\nreal\n\ntext\n\n a\n </details>"),"<details>\nreal\n\ntext\n\n a\n </details>\n\n</details>",);});@@ -1030,39 +842,25 @@ test("keeps every line of an indented code block literal", () => {test("reads a fence against its block quote rather than the raw line", () => {// The marker keeps FENCE_LINE_PATTERN from matching, so quoted code was scanned live.assert.equal(- renderConversationBlocks([{ kind: "text", text: "> ```\n> <script>\n> ```" }]),+ renderText("> ```\n> <script>\n> ```"),"> ```\n> <script>\n> ```",);// The quote ending ends the fence, so nothing is appended for it.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "> ```js\n> var a = 1;" }]),- "> ```js\n> var a = 1;",- );+ assert.equal(renderText("> ```js\n> var a = 1;"), "> ```js\n> var a = 1;");});test("treats a backtick run as one delimiter at both ends", () => {// ```x`` has no matching run, so it is live text carrying an opener.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "```<script>``" }]),- "```<script>``\n</script>",- );+ assert.equal(renderText("```<script>``"), "```<script>``\n</script>");// A real span still masks.- assert.equal(- renderConversationBlocks([{ kind: "text", text: "`<script>`" }]),- "`<script>`",- );+ assert.equal(renderText("`<script>`"), "`<script>`");});test("reads an angle bracket link destination as a url", () => {- assert.equal(- renderConversationBlocks([{ kind: "text", text: "[x](<details>)" }]),- "[x](<details>)",- );+ assert.equal(renderText("[x](<details>)"), "[x](<details>)");// And it must not spend the closer of a real open element either.assert.equal(- renderConversationBlocks([- { kind: "text", text: "<details>\nreal\n\n[x](</details>)" },- ]),+ renderText("<details>\nreal\n\n[x](</details>)"),"<details>\nreal\n\n[x](</details>)\n\n</details>",);});@@ -1070,7 +868,7 @@ test("reads an angle bracket link destination as a url", () => {test("reads a closing tag inside a raw text element as text", () => {// </details> there is script data, so it must not spend a real details closer.assert.equal(- renderConversationBlocks([{ kind: "text", text: "<details>\n<script>\n</details>" }]),+ renderText("<details>\n<script>\n</details>"),"<details>\n<script>\n</details>\n</script>\n\n</details>",);});@@ -1093,23 +891,19 @@ test("keeps the edge spaces of a code span value", () => {test("follows a code span across a soft line break", () => {// The span is one inline, so the tag inside it is literal on both lines.assert.equal(- renderConversationBlocks([- { kind: "text", text: "<details>\nreal\n\nuse `foo\nbar </details>` here" },- ]),+ renderText("<details>\nreal\n\nuse `foo\nbar </details>` here"),"<details>\nreal\n\nuse `foo\nbar </details>` here\n\n</details>",);// A run with no match is live text, not an unterminated span.assert.equal(- renderConversationBlocks([{ kind: "text", text: "`foo\nbar <details> here" }]),+ renderText("`foo\nbar <details> here"),"`foo\nbar <details> here\n\n</details>",);});test("reads an image description as alt text", () => {assert.equal(- renderConversationBlocks([- { kind: "text", text: "<details>\nreal\n\n" },- ]),+ renderText("<details>\nreal\n\n"),"<details>\nreal\n\n\n\n</details>",);});@@ -1117,7 +911,7 @@ test("reads an image description as alt text", () => {test("closes a select the message left open", () => {// The browser stays in select insertion mode and folds the next heading in.assert.equal(- renderConversationBlocks([{ kind: "text", text: "<select>\n<option>one" }]),+ renderText("<select>\n<option>one"),"<select>\n<option>one\n\n</select>",);});diff --git a/studio/frontend/tests/credential-persistence.test.ts b/studio/frontend/tests/credential-persistence.test.tsindex 8a73dc3c801..e7291c83a8b 100644--- a/studio/frontend/tests/credential-persistence.test.ts+++ b/studio/frontend/tests/credential-persistence.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import forge from "node-forge";@@ -11,6 +10,7 @@ import type { ProviderConfig } from "../src/features/chat/api/providers-api.ts";import {installLocalStorageFake,+ readSrc,registerStoreStubResolver,} from "./helpers/kit.ts";import { loadWithStubs } from "./helpers/module-stubs.ts";@@ -29,6 +29,9 @@ const { resolveProviderCredentialEdit } = await import("../src/features/chat/provider-credential-edit.ts");+const BOOTSTRAP = readSrc("features/credentials/bootstrap.ts");+const HF_TOKEN_STORE = readSrc("features/hub/stores/hf-token-store.ts");+type UiProviderConfig = ReturnType<Parameters<typeof runCredentialBootstrap>[0]["getProviders"]@@ -199,15 +202,8 @@ test("authoritative provider cleanup removes only orphaned legacy keys", async (test("browser credential migration uses insert-if-absent endpoints", () => {- const hfSource = readFileSync(- new URL("../src/features/hub/stores/hf-token-store.ts", import.meta.url),- "utf8",- );- const providerSource = readFileSync(- new URL("../src/features/chat/sync-external-providers.ts", import.meta.url),- "utf8",- );- assert.match(hfSource, /migrateHfToken\(token\)/);+ const providerSource = readSrc("features/chat/sync-external-providers.ts");+ assert.match(HF_TOKEN_STORE, /migrateHfToken\(token\)/);assert.match(providerSource, /saveLegacyKey: migrateProviderApiKey/);});@@ -362,12 +358,8 @@ test("provider migration does not consume local input after a session change", a});test("legacy migration remains installation-wide and retry-safe", () => {- const bootstrapSource = readFileSync(- new URL("../src/features/credentials/bootstrap.ts", import.meta.url),- "utf8",- );- assert.doesNotMatch(bootstrapSource, /migration-owner|legacy_credential_owner/);- assert.doesNotMatch(bootstrapSource, /authSubjectFromJwt|currentOwner/);+ assert.doesNotMatch(BOOTSTRAP, /migration-owner|legacy_credential_owner/);+ assert.doesNotMatch(BOOTSTRAP, /authSubjectFromJwt|currentOwner/);});@@ -671,25 +663,15 @@ test("a superseded successful HF write advances the rollback baseline", async ()test("new HF edits never write the token back to localStorage", () => {- const source = readFileSync(- new URL("../src/features/hub/stores/hf-token-store.ts", import.meta.url),- "utf8",- );- assert.doesNotMatch(source, /localStorage\.setItem\(HF_TOKEN_KEY/);+ assert.doesNotMatch(HF_TOKEN_STORE, /localStorage\.setItem\(HF_TOKEN_KEY/);- assert.match(source, /persistenceError:/);- assert.match(source, /HF_TOKEN_SYNC_KEY/);+ assert.match(HF_TOKEN_STORE, /persistenceError:/);+ assert.match(HF_TOKEN_STORE, /HF_TOKEN_SYNC_KEY/);});test("legacy training HF tokens never merge back into persisted state", () => {- const source = readFileSync(- new URL(- "../src/features/training/stores/training-config-persistence.ts",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("features/training/stores/training-config-persistence.ts");assert.match(source, /if \(key === "hfToken"\) return false/);assert.match(source, /delete persistedRecord\.hfToken/);});@@ -709,10 +691,7 @@ test("provider edit state keeps, replaces, and explicitly clears saved keys", ()action: "missing",});- const source = readFileSync(- new URL("../src/features/chat/chat-providers-dialog.tsx", import.meta.url),- "utf8",- );+ const source = readSrc("features/chat/chat-providers-dialog.tsx");assert.match(source, /Saved securely\. Leave blank to keep it\./);assert.match(source, /Remove saved key/);@@ -720,14 +699,8 @@ test("provider edit state keeps, replaces, and explicitly clears saved keys", ()});test("credential gate follows authentication session transitions", () => {- const rootSource = readFileSync(- new URL("../src/app/routes/__root.tsx", import.meta.url),- "utf8",- );- const sessionSource = readFileSync(- new URL("../src/features/auth/session.ts", import.meta.url),- "utf8",- );+ const rootSource = readSrc("app/routes/__root.tsx");+ const sessionSource = readSrc("features/auth/session.ts");assert.match(rootSource, /AUTH_SESSION_CLEARED_EVENT, reconcile/);assert.match(rootSource, /AUTH_SESSION_STORED_EVENT, reconcile/);@@ -745,14 +718,10 @@ test("credential gate follows authentication session transitions", () => {);assert.match(sessionSource, /const sessionStarted = !localStorage\.getItem\(AUTH_TOKEN_KEY\)/);assert.match(sessionSource, /dispatchEvent\(new Event\(AUTH_SESSION_STORED_EVENT\)\)/);- const bootstrapSource = readFileSync(- new URL("../src/features/credentials/bootstrap.ts", import.meta.url),- "utf8",- );assert.match(sessionSource, /authSessionEpoch \+= 1/);- assert.match(bootstrapSource, /const sessionEpoch = getAuthSessionEpoch\(\)/);+ assert.match(BOOTSTRAP, /const sessionEpoch = getAuthSessionEpoch\(\)/);assert.match(- bootstrapSource,+ BOOTSTRAP,/hasAuthToken\(\) && getAuthSessionEpoch\(\) === sessionEpoch/,);diff --git a/studio/frontend/tests/crypto-uuid-boot.test.ts b/studio/frontend/tests/crypto-uuid-boot.test.tsindex ca2933f484f..1b548e68ce4 100644--- a/studio/frontend/tests/crypto-uuid-boot.test.ts+++ b/studio/frontend/tests/crypto-uuid-boot.test.ts@@ -4,11 +4,9 @@import assert from "node:assert/strict";import { readFileSync, readdirSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import { createContext, runInContext } from "node:vm";-const read = (relative: string): string =>- readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");+import { readText } from "./helpers/kit.ts";const HTML_COMMENT = /<!--[\s\S]*?-->/g;const POLYFILL_TAG = /<script\b[^>]*src="\/crypto-boot\.js"[^>]*>/;@@ -21,8 +19,10 @@ const UUID_V4 =// Check every HTML entry as raw markup so comments cannot satisfy the patterns.const PAGES = readdirSync(new URL("../", import.meta.url)).filter((name) => name.endsWith(".html"))- .map((name) => [name, read(`../${name}`).replace(HTML_COMMENT, "")] as const);-const BOOT_SCRIPT = read("../public/crypto-boot.js");+ .map(+ (name) => [name, readText(`../${name}`).replace(HTML_COMMENT, "")] as const,+ );+const BOOT_SCRIPT = readText("../public/crypto-boot.js");function boot(cryptoStub: unknown): { randomUUID?: () => string } {const sandbox = { crypto: cryptoStub } as {diff --git a/studio/frontend/tests/current-date-settings-accessibility.test.ts b/studio/frontend/tests/current-date-settings-accessibility.test.tsindex b480745ec53..c90519eaafc 100644--- a/studio/frontend/tests/current-date-settings-accessibility.test.ts+++ b/studio/frontend/tests/current-date-settings-accessibility.test.ts@@ -2,13 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-const chatTab = await readFile(- new URL("../src/features/settings/tabs/chat-tab.tsx", import.meta.url),- "utf8",-);+import { readSrcAsync } from "./helpers/kit.ts";++const chatTab = await readSrcAsync("features/settings/tabs/chat-tab.tsx");test("the current date switch has an accessible name", () => {assert.match(diff --git a/studio/frontend/tests/dataset-file-selection.test.ts b/studio/frontend/tests/dataset-file-selection.test.tsindex 002c1987299..e27688c55bb 100644--- a/studio/frontend/tests/dataset-file-selection.test.ts+++ b/studio/frontend/tests/dataset-file-selection.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {@@ -18,6 +17,8 @@ import {selectDatasetFiles,} from "../src/features/images/train/dataset-files.ts";+import { readSrcAsync, readText } from "./helpers/kit.ts";+/** a picked file of a given byte size. chunking reads only `size`, so the payload is stubbed:* materializing it made these cases allocate over a gigabyte between them. */function sized(name: string, bytes: number): File {@@ -36,10 +37,7 @@ function picked(name: string, path?: string): File {}test("accepts exactly the extensions the backend accepts", async () => {- const source = await readFile(- new URL("../../backend/routes/training.py", import.meta.url),- "utf8",- );+ const source = readText("../../backend/routes/training.py");const literals = (name: string) => {const match = new RegExp(`${name}\\s*=\\s*\\{([^}]+)\\}`).exec(source);assert.ok(match, `${name} not found in training.py`);@@ -53,10 +51,7 @@ test("accepts exactly the extensions the backend accepts", async () => {// clips are defined once, in core/training/diffusion_clip_formats.py, and read from there by// both the routes and the trainer's clip discovery. The picker has to mirror that same list.- const clipSource = await readFile(- new URL("../../backend/core/training/diffusion_clip_formats.py", import.meta.url),- "utf8",- );+ const clipSource = readText("../../backend/core/training/diffusion_clip_formats.py");const clipMatch = /CLIP_EXTS\s*=\s*frozenset\(\{([^}]+)\}\)/.exec(clipSource);assert.ok(clipMatch, "CLIP_EXTS not found in diffusion_clip_formats.py");assert.deepEqual(@@ -477,10 +472,7 @@ test("uses the flat list when the entries API is unavailable", async () => {test("the labeling grid is gated on images, not just its toggle", async () => {// A mixed folder keeps its listing on clip_count alone, so deleting the last image leaves the// grid with no toggle to close it unless the grid itself sits inside the same guard.- const source = await readFile(- new URL("../src/features/images/train/diffusion-train-panel.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("features/images/train/diffusion-train-panel.tsx");const guard = "{selectedDataset.image_count > 0 && (";const toggle = source.indexOf("<LabelingGridToggle");const grid = source.indexOf("<DatasetLabelingGrid");diff --git a/studio/frontend/tests/delete-chat-files-preference.test.ts b/studio/frontend/tests/delete-chat-files-preference.test.tsindex bde492640a0..2c584e84123 100644--- a/studio/frontend/tests/delete-chat-files-preference.test.ts+++ b/studio/frontend/tests/delete-chat-files-preference.test.ts@@ -5,7 +5,7 @@ import assert from "node:assert/strict";import { readFile } from "node:fs/promises";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrcAsync, registerBundlerResolver } from "./helpers/kit.ts";// The store reaches a relative import written without its extension, which bare// node resolves only through this. Registered before the dynamic import, since a@@ -25,10 +25,7 @@ test("deleting a chat leaves its files alone until asked", () => {test("a saved payload without the key still defaults to off", async () => {// Preferences written before this setting existed rehydrate through merge,// and a missing key there must not read as "yes, delete the files".- const source = await readFile(- new URL("../src/features/chat/stores/chat-preferences-store.ts", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("features/chat/stores/chat-preferences-store.ts");assert.match(source,/alwaysDeleteChatFiles: saved\?\.alwaysDeleteChatFiles \?\? false/,diff --git a/studio/frontend/tests/desktop-closing-overlay.test.ts b/studio/frontend/tests/desktop-closing-overlay.test.tsindex 45b24b458f9..e57f633dab7 100644--- a/studio/frontend/tests/desktop-closing-overlay.test.ts+++ b/studio/frontend/tests/desktop-closing-overlay.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";// The overlay itself is JSX, which cannot be imported here. So: drive the store the@@ -16,9 +15,7 @@ import {subscribeAppClosing,} from "../src/components/tauri/closing-signal.ts";-function source(path: string): Promise<string> {- return readFile(new URL(`../src/${path}`, import.meta.url), "utf8");-}+import { readSrc, readText } from "./helpers/kit.ts";/** The ClosingContent body, up to whatever component is declared after it. */function closingContent(screen: string): string {@@ -69,7 +66,7 @@ test("an unsubscribed listener stops hearing about quits", () => {});test("the backend hook routes both quit events into the store", async () => {- const hook = await source("hooks/use-tauri-backend.ts");+ const hook = await readSrc("hooks/use-tauri-backend.ts");assert.match(hook,@@ -95,7 +92,7 @@ test("the backend hook routes both quit events into the store", async () => {});test("the overlay covers the app instead of replacing it", async () => {- const provider = await source("app/provider.tsx");+ const provider = await readSrc("app/provider.tsx");// Unmounting the app subtree would cancel in-flight generations and drop debounced// drafts, and a declined quit has to give all of that back.@@ -106,7 +103,7 @@ test("the overlay covers the app instead of replacing it", async () => {"the overlay is back to replacing the app it should be covering",);- const screen = await source("components/tauri/startup-screen.tsx");+ const screen = await readSrc("components/tauri/startup-screen.tsx");const closingScreen = screen.slice(screen.indexOf("export function ClosingScreen()"),);@@ -118,7 +115,7 @@ test("the overlay covers the app instead of replacing it", async () => {});test("the overlay survives a modal's body pointer-events lockout", async () => {- const screen = await source("components/tauri/startup-screen.tsx");+ const screen = await readSrc("components/tauri/startup-screen.tsx");const closingScreen = screen.slice(screen.indexOf("export function ClosingScreen()"),);@@ -136,7 +133,7 @@ test("the overlay survives a modal's body pointer-events lockout", async () => {});test("the close button leaves the overlay to Rust", async () => {- const titlebar = await source("components/tauri/window-titlebar.tsx");+ const titlebar = await readSrc("components/tauri/window-titlebar.tsx");// Raising it here would put it behind the quit confirmations, one of which asks whether// to keep training. Rust raises it only once those have passed.@@ -149,8 +146,8 @@ test("the close button leaves the overlay to Rust", async () => {});test("the overlay is presentation only, with no way out of a wedged reap", async () => {- const signal = await source("components/tauri/closing-signal.ts");- const screen = await source("components/tauri/startup-screen.tsx");+ const signal = await readSrc("components/tauri/closing-signal.ts");+ const screen = await readSrc("components/tauri/startup-screen.tsx");const body = closingContent(screen);// A wedged teardown has no escape, and did not have one before this overlay either: a@@ -169,10 +166,7 @@ test("the overlay is presentation only, with no way out of a wedged reap", async});test("a quit with no window on screen raises no overlay", async () => {- const rust = await readFile(- new URL("../../src-tauri/src/main.rs", import.meta.url),- "utf8",- );+ const rust = readText("../../src-tauri/src/main.rs");// Tray Quit reaches request_quit without going through the main window, and an autostart// launch passes --hidden, whose window is built "visible": false and never shown. The@@ -189,7 +183,7 @@ test("a quit with no window on screen raises no overlay", async () => {});test("the overlay names the wait it is covering", async () => {- const screen = await source("components/tauri/startup-screen.tsx");+ const screen = await readSrc("components/tauri/startup-screen.tsx");const body = closingContent(screen);assert.match(body, /Closing Unsloth Desktop\.\.\./);@@ -199,10 +193,7 @@ test("the overlay names the wait it is covering", async () => {});test("both sides agree on the event names", async () => {- const rust = await readFile(- new URL("../../src-tauri/src/main.rs", import.meta.url),- "utf8",- );+ const rust = readText("../../src-tauri/src/main.rs");assert.match(rust,diff --git a/studio/frontend/tests/desktop-stop-intent.test.ts b/studio/frontend/tests/desktop-stop-intent.test.tsindex 46e4a9052c9..a1af74b1dfc 100644--- a/studio/frontend/tests/desktop-stop-intent.test.ts+++ b/studio/frontend/tests/desktop-stop-intent.test.ts@@ -15,6 +15,10 @@ import {markServerStopIntent,} from "../src/hooks/server-stop-intent.ts";+import { readSrc } from "./helpers/kit.ts";++const USE_TAURI_BACKEND = readSrc("hooks/use-tauri-backend.ts");+type Storage = {getItem: (key: string) => string | null;setItem: (key: string, value: string) => void;@@ -51,13 +55,6 @@ function uninstallSessionStorage(): void {Reflect.deleteProperty(globalThis, "sessionStorage");}-function hookSource(): Promise<string> {- return readFile(- new URL("../src/hooks/use-tauri-backend.ts", import.meta.url),- "utf8",- );-}-test("a fresh session carries no stop intent", () => {installSessionStorage();assert.equal(hasServerStopIntent(), false);@@ -151,7 +148,7 @@ test("the marker key belongs to nothing else in the app", async () => {});test("the hook reaches storage only through the guarded helpers", async () => {- const hook = await hookSource();+ const hook = USE_TAURI_BACKEND;// A raw sessionStorage call in the hook is the bug this module exists to prevent: the// read in checkInstallAndStart sits outside its try, so a SecurityError there rejects@@ -168,7 +165,7 @@ test("the hook reaches storage only through the guarded helpers", async () => {});test("a persisted stop is honored before preflight runs", async () => {- const hook = await hookSource();+ const hook = USE_TAURI_BACKEND;const body = hook.slice(hook.indexOf("async function checkInstallAndStart()"),@@ -196,7 +193,7 @@ test("a persisted stop is honored before preflight runs", async () => {});test("stopping records the intent before the shutdown it can outlive", async () => {- const hook = await hookSource();+ const hook = USE_TAURI_BACKEND;const body = hook.slice(hook.indexOf("async function stopServer()"),hook.indexOf("async function startInstall()"),@@ -229,7 +226,7 @@ test("stopping records the intent before the shutdown it can outlive", async ()});test("a second stop cannot run while the first is in flight", async () => {- const hook = await hookSource();+ const hook = USE_TAURI_BACKEND;// The tray item stays enabled while the server runs and the toggle branches on// statusRef, which stays "running" for the whole invoke, so two Stop clicks reach@@ -261,7 +258,7 @@ test("a second stop cannot run while the first is in flight", async () => {});test("every deliberate start drops the marker", async () => {- const hook = await hookSource();+ const hook = USE_TAURI_BACKEND;const managed = hook.slice(hook.indexOf("async function startManagedServer()"),diff --git a/studio/frontend/tests/diffusion-train-batch-cap.test.ts b/studio/frontend/tests/diffusion-train-batch-cap.test.tsindex bfab7d36431..51118e6d3cb 100644--- a/studio/frontend/tests/diffusion-train-batch-cap.test.ts+++ b/studio/frontend/tests/diffusion-train-batch-cap.test.ts@@ -9,13 +9,11 @@// labeling-grid gate is in dataset-file-selection.test.ts.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-const source = await readFile(- new URL("../src/features/images/train/diffusion-train-panel.tsx", import.meta.url),- "utf8",-);+import { readSrcAsync } from "./helpers/kit.ts";++const source = await readSrcAsync("features/images/train/diffusion-train-panel.tsx");test("the batch cap comes from the family the backend reported", () => {assert.match(source, /max_train_batch_size/);diff --git a/studio/frontend/tests/diffusion-train-deploy.test.ts b/studio/frontend/tests/diffusion-train-deploy.test.tsindex 52c0f396e37..c953e08c7dd 100644--- a/studio/frontend/tests/diffusion-train-deploy.test.ts+++ b/studio/frontend/tests/diffusion-train-deploy.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {@@ -10,6 +9,8 @@ import {resolveDiffusionTrainingBase,} from "../src/features/images/train/diffusion-train-deploy.ts";+import { readSrcAsync } from "./helpers/kit.ts";+const klein = {name: "flux.2-klein",label: "FLUX.2 Klein",@@ -99,10 +100,7 @@ test("a mirror-loaded checkpoint preselects the vendor base it copies", () => {test("the Train panel preselect actually consults the pairing", async () => {// The helper on its own changes nothing: the bug was in the preselect chain, which fell from an// exact base_repos match straight to base_repos[0]. Assert the pairing sits BETWEEN the two.- const source = await readFile(- new URL("../src/features/images/train/diffusion-train-panel.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("features/images/train/diffusion-train-panel.tsx");const paired = source.indexOf("pairedTrainingBase ??");const first = source.indexOf("family.base_repos[0]");assert.ok(paired > 0, "the preselect no longer falls back to the paired training base");diff --git a/studio/frontend/tests/diffusion-train-warmup-preset.test.ts b/studio/frontend/tests/diffusion-train-warmup-preset.test.tsindex f8f553fc943..34d9168d3e5 100644--- a/studio/frontend/tests/diffusion-train-warmup-preset.test.ts+++ b/studio/frontend/tests/diffusion-train-warmup-preset.test.ts@@ -11,7 +11,6 @@// normalization lives in its own module and is exercised directly.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {@@ -19,10 +18,9 @@ import {lrSchedulePreset,} from "../src/features/images/train/diffusion-train-lr-schedule.ts";-const source = await readFile(- new URL("../src/features/images/train/diffusion-train-panel.tsx", import.meta.url),- "utf8",-);+import { readSrcAsync } from "./helpers/kit.ts";++const source = await readSrcAsync("features/images/train/diffusion-train-panel.tsx");test("a family that recommends a ramp carries both halves of it", () => {assert.deepEqual(diff --git a/studio/frontend/tests/download-adopt-and-hydrate.test.ts b/studio/frontend/tests/download-adopt-and-hydrate.test.tsindex e739ba1955c..b1d5f7465ba 100644--- a/studio/frontend/tests/download-adopt-and-hydrate.test.ts+++ b/studio/frontend/tests/download-adopt-and-hydrate.test.ts@@ -4,11 +4,10 @@// Two decisions the download manager makes from a single reading, both of which used to be// wrong in the same way: treating a zero byte count as evidence of something it is not.-import { readFileSync } from "node:fs";import assert from "node:assert/strict";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -16,6 +15,8 @@ const { carriesOverSeed, idleProbeVerdict, seededMeasuredTransfer } = await impo"../src/features/hub/download-manager/adopt-rules.ts");+const POLL_LOOP = readSrc("features/hub/download-manager/poll-loop.ts");+test("adopting a new generation drops the previous run's byte seed", () => {// The persisted job describes generation 4; the backend reports 5 in flight. Seeding 4's bytes// while serverGeneration jumps to 5 leaves the first poll seeing no change, so the new run's@@ -99,16 +100,9 @@ test("a scan that never happened does not retire a job", () => {});test("live idle polls retire an explicitly missing target before the grace period", () => {- const src = readFileSync(- new URL(- "../src/features/hub/download-manager/poll-loop.ts",- import.meta.url,- ),- "utf8",- );- const start = src.indexOf("function handleIdleAfterProgress");- const end = src.indexOf("\nfunction handleTickError", start);- const handler = src.slice(start, end);+ const start = POLL_LOOP.indexOf("function handleIdleAfterProgress");+ const end = POLL_LOOP.indexOf("\nfunction handleTickError", start);+ const handler = POLL_LOOP.slice(start, end);assert.match(handler,@@ -116,7 +110,7 @@ test("live idle polls retire an explicitly missing target before the grace perio"an authoritative missing-target response must bypass the idle grace period",);assert.match(- src,+ POLL_LOOP,/handleIdleAfterProgress\(rt, key, madeProgress, progressResp\)/,"the live poll must pass its progress response to the idle verdict",);@@ -136,15 +130,8 @@ test("the held-transfer marker travels with the counters it describes", () => {test("the adoption path actually seeds the marker onto the job", () => {// The helper above is pure, so it cannot catch the seed being computed and// then left off the rebuilt job, which is how the marker was lost once.- const src = readFileSync(- new URL(- "../src/features/hub/download-manager/poll-loop.ts",- import.meta.url,- ),- "utf8",- );assert.match(- src,+ POLL_LOOP,/measuredTransfer:\s*seedMeasuredTransfer/,"startJob computes the seeded held-transfer marker but no longer puts it on "+ "the job, so an adopted run restores it as undefined (measured) and "diff --git a/studio/frontend/tests/download-eta-invalidation.test.ts b/studio/frontend/tests/download-eta-invalidation.test.tsindex 021faa558d3..eb78f87f826 100644--- a/studio/frontend/tests/download-eta-invalidation.test.ts+++ b/studio/frontend/tests/download-eta-invalidation.test.ts@@ -10,11 +10,11 @@// gaps time the poller, not the transfer, and would read as the burst rate.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {installLocalStorageFake,+ readSrc,registerBundlerResolver,} from "./helpers/kit.ts";@@ -62,19 +62,13 @@ test("a total that grows drops the ETA measured against the old one", () => {test("the poll loop drops a hidden tab's throttled samples", () => {// Voice used to run a second estimator of its own for a progress bar beside// the shared panel. Both are gone, so this is the only one left to guard.- const voice = readFileSync(- new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url),- "utf8",- );+ const voice = readSrc("features/settings/tabs/voice-tab.tsx");assert.ok(!voice.includes("downloadSamplesRef"),"voice no longer estimates a rate of its own",);- const source = readFileSync(- new URL("../src/features/hub/download-manager/poll-loop.ts", import.meta.url),- "utf8",- );+ const source = readSrc("features/hub/download-manager/poll-loop.ts");const guard = source.indexOf("document.hidden");assert.ok(guard > 0, "the poll loop should skip a hidden tab");const clear = source.indexOf("rt.speedSamples.length = 0", guard);diff --git a/studio/frontend/tests/download-generation-pending.test.ts b/studio/frontend/tests/download-generation-pending.test.tsindex 3f72032cc9b..299ab6b3949 100644--- a/studio/frontend/tests/download-generation-pending.test.ts+++ b/studio/frontend/tests/download-generation-pending.test.ts@@ -9,7 +9,6 @@// until a progress poll consumes it is what makes the reset reliable.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -17,10 +16,9 @@ import {PROGRESS_POLL_INTERVAL_MS,} from "../src/features/hub/download-manager/download-manager-config.ts";-const source = readFileSync(- new URL("../src/features/hub/download-manager/poll-loop.ts", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/hub/download-manager/poll-loop.ts");test("status ticks outnumber progress polls, so the race is the normal case", () => {assert.ok(diff --git a/studio/frontend/tests/download-generation-rate-reset.test.ts b/studio/frontend/tests/download-generation-rate-reset.test.tsindex e35d04aad39..c9ae83392b5 100644--- a/studio/frontend/tests/download-generation-rate-reset.test.ts+++ b/studio/frontend/tests/download-generation-rate-reset.test.ts@@ -8,7 +8,6 @@// then lands inside the measured span: 100 MB/s published 13 MB/s.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -17,16 +16,12 @@ import {computeTransferStats,} from "../src/lib/transfer-stats.ts";+import { readSrc } from "./helpers/kit.ts";+const MB = 1e6;test("a generation change clears the rate samples before the next one is taken", () => {- const source = readFileSync(- new URL(- "../src/features/hub/download-manager/poll-loop.ts",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("features/hub/download-manager/poll-loop.ts");const clear = source.indexOf("rt.speedSamples.length = 0",source.indexOf("generationChanged) {"),diff --git a/studio/frontend/tests/download-transport-after-start.test.ts b/studio/frontend/tests/download-transport-after-start.test.tsindex 88cfb49c093..e7eb105f8a2 100644--- a/studio/frontend/tests/download-transport-after-start.test.ts+++ b/studio/frontend/tests/download-transport-after-start.test.ts@@ -4,8 +4,6 @@import assert from "node:assert/strict";import test from "node:test";-import { readFileSync } from "node:fs";-import {adoptedTransports,mismatchStartAction,@@ -14,6 +12,8 @@ import {transportAfterStart,} from "../src/features/hub/download-manager/constants.ts";+import { readSrc } from "./helpers/kit.ts";+test("a start of its own keeps the transport it resolved", () => {assert.equal(transportAfterStart("http", null), "http");assert.equal(transportAfterStart("xet", undefined), "xet");@@ -162,13 +162,7 @@ test("a matching pair is left alone", () => {});test("a transport mismatch start uses the mismatch helper", () => {- const source = readFileSync(- new URL(- "../src/features/hub/download-manager/transport-conflict.ts",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("features/hub/download-manager/transport-conflict.ts");assert.match(source,/mismatchStartAction\(\s*preferred,\s*resolved,\s*last,\s*status\.resumable,\s*\)/,@@ -181,13 +175,7 @@ test("a transport mismatch start uses the mismatch helper", () => {});test("staging owns cleanup while Hub resolves exact or scoped conflicts", () => {- const source = readFileSync(- new URL(- "../src/features/hub/download-manager/use-repo-download.ts",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("features/hub/download-manager/use-repo-download.ts");const exactIndex = source.indexOf("const exact = state.conflicts[conflictKey]",);diff --git a/studio/frontend/tests/download-transport-setting.test.ts b/studio/frontend/tests/download-transport-setting.test.tsindex 1087511da38..a4e71df9d3b 100644--- a/studio/frontend/tests/download-transport-setting.test.ts+++ b/studio/frontend/tests/download-transport-setting.test.ts@@ -6,10 +6,9 @@// setting is next, the default is still Auto, and the row spells out the difference.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -17,21 +16,17 @@ const { DEFAULT_TRANSPORT_MODE, TRANSPORT, pickTransportMode } = await import("../src/features/hub/download-manager/constants.ts");-function read(path: string): string {- return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");-}--const ROW = read("features/settings/components/download-transport-row.tsx");-const PREFERENCE = read(+const ROW = readSrc("features/settings/components/download-transport-row.tsx");+const PREFERENCE = readSrc("features/hub/download-manager/transport-preference.ts",);-const GENERAL_TAB = read("features/settings/tabs/general-tab.tsx");-const TOGGLE = read("features/hub/catalog/transport-toggle.tsx");-const API = read("features/settings/api/download-transport.ts");-const POLL_LOOP = read("features/hub/download-manager/poll-loop.ts");-const SEARCH = read("features/settings/settings-search.ts");-const GENERAL_TAB_SRC = read("features/settings/tabs/general-tab.tsx");-const EN = read("i18n/locales/en.ts");+const GENERAL_TAB = readSrc("features/settings/tabs/general-tab.tsx");+const TOGGLE = readSrc("features/hub/catalog/transport-toggle.tsx");+const API = readSrc("features/settings/api/download-transport.ts");+const POLL_LOOP = readSrc("features/hub/download-manager/poll-loop.ts");+const SEARCH = readSrc("features/settings/settings-search.ts");+const GENERAL_TAB_SRC = readSrc("features/settings/tabs/general-tab.tsx");+const EN = readSrc("i18n/locales/en.ts");test("this browser's own choice beats the install setting", () => {assert.equal(pickTransportMode("xet", "http"), TRANSPORT.XET);@@ -57,8 +52,8 @@ test("a download waits for the install setting before picking a transport", () =// getTransportMode() answers from what is known, so reading it before the settings fetch// landed missed a transport picked in another browser.for (const source of [- read("features/hub/download-manager/poll-loop.ts"),- read("features/hub/download-manager/transport-conflict.ts"),+ readSrc("features/hub/download-manager/poll-loop.ts"),+ readSrc("features/hub/download-manager/transport-conflict.ts"),]) {assert.match(source, /await resolveTransportMode\(\)/);assert.ok(@@ -104,7 +99,6 @@ test("the copy explains the difference, not just the names", () => {assert.match(downloads, /hf_xet/);});-// The four below are source assertions, in this file's idiom: they pin the shape of a fix// rather than its behaviour, so each names the failure it exists for.diff --git a/studio/frontend/tests/drag-costs-no-render.test.ts b/studio/frontend/tests/drag-costs-no-render.test.tsindex 9a9956841c8..fde55d53754 100644--- a/studio/frontend/tests/drag-costs-no-render.test.ts+++ b/studio/frontend/tests/drag-costs-no-render.test.ts@@ -9,15 +9,12 @@// unit test and only shows up under the hand.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-function source(path: string): string {- return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");-}+import { readSrc } from "./helpers/kit.ts";test("the card paints a drag frame through a transform", () => {- const hook = source("features/loaded-models/use-drag-position.ts");+ const hook = readSrc("features/loaded-models/use-drag-position.ts");assert.match(hook, /panel\.style\.transform = `translate3d\(/);assert.match(hook, /frameRef\.current = requestAnimationFrame\(paint\)/);// The old path: one setPosition per pointermove, so one render per event.@@ -28,13 +25,13 @@ test("the card paints a drag frame through a transform", () => {// disconnected the observer and built a new one, and observing re-measures,// which forces a synchronous layout.test("the card's reclamp observer outlives a drag frame", () => {- const hook = source("features/loaded-models/use-drag-position.ts");+ const hook = readSrc("features/loaded-models/use-drag-position.ts");assert.match(hook, /\}, \[panelEl, reclamp\]\);/);assert.doesNotMatch(hook, /\}, \[position, panelEl, reclamp\]\);/);});test("the card hands the offset back to left/top on release", () => {- const hook = source("features/loaded-models/use-drag-position.ts");+ const hook = readSrc("features/loaded-models/use-drag-position.ts");assert.match(hook, /panel\.style\.left = `\$\{session\.lastLeft\}px`/);assert.match(hook, /panel\.style\.transform = ""/);assert.match(@@ -45,7 +42,7 @@ test("the card hands the offset back to left/top on release", () => {});test("the monitor paints a drag frame through a transform", () => {- const panel = source("components/floating-monitor.tsx");+ const panel = readSrc("components/floating-monitor.tsx");assert.match(panel, /monitor\.style\.transform = `translate3d\(/);assert.match(panel,@@ -54,7 +51,7 @@ test("the monitor paints a drag frame through a transform", () => {});test("the monitor commits its position once, on release", () => {- const panel = source("components/floating-monitor.tsx");+ const panel = readSrc("components/floating-monitor.tsx");const finish = panel.slice(panel.indexOf("function finishDrag"));assert.match(finish, /monitor\.style\.transform = ""/);assert.match(finish, /setLayout\(\(current\) =>/);@@ -63,7 +60,7 @@ test("the monitor commits its position once, on release", () => {// The measured box carries the drag's transform, so committing it mid-drag// would move the panel twice as far as the pointer went.test("a resize mid-drag does not commit the transformed box", () => {- const panel = source("components/floating-monitor.tsx");+ const panel = readSrc("components/floating-monitor.tsx");assert.match(panel, /const held = session && current \? current : null;/);assert.match(panel, /left: restLeft,/);assert.match(panel, /maxWidth: constraintsBox\.width - restLeft,/);@@ -72,7 +69,7 @@ test("a resize mid-drag does not commit the transformed box", () => {// Every frame published the monitor's box to a shared store, and each write// re-rendered every overlay subscribed to it, the loaded models card included.test("dragging the monitor does not republish its frame per frame", () => {- const panel = source("components/floating-monitor.tsx");+ const panel = readSrc("components/floating-monitor.tsx");const update = panel.slice(panel.indexOf("function updateDrag"),panel.indexOf("function finishDrag"),diff --git a/studio/frontend/tests/external-model-selection-label.test.ts b/studio/frontend/tests/external-model-selection-label.test.tsindex c0ff2d8b5c6..a8d868c986f 100644--- a/studio/frontend/tests/external-model-selection-label.test.ts+++ b/studio/frontend/tests/external-model-selection-label.test.ts@@ -19,7 +19,7 @@ import type {ExternalConnectionRef,ExternalModelRef,} from "../src/features/model-picker/components/model-selector/missing-external-model.ts";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";// Both helpers reach across the tree the way vite resolves it: the "@/" alias and an// extensionless relative import.@@ -416,10 +416,7 @@ test("the picker trigger resolves a dropped connected model before naming it", (// The catalogue only reaches the picker if chat-page builds it from the connections and// passes it down both the single-chat and compare paths.test("the chat page feeds the picker the connections behind the options", () => {- const page = readFileSync(- fileURLToPath(new URL("../src/features/chat/chat-page.tsx", import.meta.url)),- "utf8",- );+ const page = readSrc("features/chat/chat-page.tsx");assert.match(page, /availableModels: provider\.availableModels/);// Once for the memo's own type, then every hop from chat-page to the picker.assert.ok(@@ -430,12 +427,7 @@ test("the chat page feeds the picker the connections behind the options", () =>});test("the compare and audio toasts use the external-aware labels", () => {- const composer = readFileSync(- fileURLToPath(- new URL("../src/features/chat/shared-composer.tsx", import.meta.url),- ),- "utf8",- );+ const composer = readSrc("features/chat/shared-composer.tsx");assert.match(composer,/const name1 = model1\?\.id \? compareModelDisplayName\(/,@@ -447,15 +439,7 @@ test("the compare and audio toasts use the external-aware labels", () => {// The local split("/") helper that leaked the id must be gone.assert.doesNotMatch(composer, /function modelDisplayName\(/);- const audio = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/audio-attachment-adapter.ts",- import.meta.url,- ),- ),- "utf8",- );+ const audio = readSrc("features/chat/audio-attachment-adapter.ts");assert.match(audio,/activeModel\?\.name \|\|\s*externalModelLabel\(checkpoint\) \|\|/,diff --git a/studio/frontend/tests/external-sampling-payload.test.ts b/studio/frontend/tests/external-sampling-payload.test.tsindex 51a3beb2070..5b8ebd330a9 100644--- a/studio/frontend/tests/external-sampling-payload.test.ts+++ b/studio/frontend/tests/external-sampling-payload.test.ts@@ -5,12 +5,11 @@// Its function is too large to call here, so the gated spreads are extracted and evaluated.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import ts from "typescript";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -27,10 +26,7 @@ const PARAMS = {presencePenalty: 0.3,};-const source = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",-);+const source = readSrc("features/chat/api/chat-adapter.ts");const tree = ts.createSourceFile("chat-adapter.ts",source,@@ -140,10 +136,7 @@ test("an unknown provider stays on the OpenAI-compatible shape", () => {});test("the panel and the request read the same capability flags", () => {- const sheet = readFileSync(- new URL("../src/features/chat/chat-settings-sheet.tsx", import.meta.url),- "utf8",- );+ const sheet = readSrc("features/chat/chat-settings-sheet.tsx");// Gating the body on anything but these flags is how panel and request drifted apart.assert.match(sheet, /Boolean\(providerCapabilities\?\.minP\)/);assert.match(sheet, /Boolean\(providerCapabilities\?\.repetitionPenalty\)/);diff --git a/studio/frontend/tests/find-in-page.test.ts b/studio/frontend/tests/find-in-page.test.tsindex 3eb57112f63..2adc1385016 100644--- a/studio/frontend/tests/find-in-page.test.ts+++ b/studio/frontend/tests/find-in-page.test.ts@@ -7,7 +7,6 @@import assert from "node:assert/strict";import { spawnSync } from "node:child_process";-import { readFileSync } from "node:fs";import { readFile } from "node:fs/promises";import test from "node:test";@@ -42,14 +41,24 @@ import {startPositionAt,} from "../src/features/find-in-page/lib/find-text-index.ts";+import { readSrc, readSrcAsync } from "./helpers/kit.ts";++const FIND_BAR = readSrc("features/find-in-page/components/find-bar.tsx");+const FIND_IN_PAGE = readSrc(+ "features/find-in-page/components/find-in-page.tsx",+);+const USE_FIND_IN_PAGE = readSrc(+ "features/find-in-page/hooks/use-find-in-page.ts",+);+const FIND_DOM = readSrc("features/find-in-page/lib/find-dom.ts");+const FIND_TEXT_INDEX = readSrc("features/find-in-page/lib/find-text-index.ts");+const USE_SHORTCUT = readSrc("features/settings/hooks/use-shortcut.ts");+const INDEX = readSrc("index.css");+/** The feature's component module as one string. */async function readComponentSource(): Promise<string> {- return await readFile(- new URL(- "../src/features/find-in-page/components/find-in-page.tsx",- import.meta.url,- ),- "utf8",+ return await readSrcAsync(+ "features/find-in-page/components/find-in-page.tsx",);}@@ -552,12 +561,8 @@ function record(test("the selection fallback hands the caret back to the field", async () => {// The caret goes with the selection on WebKit and Blink: the field still reports as active// while every keystroke is swallowed.- const engine = await readFile(- new URL("../src/features/find-in-page/lib/find-dom.ts", import.meta.url),- "utf8",- );- const fallback = engine.slice(- engine.indexOf("export function selectRangeFallback"),+ const fallback = FIND_DOM.slice(+ FIND_DOM.indexOf("export function selectRangeFallback"),);const body = fallback.slice(0, fallback.indexOf("\n}"));assert.match(body, /holdCaret\(\)/);@@ -1269,13 +1274,9 @@ function cssRule(css: string, selector: string): string {}test("the stylesheet paints the two highlights the code registers", async () => {- const css = await readFile(- new URL("../src/index.css", import.meta.url),- "utf8",- );for (const name of [FIND_HIGHLIGHT, FIND_HIGHLIGHT_ACTIVE]) {assert.ok(- css.includes(`::highlight(${name})`),+ INDEX.includes(`::highlight(${name})`),`${name} is registered but never painted`,);}@@ -1396,31 +1397,13 @@ test("registered ranges are cleared and repainted before deletion or replacement});test("the bar keeps itself out of the region it searches", async () => {- const bar = await readFile(- new URL(- "../src/features/find-in-page/components/find-bar.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(bar, new RegExp(`${FIND_SKIP_ATTRIBUTE}=`));- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );- assert.match(engine, /FIND_SKIP_ATTRIBUTE/);+ assert.match(FIND_BAR, new RegExp(`${FIND_SKIP_ATTRIBUTE}=`));+ assert.match(USE_FIND_IN_PAGE, /FIND_SKIP_ATTRIBUTE/);});test("light mode is the chatbox's background, under a slightly heavier shadow", async () => {- const css = await readFile(- new URL("../src/index.css", import.meta.url),- "utf8",- );- const composer = cssRule(css, ".unsloth-composer-surface");- const bar = cssRule(css, ".find-bar-surface");+ const composer = cssRule(INDEX, ".unsloth-composer-surface");+ const bar = cssRule(INDEX, ".find-bar-surface");// The composer is the reference, not a copied colour, so a restyle fails here.const background = /background-color:\s*(#[0-9a-f]{6});/i.exec(composer);@@ -1466,13 +1449,9 @@ test("light mode is the chatbox's background, under a slightly heavier shadow",});test("dark mode sits above the cards it floats over", async () => {- const css = await readFile(- new URL("../src/index.css", import.meta.url),- "utf8",- );const value = (selector: string, property: string) => {const hit = new RegExp(`${property}:\\s*([^;]+);`).exec(- cssRule(css, selector),+ cssRule(INDEX, selector),);assert.ok(hit, `${selector} has no ${property}`);return hit[1].trim();@@ -1491,21 +1470,14 @@ test("dark mode sits above the cards it floats over", async () => {});test("the bar stays out of a backgrounded scope, and off the document origin", async () => {- const bar = await readFile(- new URL(- "../src/features/find-in-page/components/find-bar.tsx",- import.meta.url,- ),- "utf8",- );// Every modal, not just Settings: Radix marks the shell aria-hidden for as long as one is up,// and `enabled` is read at render, which a dialog opening need not cause.assert.match(- bar,+ FIND_BAR,/isSurfaceBackgrounded\(`\[\$\{FIND_SCOPE_ATTRIBUTE\}\]`\)/,);// Fixed, not absolute: on a route whose outer container scrolls, an absolute bar scrolls away.- const surface = /className="(find-bar-surface[^"]*)"/.exec(bar);+ const surface = /className="(find-bar-surface[^"]*)"/.exec(FIND_BAR);assert.ok(surface);assert.match(surface[1], /\bfixed\b/);assert.equal(/\babsolute\b/.test(surface[1]), false);@@ -1516,7 +1488,9 @@ test("the bar stays out of a backgrounded scope, and off the document origin", a// 22.25/28.25rem is exactly the previous short-counter width: fixed input + 12rem chrome.assert.match(surface[1], /(?:^|\s)w-\[22\.25rem\](?:\s|$)/);assert.match(surface[1], /(?:^|\s)sm:w-\[28\.25rem\](?:\s|$)/);- const input = /<input[\s\S]*?className=\{cn\([\s\S]*?"([^"]*)"/.exec(bar);+ const input = /<input[\s\S]*?className=\{cn\([\s\S]*?"([^"]*)"/.exec(+ FIND_BAR,+ );assert.ok(input);assert.match(input[1], /\bflex-1\b/);assert.equal(/\bw-(?:40|64)\b/.test(input[1]), false);@@ -1525,62 +1499,43 @@ test("the bar stays out of a backgrounded scope, and off the document origin", atest("the reveal looks again while the scroll is still moving", async () => {// Such a subtree contributes placeholder height until it renders, clamping the first scroll// 3415px short on all three engines. The node suite cannot see a scroll.- const dom = await readFile(- new URL("../src/features/find-in-page/lib/find-dom.ts", import.meta.url),- "utf8",- );assert.match(- dom,+ FIND_DOM,/export function scrollRangeIntoView\(range: Range\): boolean/,);- const reveal = dom.slice(dom.indexOf("function revealPass("));+ const reveal = FIND_DOM.slice(FIND_DOM.indexOf("function revealPass("));const body = reveal.slice(0, reveal.indexOf("\n}\n"));assert.match(body,/if \(!scrollRangeIntoView\(range\) \|\| tries <= 1\) return;/,);assert.match(body, /tries - 1/);- assert.match(dom, /revealRangeWhenPainted\(range: Range, tries = \d\)/);+ assert.match(FIND_DOM, /revealRangeWhenPainted\(range: Range, tries = \d\)/);assert.match(body, /requestAnimationFrame\(/);assert.match(body, /range\.startContainer\.isConnected/);- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",+ assert.match(USE_FIND_IN_PAGE, /revealRangeWhenPainted\(activeRange\)/);+ assert.equal(+ /scrollRangeIntoView\(activeRange\)/.test(USE_FIND_IN_PAGE),+ false,);- assert.match(engine, /revealRangeWhenPainted\(activeRange\)/);- assert.equal(/scrollRangeIntoView\(activeRange\)/.test(engine), false);});test("a dismissed or superseded search abandons its queued reveal passes", async () => {// The workspace stays mounted when the bar closes, so `isConnected` stays true and the old// chain keeps scrolling to a dismissed match.- const dom = await readFile(- new URL("../src/features/find-in-page/lib/find-dom.ts", import.meta.url),- "utf8",- );- const entry = dom.slice(- dom.indexOf("export function revealRangeWhenPainted"),+ const entry = FIND_DOM.slice(+ FIND_DOM.indexOf("export function revealRangeWhenPainted"),);assert.match(entry.slice(0, entry.indexOf("\n}\n")),/cancelRevealPasses\(\)/,);- const pass = dom.slice(dom.indexOf("function revealPass("));+ const pass = FIND_DOM.slice(FIND_DOM.indexOf("function revealPass("));assert.match(pass.slice(0, pass.indexOf("\n}\n")),/if \(generation !== revealGeneration\) return;/,);- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );- assert.match(engine, /cancelRevealPasses\(\);/);+ assert.match(USE_FIND_IN_PAGE, /cancelRevealPasses\(\);/);});test("a query too large to compile falls back instead of throwing on the first scan", () => {@@ -1838,14 +1793,11 @@ test("the grapheme fences do not depend on lookbehind", async () => {// JavaScriptCore only shipped lookbehind in Safari 16.4, and a pattern using one throws on older// engines straight into the unfenced literal scan, quietly undoing both boundaries. So the start// of the fence is checked in code and the pattern carries none.- const source = await readFile(- new URL(- "../src/features/find-in-page/lib/find-text-index.ts",- import.meta.url,- ),- "utf8",+ assert.equal(+ FIND_TEXT_INDEX.includes("(?<"),+ false,+ "no lookbehind in the pattern",);- assert.equal(source.includes("(?<"), false, "no lookbehind in the pattern");const real = globalThis.RegExp;const refuse = (pattern: string, flags?: string) => {@@ -1967,22 +1919,18 @@ test("an engine whose `containing` is off by one is not trusted with it", () =>test("the seek probe is asked once, on a fixture the spec settles", () => {// Once per process: a probe on the hot path is the cost the budget exists to avoid.- const source = readFileSync(- new URL(- "../src/features/find-in-page/lib/find-text-index.ts",- import.meta.url,- ),- "utf8",- );- assert.match(source, /let seeksBoundaries: boolean \| undefined;/);+ assert.match(FIND_TEXT_INDEX, /let seeksBoundaries: boolean \| undefined;/);assert.match(- source,+ FIND_TEXT_INDEX,/if \(seeksBoundaries !== undefined\) return seeksBoundaries;/,);// `containing(1)` over a code unit and a surrogate pair is the start of the pair, per the spec.- assert.match(source, /probe\.containing\(1\)\?\.index === 1/);+ assert.match(FIND_TEXT_INDEX, /probe\.containing\(1\)\?\.index === 1/);// The definition, the seek in `startsGrapheme`, and the junction check a cut asks.- assert.equal((source.match(/segmenterSeeksBoundaries\(/g) ?? []).length, 3);+ assert.equal(+ (FIND_TEXT_INDEX.match(/segmenterSeeksBoundaries\(/g) ?? []).length,+ 3,+ );});test("a query that needs no pattern is not given one", () => {@@ -1997,15 +1945,13 @@ test("a query that needs no pattern is not given one", () => {test("plain text does not pay for the boundary check", () => {// The segmenter is asked only where something could actually join, which nothing below U+0300// can. Latin prose therefore costs one comparison per match rather than a segmentation.- const source = readFileSync(- new URL(- "../src/features/find-in-page/lib/find-text-index.ts",- import.meta.url,- ),- "utf8",+ assert.match(+ FIND_TEXT_INDEX,+ /const JOINS_GRAPHEME = \/\[\^\\u0000-\\u02ff\]\//,+ );+ const guard = FIND_TEXT_INDEX.slice(+ FIND_TEXT_INDEX.indexOf("function alignsToGraphemes"),);- assert.match(source, /const JOINS_GRAPHEME = \/\[\^\\u0000-\\u02ff\]\//);- const guard = source.slice(source.indexOf("function alignsToGraphemes"));const before = guard.indexOf("JOINS_GRAPHEME");const asks = guard.indexOf("graphemeSegmenter()");assert.ok(before > 0 && before < asks, "the cheap test comes first");@@ -2442,81 +2388,51 @@ test("nothing below U+0300 can join a grapheme, which is what the fast path rest});test("a match with no geometry is aimed at through its nearest laid-out ancestor", async () => {- const dom = await readFile(- new URL("../src/features/find-in-page/lib/find-dom.ts", import.meta.url),- "utf8",- );// Such text has a collapsed rect while the subtree's own box keeps its placeholder geometry.assert.match(- dom,+ FIND_DOM,/export function revealRect\(range: Range\): DOMRect \| null/,);- assert.match(dom, /export function rangeTop\(range: Range\): number \| null/);- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",+ assert.match(+ FIND_DOM,+ /export function rangeTop\(range: Range\): number \| null/,+ );+ assert.match(USE_FIND_IN_PAGE, /const top = rangeTop\(range\);/);+ assert.equal(+ /range\.getBoundingClientRect\(\)/.test(USE_FIND_IN_PAGE),+ false,);- assert.match(engine, /const top = rangeTop\(range\);/);- assert.equal(/range\.getBoundingClientRect\(\)/.test(engine), false);});test("a fresh query starts from the scroll container's top, not the window's", async () => {- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );// The viewport starts below the navbar, so a match clipped off its top still has positive `top`.- assert.match(engine, /top >= scrollViewportTop\(range\)/);- assert.equal(/top >= 0/.test(engine), false);+ assert.match(USE_FIND_IN_PAGE, /top >= scrollViewportTop\(range\)/);+ assert.equal(/top >= 0/.test(USE_FIND_IN_PAGE), false);});test("a pending query clears the previous highlight before the next paint", async () => {- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );// The input value is committed during the event. A passive effect may run only after the browser// has painted that new value beside the old query's ranges, which is the visible `sta`/`stan`// mismatch this guards. A layout effect clears those ranges in the same commit, before paint.- assert.match(engine, /import \{[^}]*useLayoutEffect[^}]*\} from "react";/);assert.match(- engine,+ USE_FIND_IN_PAGE,+ /import \{[^}]*useLayoutEffect[^}]*\} from "react";/,+ );+ assert.match(+ USE_FIND_IN_PAGE,/useLayoutEffect\(\(\) => \{\s*if \(queryPending\) \{\s*cancelRevealPasses\(\);\s*clearHighlights\(\);/,);});test("re-indexing while the document changes is a throttle, and says so", async () => {- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );// A debounce would freeze the count for as long as a reply takes to write.- assert.match(engine, /REINDEX_INTERVAL_MS/);- assert.equal(/REINDEX_DEBOUNCE_MS/.test(engine), false);- assert.match(engine, /A throttle rather than a debounce/);+ assert.match(USE_FIND_IN_PAGE, /REINDEX_INTERVAL_MS/);+ assert.equal(/REINDEX_DEBOUNCE_MS/.test(USE_FIND_IN_PAGE), false);+ assert.match(USE_FIND_IN_PAGE, /A throttle rather than a debounce/);});test("the bar has no border, and its buttons have a hover that shows", async () => {- const bar = await readFile(- new URL(- "../src/features/find-in-page/components/find-bar.tsx",- import.meta.url,- ),- "utf8",- );- const surface = /className="(find-bar-surface[^"]*)"/.exec(bar);+ const surface = /className="(find-bar-surface[^"]*)"/.exec(FIND_BAR);assert.ok(surface, "the bar no longer wears the shared surface class");assert.equal(/\bborder\b/.test(surface[1]),@@ -2524,44 +2440,36 @@ test("the bar has no border, and its buttons have a hover that shows", async ()"the bar took a border back",);// The ghost variant's own `--muted/50` hover lands within a shade of this surface.- assert.match(bar, /hover:bg-black\/\[0\.06\] dark:hover:bg-white\/10/);- assert.equal((bar.match(/className=\{FIND_BUTTON_CLASS\}/g) ?? []).length, 3);+ assert.match(FIND_BAR, /hover:bg-black\/\[0\.06\] dark:hover:bg-white\/10/);+ assert.equal(+ (FIND_BAR.match(/className=\{FIND_BUTTON_CLASS\}/g) ?? []).length,+ 3,+ );});test("a long query rewinds to its first character when focus leaves", async () => {// Typing past the width of the field scrolls it, and a bar left showing the tail of a word says// nothing about what was searched for.- const bar = await readFile(- new URL(- "../src/features/find-in-page/components/find-bar.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(bar, /onBlur=\{rewindToStart\}/);- assert.match(bar, /input\.setSelectionRange\(0, 0\);/);- assert.match(bar, /input\.scrollLeft = 0;/);- assert.match(bar, /onMouseDown=\{keepFocusInField\}/);+ assert.match(FIND_BAR, /onBlur=\{rewindToStart\}/);+ assert.match(FIND_BAR, /input\.setSelectionRange\(0, 0\);/);+ assert.match(FIND_BAR, /input\.scrollLeft = 0;/);+ assert.match(FIND_BAR, /onMouseDown=\{keepFocusInField\}/);});test("the observer watches the attributes a workspace switch flips", async () => {// Switching between kept-alive workspaces flips `inert` rather than mutating children.- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );- assert.match(engine, /attributeFilter: \[[^\]]*"inert"/);+ assert.match(USE_FIND_IN_PAGE, /attributeFilter: \[[^\]]*"inert"/);// `open` too: it is all a `<details>` changes, while its body goes from visible to not.- assert.match(engine, /attributeFilter: \[[^\]]*"open"/);+ assert.match(USE_FIND_IN_PAGE, /attributeFilter: \[[^\]]*"open"/);// Not the whole stream: `class` changes on every hover. Scanned, not matched, since the// comments in between make a regex backtrack badly.- const opensAttributes = engine.indexOf("attributes: true,");- const opensFilter = engine.indexOf("attributeFilter:", opensAttributes);+ const opensAttributes = USE_FIND_IN_PAGE.indexOf("attributes: true,");+ const opensFilter = USE_FIND_IN_PAGE.indexOf(+ "attributeFilter:",+ opensAttributes,+ );assert.ok(opensAttributes !== -1 && opensFilter > opensAttributes);- const between = engine.slice(+ const between = USE_FIND_IN_PAGE.slice(opensAttributes + "attributes: true,".length,opensFilter,);@@ -2572,7 +2480,7 @@ test("the observer watches the attributes a workspace switch flips", async () =>true,"nothing else is being observed between the flag and its filter",);- assert.equal(engine.includes('attributeFilter: ["class"'), false);+ assert.equal(USE_FIND_IN_PAGE.includes('attributeFilter: ["class"'), false);});/** Stand in for the document `resolvePortalSurfaces` queries: node has no version of one. */@@ -2628,11 +2536,7 @@ test("explicit monitor portals are searched but are not dismissible surfaces", aelse view.document = undefined;}- const dom = await readFile(- new URL("../src/features/find-in-page/lib/find-dom.ts", import.meta.url),- "utf8",- );- assert.match(dom, /export function resolveDismissiblePortalSurfaces/);+ assert.match(FIND_DOM, /export function resolveDismissiblePortalSurfaces/);for (const path of ["../src/features/api-monitor/api-monitor-overlay.tsx",@@ -2657,50 +2561,29 @@ test("a surface inside the scope, or inside one already taken, is not indexed tw});test("the observer watches the document, since a portal lands outside the scope", async () => {- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );// A popover renders to the body: an observer on the scope alone never hears one open or close.- assert.match(engine, /scope\?\.ownerDocument\?\.body \?\? scope/);+ assert.match(USE_FIND_IN_PAGE, /scope\?\.ownerDocument\?\.body \?\? scope/);// `data-state` is all a dismissed one changes, and it keeps its box until the animation ends.- assert.match(engine, /attributeFilter: \[[^\]]*"data-state"/);+ assert.match(USE_FIND_IN_PAGE, /attributeFilter: \[[^\]]*"data-state"/);});test("the rows progressive completion adds are re-anchored, not renumbered", async () => {// Progressive completion PREPENDS, and match 3 of the tail is not match 3 of the thread.- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );assert.match(- engine,+ USE_FIND_IN_PAGE,/completeProgressiveMounts\([\s\S]*?\.then\(\(\) => \{[\s\S]*?search\(false, reindex\(\)\);/,);// `reindex` answers false when nothing came in, so a settled thread's probe takes back no Enter.- assert.equal(engine.includes("rebuild("), false);+ assert.equal(USE_FIND_IN_PAGE.includes("rebuild("), false);});test("Escape closes the bar from the walk buttons, not just the field", async () => {- const bar = await readFile(- new URL(- "../src/features/find-in-page/components/find-bar.tsx",- import.meta.url,- ),- "utf8",- );// On the WINDOW, in the capture phase, for the lifetime of the open bar. A handler on the bar// only reaches presses that started inside it, so clicking a message to read it left a bar// Escape would not close -- and with a tool request waiting, that same unprevented Escape went// on to `declineToolRequest`, which is bare Escape and is not shielded by `isTextEntryFocused`// on a message body. Closing a find bar must not be able to answer a tool request.- const effect = bar.slice(bar.indexOf("const onEscape ="));+ const effect = FIND_BAR.slice(FIND_BAR.indexOf("const onEscape ="));const body = effect.slice(0, effect.indexOf("window.addEventListener"));assert.match(body, /event\.key !== "Escape"/);assert.match(body, /event\.preventDefault\(\);/);@@ -2715,7 +2598,7 @@ test("Escape closes the bar from the walk buttons, not just the field", async ()assert.match(body, /isSurfaceBackgrounded\(/);assert.match(body, /resolveDismissiblePortalSurfaces\(/);// And nothing left on the landmark, which would take the inside presses before the window does.- const landmark = bar.slice(bar.indexOf('role="search"'));+ const landmark = FIND_BAR.slice(FIND_BAR.indexOf('role="search"'));assert.equal(landmark.slice(0, landmark.indexOf(">")).includes("onKeyDown"),false,@@ -2724,23 +2607,12 @@ test("Escape closes the bar from the walk buttons, not just the field", async ()test("only threads this search can read are forced to finish mounting", async () => {// Completing globally would make a retained conversation mount every row it withheld.- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );assert.match(- engine,+ USE_FIND_IN_PAGE,/completeProgressiveMounts\(\(viewport\) =>\s*\n?\s*indexReaches\(scope, viewport\)/,);- const progressive = await readFile(- new URL(- "../src/components/assistant-ui/progressive-messages.tsx",- import.meta.url,- ),- "utf8",+ const progressive = await readSrcAsync(+ "components/assistant-ui/progressive-messages.tsx",);// The exit has to read the filtered set, or a declined completer holds it open forever.assert.match(@@ -2753,60 +2625,41 @@ test("the chord is left to the browser when the scope is behind a modal", async// `useShortcut` prevents the event BEFORE the handler, so declining inside it kills the chord.const controller = await readComponentSource();assert.match(controller, /claims: \(\) => !isSurfaceBackgrounded\(/);- const shortcut = await readFile(- new URL("../src/features/settings/hooks/use-shortcut.ts", import.meta.url),- "utf8",- );- const consume = shortcut.indexOf("event.preventDefault();");+ const consume = USE_SHORTCUT.indexOf("event.preventDefault();");assert.ok(consume > 0);- assert.ok(shortcut.lastIndexOf("latestRef.current.claims?.()", consume) > 0);+ assert.ok(+ USE_SHORTCUT.lastIndexOf("latestRef.current.claims?.()", consume) > 0,+ );});test("the Enter that commits an IME candidate is left alone", async () => {- const bar = await readFile(- new URL(- "../src/features/find-in-page/components/find-bar.tsx",- import.meta.url,- ),- "utf8",- );// Ahead of preventDefault, or the composition is discarded before the guard is reached.- const enter = bar.slice(bar.indexOf('event.key === "Enter"'));+ const enter = FIND_BAR.slice(FIND_BAR.indexOf('event.key === "Enter"'));const guard = enter.indexOf("isImeComposing(event.nativeEvent)");const prevent = enter.indexOf("event.preventDefault()");assert.ok(guard > 0 && guard < prevent);});test("closing the bar hands focus back to where it came from", async () => {- const bar = await readFile(- new URL(- "../src/features/find-in-page/components/find-bar.tsx",- import.meta.url,- ),- "utf8",- );// Captured above the effect that focuses the field, or it reads the field it is about to fill.- const capture = bar.indexOf("const active = document.activeElement");- const takeFocus = bar.indexOf("input.select();");+ const capture = FIND_BAR.indexOf("const active = document.activeElement");+ const takeFocus = FIND_BAR.indexOf("input.select();");assert.ok(capture > 0 && capture < takeFocus);- assert.match(bar, /origin\.focus\(\);/);+ assert.match(FIND_BAR, /origin\.focus\(\);/);// First answer only: StrictMode replays the effect, and by the second run the field has focus.- assert.match(bar, /originRef\.current === null &&/);+ assert.match(FIND_BAR, /originRef\.current === null &&/);// Against the bar's element, not `data-find-skip`, which the composer carries.- assert.match(bar, /barRef\.current\?\.contains\(active\) !== true/);- assert.equal(bar.includes("closest(`[${FIND_SKIP_ATTRIBUTE}]`)"), false);+ assert.match(FIND_BAR, /barRef\.current\?\.contains\(active\) !== true/);+ assert.equal(FIND_BAR.includes("closest(`[${FIND_SKIP_ATTRIBUTE}]`)"), false);assert.match(- bar,+ FIND_BAR,/if \(focused !== null && focused !== document\.body\) return;/,);});test("the chat composer is out of the searchable scope", async () => {// Its draft lives in a textarea the index cannot read, leaving find only the pill labels.- const thread = await readFile(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );+ const thread = await readSrcAsync("components/assistant-ui/thread.tsx");const root = thread.slice(thread.indexOf("<ComposerPrimitive.Root"));assert.match(root.slice(0, root.indexOf(">")),@@ -2815,24 +2668,22 @@ test("the chat composer is out of the searchable scope", async () => {});test("the reader is kept on the occurrence, not on the number", async () => {- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );assert.match(- engine,+ USE_FIND_IN_PAGE,/activeStartRef\.current = active >= 0 \? matches\[active\]\.start : null;/,);// Read BEFORE the new list is installed, or it is the new list's answer being read back.- const read = engine.indexOf("const wasAt = activeStartRef.current;");- const install = engine.indexOf("matchesRef.current = matches;", read - 400);+ const read = USE_FIND_IN_PAGE.indexOf(+ "const wasAt = activeStartRef.current;",+ );+ const install = USE_FIND_IN_PAGE.indexOf(+ "matchesRef.current = matches;",+ read - 400,+ );assert.ok(read > 0 && read < install);- assert.match(engine, /ordinalOfStart\(matches, wasAt\)/);+ assert.match(USE_FIND_IN_PAGE, /ordinalOfStart\(matches, wasAt\)/);assert.match(- engine,+ USE_FIND_IN_PAGE,/at === -1 \? firstMatchFromViewport\(index, matches\) : at/,);});@@ -2840,22 +2691,18 @@ test("the reader is kept on the occurrence, not on the number", async () => {test("the ordinal survives an append and nothing else", async () => {// A streaming reply only adds at the tail; history above, `inert` flipping or a breakpoint// revealing a column each renumber the list.- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );// One rule, and it lives in the pure module so the tests below can exercise it directly.assert.match(- engine,+ USE_FIND_IN_PAGE,/return renumbersMatches\(before, indexRef\.current, activeStartRef\.current\);/,);- assert.equal(engine.includes("search(false, false)"), false);- assert.equal((engine.match(/search\(false, reindex\(\)\)/g) ?? []).length, 2);+ assert.equal(USE_FIND_IN_PAGE.includes("search(false, false)"), false);+ assert.equal(+ (USE_FIND_IN_PAGE.match(/search\(false, reindex\(\)\)/g) ?? []).length,+ 2,+ );assert.match(- engine,+ USE_FIND_IN_PAGE,/reindex\(\);\n\s*\/\/[^\n]*\n\s*search\(false, true\);/,);});@@ -2863,37 +2710,30 @@ test("the ordinal survives an append and nothing else", async () => {test("every navigation waits for the query to settle, buttons included", async () => {// The buttons stay enabled on the previous query's count while an edit is pending, and `apply`// will not paint until it settles, so calling `next`/`previous` from a click dropped it silently.- const bar = await readFile(- new URL(- "../src/features/find-in-page/components/find-bar.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(bar, /onClick=\{\(\) => stepWhenSettled\(-1\)\}/);- assert.match(bar, /onClick=\{\(\) => stepWhenSettled\(1\)\}/);+ assert.match(FIND_BAR, /onClick=\{\(\) => stepWhenSettled\(-1\)\}/);+ assert.match(FIND_BAR, /onClick=\{\(\) => stepWhenSettled\(1\)\}/);// No control reaches the raw pair, so a new one cannot copy the losing spelling.- assert.equal(/onClick=\{(next|previous)\}/.test(bar), false);+ assert.equal(/onClick=\{(next|previous)\}/.test(FIND_BAR), false);// Reaching the handler at all: a settled zero must not disable the walk while the next query is// still pending, or editing "no matches" into a match loses the press to a disabled button.assert.match(- bar,+ FIND_BAR,/const canStep = searching && \(count > 0 \|\| queryPending\);/,);- assert.equal((bar.match(/disabled=\{!canStep\}/g) ?? []).length, 2);- assert.equal(bar.includes("disabled={count === 0}"), false);+ assert.equal((FIND_BAR.match(/disabled=\{!canStep\}/g) ?? []).length, 2);+ assert.equal(FIND_BAR.includes("disabled={count === 0}"), false);// The helper queues the step and forces the settle rather than dropping it.assert.match(- bar,+ FIND_BAR,/if \(queryPending\) \{\s*queuedStepsRef\.current\.push\(\{ query, delta \}\);[\s\S]*?settleQuery\(\);/,);- assert.match(bar, /filter\([\s\S]*?\(step\) => step\.query === query/);+ assert.match(FIND_BAR, /filter\([\s\S]*?\(step\) => step\.query === query/);- assert.match(bar, /queuedStepsRef\.current = \[\.\.\.pendingSteps\]/);- assert.match(bar, /for \(const step of steps\)/);+ assert.match(FIND_BAR, /queuedStepsRef\.current = \[\.\.\.pendingSteps\]/);+ assert.match(FIND_BAR, /for \(const step of steps\)/);- assert.match(bar, /if \(count > 0\) \{\s*for \(const step of steps\)/);+ assert.match(FIND_BAR, /if \(count > 0\) \{\s*for \(const step of steps\)/);});test("the seam between the workspace and the surfaces in front of it is recorded", () => {@@ -3054,36 +2894,28 @@ test("history arriving above the reader still renumbers the list", () => {test("a breakpoint that changes what is rendered invalidates the index", async () => {// Crossing one reveals whole columns with nothing in the DOM to observe.- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",+ assert.match(+ USE_FIND_IN_PAGE,+ /window\.addEventListener\("resize", invalidate\);/,);- assert.match(engine, /window\.addEventListener\("resize", invalidate\);/);- assert.match(engine, /window\.removeEventListener\("resize", invalidate\);/);assert.match(- engine,+ USE_FIND_IN_PAGE,+ /window\.removeEventListener\("resize", invalidate\);/,+ );+ assert.match(+ USE_FIND_IN_PAGE,/const invalidate = \(\) => \{[\s\S]*?REINDEX_INTERVAL_MS\);/,);});test("closing preserves the query while leaving the shell forgets the session", async () => {- const controller = await readFile(- new URL(- "../src/features/find-in-page/components/find-in-page.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(controller, /const \[query, setQuery\] = useState\(""\);/);+ assert.match(FIND_IN_PAGE, /const \[query, setQuery\] = useState\(""\);/);assert.match(- controller,+ FIND_IN_PAGE,/const close = useCallback\(\(\) => \{[\s\S]*?setOpen\(false\);[\s\S]*?\}, \[\]\);/,);- assert.equal(controller.includes('setQuery("")'), false);- assert.equal(controller.includes("useFindInPageStore"), false);+ assert.equal(FIND_IN_PAGE.includes('setQuery("")'), false);+ assert.equal(FIND_IN_PAGE.includes("useFindInPageStore"), false);});test("the capped window follows the reader, not the top of the document", () => {@@ -3212,58 +3044,36 @@ test("the counter says '+' only when the cap actually cut something off", () =>});test("the cap flag is what the bar renders, not the count", async () => {- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );assert.match(- engine,+ USE_FIND_IN_PAGE,/findMatches\(\s*\n\s*index,\s*\n\s*queryRef\.current,\s*\n\s*MAX_MATCHES \+ 1,/,);- assert.match(engine, /cappedRef\.current = matches\.length > MAX_MATCHES;/);+ assert.match(+ USE_FIND_IN_PAGE,+ /cappedRef\.current = matches\.length > MAX_MATCHES;/,+ );// Trimmed from the end the reader is further from: a window anchored near the bottom ends at// the document's last match.assert.match(- engine,+ USE_FIND_IN_PAGE,/if \(cappedRef\.current\) dropProbeFurthestFrom\(matches, anchoredAt\);/,);- assert.match(engine, /let anchoredAt: number \| null = null;/);- assert.match(engine, /anchoredAt = viewportOffset\(index\);/);- const bar = await readFile(- new URL(- "../src/features/find-in-page/components/find-bar.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(bar, /\$\{capped \? "\+" : ""\}/);- assert.equal(bar.includes("count >= MAX_MATCHES"), false);+ assert.match(USE_FIND_IN_PAGE, /let anchoredAt: number \| null = null;/);+ assert.match(USE_FIND_IN_PAGE, /anchoredAt = viewportOffset\(index\);/);+ assert.match(FIND_BAR, /\$\{capped \? "\+" : ""\}/);+ assert.equal(FIND_BAR.includes("count >= MAX_MATCHES"), false);});test("Escape is left to the IME while it is composing", async () => {// Escape dismisses a candidate. Consumed here, it closes the bar out from under a word still// being typed, and the candidate window never sees the key it was aimed at.- const bar = await readFile(- new URL(- "../src/features/find-in-page/components/find-bar.tsx",- import.meta.url,- ),- "utf8",- );- const escapeHandler = bar.slice(bar.indexOf("const onEscape ="));+ const escapeHandler = FIND_BAR.slice(FIND_BAR.indexOf("const onEscape ="));const guard = escapeHandler.indexOf("isImeComposing(event)");const consume = escapeHandler.indexOf("event.preventDefault()");assert.ok(guard > 0 && guard < consume);// Safe: the global listener stands aside for a composing event before looking for a binding.- const shortcut = await readFile(- new URL("../src/features/settings/hooks/use-shortcut.ts", import.meta.url),- "utf8",- );assert.match(- shortcut,+ USE_SHORTCUT,/if \(isImeComposing\(event\)\) return;\n\s*const hit = bindings\.find/,);});@@ -3317,12 +3127,8 @@ test("the selection fallback only clears what it put there", () => {test("the generated-image actions are out of the index too", async () => {// Persistently transparent text has to say so, since the index cannot tell it from a fade-in.- const tool = await readFile(- new URL(- "../src/components/assistant-ui/tool-ui-image-generation.tsx",- import.meta.url,- ),- "utf8",+ const tool = await readSrcAsync(+ "components/assistant-ui/tool-ui-image-generation.tsx",);const at = tool.indexOf("sm:group-hover/generated-image:opacity-100");assert.notEqual(at, -1);@@ -3335,69 +3141,37 @@ test("the generated-image actions are out of the index too", async () => {test("a hover-only badge is out of the index", async () => {// An affordance, not an entrance animation, so it is marked at the call site rather than by// turning the opacity check on.- const sheet = await readFile(- new URL(- "../src/components/assistant-ui/message-response-details-sheet.tsx",- import.meta.url,- ),- "utf8",+ const sheet = await readSrcAsync(+ "components/assistant-ui/message-response-details-sheet.tsx",);const badge = sheet.slice(sheet.indexOf("aui-response-model-badge") - 400);assert.match(badge.slice(0, badge.indexOf("aui-response-model-badge")),/\{\.\.\.\{ \[FIND_SKIP_ATTRIBUTE\]: "" \}\}/,);- const index = await readFile(- new URL(- "../src/features/find-in-page/lib/find-text-index.ts",- import.meta.url,- ),- "utf8",- );- assert.match(index, /opacityProperty: false/);+ assert.match(FIND_TEXT_INDEX, /opacityProperty: false/);});test("a container query resizing the scope invalidates the index", async () => {// Images is an `@container`, so pinning the sidebar crosses a breakpoint with no resize and// no mutation inside the scope.- const engine = await readFile(- new URL(- "../src/features/find-in-page/hooks/use-find-in-page.ts",- import.meta.url,- ),- "utf8",- );- assert.match(engine, /new ResizeObserver\(\(\) => \{/);- assert.match(engine, /sized\.observe\(scope\);/);- assert.match(engine, /sized\?\.disconnect\(\);/);+ assert.match(USE_FIND_IN_PAGE, /new ResizeObserver\(\(\) => \{/);+ assert.match(USE_FIND_IN_PAGE, /sized\.observe\(scope\);/);+ assert.match(USE_FIND_IN_PAGE, /sized\?\.disconnect\(\);/);// The first delivery is the size the scope already had, and would cost a flatten on every open.assert.match(- engine,+ USE_FIND_IN_PAGE,/if \(!measured\) \{\s*\n\s*measured = true;\s*\n\s*return;/,);});test("nothing of the engine is mounted while the bar is closed", async () => {- const controller = await readFile(- new URL(- "../src/features/find-in-page/components/find-in-page.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(controller, /if \(!enabled \|\| !open\) return null;/);+ assert.match(FIND_IN_PAGE, /if \(!enabled \|\| !open\) return null;/);assert.match(- controller,+ FIND_IN_PAGE,/lazy\(\(\) => import\("\.\/find-bar-loader\.tsx"\)\)/,);- assert.equal(controller.includes("useFindInPage("), false);+ assert.equal(FIND_IN_PAGE.includes("useFindInPage("), false);- const loadedBar = await readFile(- new URL(- "../src/features/find-in-page/components/find-bar.tsx",- import.meta.url,- ),- "utf8",- );- assert.equal((loadedBar.match(/useFindInPage\(/g) ?? []).length, 1);+ assert.equal((FIND_BAR.match(/useFindInPage\(/g) ?? []).length, 1);});diff --git a/studio/frontend/tests/forced-repair-retry.test.ts b/studio/frontend/tests/forced-repair-retry.test.tsindex 1310683a03a..65ba6bbaa3a 100644--- a/studio/frontend/tests/forced-repair-retry.test.ts+++ b/studio/frontend/tests/forced-repair-retry.test.ts@@ -14,13 +14,11 @@// the way gpu-torch-mismatch.test.ts and system-status-verdict.test.ts do beside it.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-const src = await readFile(- new URL("../src/hooks/use-tauri-backend.ts", import.meta.url),- "utf8",-);+import { readSrcAsync } from "./helpers/kit.ts";++const src = await readSrcAsync("hooks/use-tauri-backend.ts");function lift(pattern: RegExp, what: string): string {const found = pattern.exec(src);diff --git a/studio/frontend/tests/fork-count-batching.test.ts b/studio/frontend/tests/fork-count-batching.test.tsindex 26b1629d529..7694090a8e7 100644--- a/studio/frontend/tests/fork-count-batching.test.ts+++ b/studio/frontend/tests/fork-count-batching.test.ts@@ -7,11 +7,12 @@// raises that event once per chunk. One shared subscription, one request per thread.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test, { mock } from "node:test";import { loadWithStubs } from "./helpers/module-stubs.ts";+import { readSrc } from "./helpers/kit.ts";+const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";type Store = {@@ -166,10 +167,7 @@ test("two threads on screen cost one request each", async () => {});test("the badge no longer owns a listener or a per-message request", () => {- const thread = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );+ const thread = readSrc("components/assistant-ui/thread.tsx");assert.doesNotMatch(thread, /getForkCount\(/);assert.doesNotMatch(thread, /addEventListener\(CHAT_HISTORY_UPDATED_EVENT/);assert.match(thread, /subscribeForkCounts\(remoteId, onChange\)/);diff --git a/studio/frontend/tests/gallery-flags.test.ts b/studio/frontend/tests/gallery-flags.test.tsindex a3ba71eda0c..5965738c631 100644--- a/studio/frontend/tests/gallery-flags.test.ts+++ b/studio/frontend/tests/gallery-flags.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -21,6 +20,8 @@ import {sortGalleryItems,} from "../src/lib/gallery-flags.ts";+import { readSrc } from "./helpers/kit.ts";+const item = (id: string, created_at: number | string, pinned = false) => ({id,created_at,@@ -29,13 +30,7 @@ const item = (id: string, created_at: number | string, pinned = false) => ({const ids = (items: { id: string }[]) => items.map((i) => i.id);-const archivedMediaSource = readFileSync(- new URL(- "../src/features/settings/components/archived-media-dialog.tsx",- import.meta.url,- ),- "utf8",-);+const archivedMediaSource = readSrc("features/settings/components/archived-media-dialog.tsx");test("unpinned items sort newest first", () => {const items = [item("old", 1), item("new", 3), item("mid", 2)];diff --git a/studio/frontend/tests/gallery-item-menu-visibility.test.ts b/studio/frontend/tests/gallery-item-menu-visibility.test.tsindex 19819ae2227..86df8cacf75 100644--- a/studio/frontend/tests/gallery-item-menu-visibility.test.ts+++ b/studio/frontend/tests/gallery-item-menu-visibility.test.ts@@ -2,23 +2,15 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readSrc } from "./helpers/kit.ts";+test("gallery overlay actions follow interaction state instead of stale mouse focus", async () => {const [menu, imagesPage, videoPage] = await Promise.all([- readFile(- new URL("../src/components/gallery-item-menu.tsx", import.meta.url),- "utf8",- ),- readFile(- new URL("../src/features/images/images-page.tsx", import.meta.url),- "utf8",- ),- readFile(- new URL("../src/features/video/video-page.tsx", import.meta.url),- "utf8",- ),+ readSrc("components/gallery-item-menu.tsx"),+ readSrc("features/images/images-page.tsx"),+ readSrc("features/video/video-page.tsx"),]);const closedClasses =diff --git a/studio/frontend/tests/generation-length-cap-attribution.test.ts b/studio/frontend/tests/generation-length-cap-attribution.test.tsindex 38a21d05a10..c8d8c06bceb 100644--- a/studio/frontend/tests/generation-length-cap-attribution.test.ts+++ b/studio/frontend/tests/generation-length-cap-attribution.test.ts@@ -4,11 +4,12 @@import assert from "node:assert/strict";import test from "node:test";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";-import { maxTokensIsTheLimit } from "../src/features/chat/api/generation-length.ts";+import { readSrc } from "./helpers/kit.ts";++const CHAT_ADAPTER = readSrc("features/chat/api/chat-adapter.ts");+// Hoisted: biome's useTopLevelRegex flags a literal recompiled per call.const LOCAL_WINDOW_ARGUMENT =/isExternalRequest\s*\n\s*\? null\s*\n\s*: \(runtime\.loadedCustomContextLength \?\?\s*\n\s*runtime\.loadedContextLength \?\?\s*\n\s*\(params\.maxSeqLength \|\| null\)\)/;@@ -97,26 +98,14 @@ test("a local model with no GGUF window still reports one", () => {false,);- const adapter = readFileSync(- fileURLToPath(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- ),- "utf8",- );- assert.match(adapter, LOCAL_WINDOW_ARGUMENT);+ assert.match(CHAT_ADAPTER, LOCAL_WINDOW_ARGUMENT);});test("a pending Context Length edit does not decide what stopped the generation", () => {// Typing 8192 into the field while the model still serves at 4096 would make the// 4096 stop look user-imposed, and the advice would be to raise Max Tokens rather// than to reload at the larger context.- const adapter = readFileSync(- fileURLToPath(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- ),- "utf8",- );- assert.match(adapter, LOCAL_WINDOW_ARGUMENT);- assert.doesNotMatch(adapter, PENDING_FIELD);+ assert.match(CHAT_ADAPTER, LOCAL_WINDOW_ARGUMENT);+ assert.doesNotMatch(CHAT_ADAPTER, PENDING_FIELD);});diff --git a/studio/frontend/tests/generation-length-toast-advice.test.ts b/studio/frontend/tests/generation-length-toast-advice.test.tsindex 4aae523a638..4e1b3671a2e 100644--- a/studio/frontend/tests/generation-length-toast-advice.test.ts+++ b/studio/frontend/tests/generation-length-toast-advice.test.ts@@ -2,18 +2,13 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";++import { readSrc } from "./helpers/kit.ts";// Asserted against the source like the other chat-adapter tests: importing the// module would drag in the stores and the toast layer for one catch block.-const source = readFileSync(- fileURLToPath(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- ),- "utf8",-);+const source = readSrc("features/chat/api/chat-adapter.ts");// Hoisted: biome's useTopLevelRegex flags a literal recompiled per call.const TOAST_BRANCH =@@ -43,12 +38,7 @@ test("the toast repeats the advice the error chose, not the Max Tokens advice",test("the two remedies really are different text, so passing it through matters", () => {// Read rather than imported, as tests/padded-response.test.ts reads it: importing// chat-api pulls in the asset graph for two string literals.- const chatApi = readFileSync(- fileURLToPath(- new URL("../src/features/chat/api/chat-api.ts", import.meta.url),- ),- "utf8",- );+ const chatApi = readSrc("features/chat/api/chat-api.ts");assert.match(chatApi, THE_ERROR_CLASS);assert.match(chatApi, CAP_REMEDY);diff --git a/studio/frontend/tests/generation-recovery-own-run.test.ts b/studio/frontend/tests/generation-recovery-own-run.test.tsindex 878dd976e5f..e63fa9f039e 100644--- a/studio/frontend/tests/generation-recovery-own-run.test.ts+++ b/studio/frontend/tests/generation-recovery-own-run.test.ts@@ -16,10 +16,9 @@// mode: a run left claimed is a run this tab can never recover.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readText, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -29,8 +28,6 @@ const {releaseLiveGenerationRun,} = await import("../src/features/chat/utils/chat-generation-recovery.ts");-const read = (path: string) => readFileSync(new URL(path, import.meta.url), "utf8");-test("a claimed run is reported as this tab's, and a released one is not", () => {assert.equal(isLiveGenerationRun("run-a"), false);claimLiveGenerationRun("run-a");@@ -63,7 +60,7 @@ test("the recovery scheduler refuses a run this tab is streaming", () => {// Source-pinned: scheduleGenerationRecovery is not reachable from a test (it needs a live// aui view and the store), so the guard is asserted where it sits. It must come BEFORE the// scheduler registers itself as running, or the early return is unreachable.- const provider = read("../src/features/chat/runtime-provider.tsx");+ const provider = readText("../src/features/chat/runtime-provider.tsx");const guard = provider.indexOf("if (isLiveGenerationRun(runId)) return;");const register = provider.indexOf("runtime.registerThreadServerCancel(threadId, serverCancel)");@@ -79,7 +76,7 @@ test("the adapter claims the run BEFORE admission, not after the response", () =// claim does not stop one already running, because the scheduler only tests ownership at// startup. The run id is the client's own (`cancelId` is passed as `runId`), so there is no// reason to wait for the server to hand it back.- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");// Matched without the closing paren: the call carries an options object and wraps.const claim = adapter.indexOf("claimLiveGenerationRun(cancelId, resolvedThreadId!,");const admission = adapter.indexOf("generationRun = await createChatGenerationRunUntilAbort(");@@ -105,7 +102,7 @@ test("the adapter claims the run BEFORE admission, not after the response", () =});test("the adapter claims the run and releases it in a finally", () => {- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");assert.ok(adapter.includes("claimLiveGenerationRun(generationRunId, resolvedThreadId!)"),diff --git a/studio/frontend/tests/gpu-torch-mismatch.test.ts b/studio/frontend/tests/gpu-torch-mismatch.test.tsindex f826c9e44d5..34c748a1f96 100644--- a/studio/frontend/tests/gpu-torch-mismatch.test.ts+++ b/studio/frontend/tests/gpu-torch-mismatch.test.ts@@ -12,24 +12,17 @@// regex and evaluated, as system-status-verdict.test.ts does beside them.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrcAsync, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();const { videoNavHint } = await import("../src/config/hardware-verdict.ts");const { en } = await import("../src/i18n/locales/en.ts");-const tabSrc = await readFile(- new URL("../src/features/settings/tabs/resources-tab.tsx", import.meta.url),- "utf8",-);-const sidebarSrc = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",-);+const tabSrc = await readSrcAsync("features/settings/tabs/resources-tab.tsx");+const sidebarSrc = await readSrcAsync("components/app-sidebar.tsx");function lift(src: string,@@ -280,33 +273,21 @@ test("every string the banner reaches for exists", () => {// isExternalServer, stopped the external-server poll and swapped the shell to the repairing// screen, so a connected user lands on the repair-error screen instead of on their server.test("the repair row hides itself for an externally started backend", async () => {- const source = await readFile(- new URL(- "../src/features/settings/components/desktop-repair-control.tsx",- import.meta.url,- ),- "utf8",- );+ const source = await readSrcAsync("features/settings/components/desktop-repair-control.tsx");assert.match(source,/if\s*\(!repair\s*\|\|\s*repair\.isExternalServer\)\s*return null;/,"the control must bail out on an external server as well as outside Tauri",);- const context = await readFile(- new URL("../src/hooks/tauri-repair-context.ts", import.meta.url),- "utf8",- );+ const context = await readSrcAsync("hooks/tauri-repair-context.ts");assert.match(context,/isExternalServer:\s*boolean;/,"the controller has to carry the flag for the control to read it",);- const provider = await readFile(- new URL("../src/app/provider.tsx", import.meta.url),- "utf8",- );+ const provider = await readSrcAsync("app/provider.tsx");const memo = provider.slice(provider.indexOf("const repairController"));assert.match(memo.slice(0, 300),@@ -326,10 +307,7 @@ test("the repair row hides itself for an externally started backend", async () =// machine and no_gpu becomes torch_cpu_build. The polling effect stopped at the first// settled verdict, so the new hint was unreachable for the rest of the session.test("the sidebar keeps polling while the inventory can still change the verdict", async () => {- const source = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("components/app-sidebar.tsx");assert.match(source,diff --git a/studio/frontend/tests/hardware-verdict-recovery.test.ts b/studio/frontend/tests/hardware-verdict-recovery.test.tsindex 988750c3e84..73b832ac945 100644--- a/studio/frontend/tests/hardware-verdict-recovery.test.ts+++ b/studio/frontend/tests/hardware-verdict-recovery.test.ts@@ -14,7 +14,11 @@ import { readFile } from "node:fs/promises";import { register } from "node:module";import test from "node:test";-import { installLocalStorageFake, registerBundlerResolver } from "./helpers/kit.ts";+import {+ installLocalStorageFake,+ readSrcAsync,+ registerBundlerResolver,+} from "./helpers/kit.ts";register("./helpers/vite-env-loader.mjs", import.meta.url);registerBundlerResolver();@@ -105,10 +109,7 @@ test("a cached authoritative verdict is not re-read without force", async () =>});test("the recovery poll runs while the verdict is unknown, on every platform", async () => {- const src = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );+ const src = await readSrcAsync("components/app-sidebar.tsx");const call = src.indexOf("void fetchDeviceType({ force: true })");assert.ok(call > 0, "the recovery poll left app-sidebar.tsx");const start = src.lastIndexOf("useEffect(() => {", call);@@ -152,10 +153,7 @@ test("the recovery poll runs while the verdict is unknown, on every platform", a});test("the poll is mounted on every route that gates on the verdict", async () => {- const root = await readFile(- new URL("../src/app/routes/__root.tsx", import.meta.url),- "utf8",- );+ const root = await readSrcAsync("app/routes/__root.tsx");const hidden = /const HIDDEN_NAVBAR_ROUTES = \[([^\]]*)\]/.exec(root);assert.ok(hidden, "could not find HIDDEN_NAVBAR_ROUTES in __root.tsx");assert.ok(@@ -177,10 +175,7 @@ test("the poll is mounted on every route that gates on the verdict", async () =>`${page} re-reads the verdict itself instead of reading the store`,);}- const studio = await readFile(- new URL("../src/features/studio/studio-page.tsx", import.meta.url),- "utf8",- );+ const studio = await readSrcAsync("features/studio/studio-page.tsx");assert.match(studio,/capabilitiesUnknown/,diff --git a/studio/frontend/tests/helpers/kit.ts b/studio/frontend/tests/helpers/kit.tsindex f1174c9de90..cee4fba2376 100644--- a/studio/frontend/tests/helpers/kit.ts+++ b/studio/frontend/tests/helpers/kit.ts@@ -1,11 +1,30 @@// 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 { readFileSync } from "node:fs";+import { readFile } from "node:fs/promises";import { register } from "node:module";import type { ResidentAdoptionState } from "../../src/features/hub/lib/adopt-inference-status.ts";import type { ResidentStatusRefreshTargets } from "../../src/features/hub/lib/resident-status-refresh.ts";+/**+ * A module under `src` read as text, path relative to `src` so it survives a test+ * file moving. Shape assertions need the shipped file, not a copy of it.+ */+export function readSrc(relative: string): string {+ return readFileSync(new URL(`../../src/${relative}`, import.meta.url), "utf8");+}++/** A repository file read as text, relative to `studio/frontend/tests` like the `new URL` it replaces. Prefer `readSrc` under `src`. */+export function readText(relative: string): string {+ return readFileSync(new URL(`../${relative}`, import.meta.url), "utf8");+}++export function readSrcAsync(relative: string): Promise<string> {+ return readFile(new URL(`../../src/${relative}`, import.meta.url), "utf8");+}+/*** Teach the loader the two resolution rules vite and tsconfig's "bundler" mode give the* app. Call before dynamically importing any src module that resolves that way.diff --git a/studio/frontend/tests/hosted-image-tool-with-studio-tools.test.ts b/studio/frontend/tests/hosted-image-tool-with-studio-tools.test.tsindex 9b67a3bf536..336a7abdcc0 100644--- a/studio/frontend/tests/hosted-image-tool-with-studio-tools.test.ts+++ b/studio/frontend/tests/hosted-image-tool-with-studio-tools.test.ts@@ -2,19 +2,16 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import test from "node:test";+import { readSrc } from "./helpers/kit.ts";+// The request body is built deep inside the adapter's run closure, which needs// a live runtime, a provider store and an encryption key to reach. The property// that regressed is structural though: which names the Unsloth-tools branch puts// in enabled_tools. So this reads that branch out of the source, the same way// the backend's route tests read the gate out of routes/inference.py.-const SOURCE = readFileSync(- fileURLToPath(new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url)),- "utf8",-);+const SOURCE = readSrc("features/chat/api/chat-adapter.ts");// The branch taken when the provider runs Unsloth's tools. Bounded by the// hosted-only branch that follows it, so the two cannot be confused.diff --git a/studio/frontend/tests/hub-failure-panel-coverage.test.ts b/studio/frontend/tests/hub-failure-panel-coverage.test.tsindex 994f49b11aa..0f1b12e070d 100644--- a/studio/frontend/tests/hub-failure-panel-coverage.test.ts+++ b/studio/frontend/tests/hub-failure-panel-coverage.test.ts@@ -3,7 +3,8 @@import assert from "node:assert/strict";import test from "node:test";-import { readFile } from "node:fs/promises";++import { readText } from "./helpers/kit.ts";// The whole point of this change is that the panel names the cause. A kind the// renderer does not handle falls through to the generic wording, and because the@@ -15,18 +16,16 @@ import { readFile } from "node:fs/promises";// A superseded request is never rendered: it is not a failure the user caused.const NOT_RENDERED = new Set(["aborted"]);-function read(path: string): Promise<string> {- return readFile(new URL(path, import.meta.url), "utf8");-}-test("every renderable Hub failure kind has a branch in the panel", async () => {- const network = await read("../src/features/hub/lib/network.ts");+ const network = await readText("../src/features/hub/lib/network.ts");const decl = /export type HubFailureKind =([\s\S]*?);/.exec(network);assert.ok(decl, "could not find HubFailureKind in network.ts");const kinds = [...decl[1].matchAll(/"([a-z-]+)"/g)].map((m) => m[1]);assert.ok(kinds.length >= 5, `parsed too few kinds: ${kinds.join(", ")}`);- const states = await read("../src/features/hub/catalog/catalog-states.tsx");+ const states = await readText(+ "../src/features/hub/catalog/catalog-states.tsx",+ );const start = states.indexOf("function describeFailure");assert.notEqual(start, -1, "could not find describeFailure");const body = states.slice(start, states.indexOf("\nexport function", start));diff --git a/studio/frontend/tests/hub-network-availability.test.ts b/studio/frontend/tests/hub-network-availability.test.tsindex bfdeb00e862..6e766c63b6a 100644--- a/studio/frontend/tests/hub-network-availability.test.ts+++ b/studio/frontend/tests/hub-network-availability.test.ts@@ -3,7 +3,6 @@import assert from "node:assert/strict";import test from "node:test";-import { readFile } from "node:fs/promises";import {classifyFetchFailure,@@ -20,6 +19,8 @@ import {sanitizeHubErrorMessage,} from "../src/features/hub/lib/network.ts";+import { readSrcAsync } from "./helpers/kit.ts";+const HF = "https://huggingface.co";// Installing a window exercises the same event path the app uses, not the@@ -349,10 +350,7 @@ test("a generator that threw is not pulled again", async () => {assert.equal((await iter.next()).done, true, "it is finished once it throws");assert.equal(requests, 2, "reusing it issues no request, so done is a lie");- const src = await readFile(- new URL("../src/features/hub/hooks/use-hub-paginated-search.ts", import.meta.url),- "utf8",- );+ const src = await readSrcAsync("features/hub/hooks/use-hub-paginated-search.ts");// Set on the failure path, cleared only where a new generator is built.assert.match(src, /iterDeadRef\.current = true;/);assert.match(src, /iterRef\.current = iter;\s*\n\s*iterDeadRef\.current = false;/);diff --git a/studio/frontend/tests/hub-progress-token-boundary.test.ts b/studio/frontend/tests/hub-progress-token-boundary.test.tsindex 5f578c47bef..da2ec818bc7 100644--- a/studio/frontend/tests/hub-progress-token-boundary.test.ts+++ b/studio/frontend/tests/hub-progress-token-boundary.test.ts@@ -5,19 +5,17 @@// if the header is dropped, blanked, or eaten by authFetch's own merge.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { hubTokenHeader } from "../src/features/hub/lib/hub-token-header.ts";import { loadWithStubs } from "./helpers/module-stubs.ts";+import { readText } from "./helpers/kit.ts";+type AuthApi = {authFetch: (input: string, init?: RequestInit) => Promise<Response>;};-const read = (relativePath: string): string =>- readFileSync(new URL(relativePath, import.meta.url), "utf8");-async function emittedHeaders(init?: RequestInit): Promise<Headers> {const originalFetch = globalThis.fetch;let received = new Headers();@@ -85,7 +83,7 @@ test("hubTokenHeader never leaks the token anywhere but its own header", async (test("the progress callers accept and forward a request-scoped token", () => {// Whitespace-insensitive: the transport tests cannot prove these callers send one.- const api = read("../src/features/chat/api/chat-api.ts");+ const api = readText("../src/features/chat/api/chat-api.ts");for (const name of ["getGgufDownloadProgress","getDownloadProgress",@@ -106,7 +104,7 @@ test("the progress callers accept and forward a request-scoped token", () => {test("a local load is not gated behind Hub token preparation", () => {// prepareHfTokenForUse validates over the network and can block on a dialog.- const chatRuntime = read(+ const chatRuntime = readText("../src/features/chat/hooks/use-chat-model-runtime.ts",);const start = chatRuntime.indexOf("const mayReachHub");diff --git a/studio/frontend/tests/hub-recovery-paths.test.ts b/studio/frontend/tests/hub-recovery-paths.test.tsindex a46d13bc5f0..275946380a3 100644--- a/studio/frontend/tests/hub-recovery-paths.test.ts+++ b/studio/frontend/tests/hub-recovery-paths.test.ts@@ -3,16 +3,13 @@import assert from "node:assert/strict";import test from "node:test";-import { readFile } from "node:fs/promises";++import { readText } from "./helpers/kit.ts";// Making a lapsed backoff mean "probing" fixed the flapping, but "probing" only// clears when a *listing* succeeds. Anything else gated on it, or on the dead// iterator that a failed page leaves behind, has to keep a way back on its own.-function read(path: string): Promise<string> {- return readFile(new URL(path, import.meta.url), "utf8");-}-/** A callback body, so a dependency array cannot satisfy an assertion. */function body(source: string, start: string, end: string): string {const at = source.indexOf(start);@@ -23,7 +20,7 @@ function body(source: string, start: string, end: string): string {}test("clients with their own request keep their own reachability", async () => {- const page = await read("../src/features/hub/hub-page.tsx");+ const page = await readText("../src/features/hub/hub-page.tsx");// This value reaches useHubFeed and, through useModelsSelection, the selected// model's metadata lookup. Those are independent requests: on the discovery// phase they stayed blocked at "probing" until a listing succeeded, and the@@ -36,17 +33,17 @@ test("clients with their own request keep their own reachability", async () => {});test("the panel still reads the classified cause, not that boolean", async () => {- const page = await read("../src/features/hub/hub-page.tsx");+ const page = await readText("../src/features/hub/hub-page.tsx");// Reverting `online` must not quietly revert the diagnosis with it: the panel// is driven by searchFailure, which useDiscoverSearch reads off the phase.assert.match(page, /searchFailure,/);- const search = await read("../src/features/hub/hooks/use-discover-search.ts");+ const search = await readText("../src/features/hub/hooks/use-discover-search.ts");assert.match(search, /const \{ phase, failure \} = useHubAvailability\(\);/);assert.match(search, /const online = phase === "available";/);});test("a dead feed is restarted by Load more, not left inert", async () => {- const search = await read("../src/features/hub/hooks/use-discover-search.ts");+ const search = await readText("../src/features/hub/hooks/use-discover-search.ts");const fn = body(search, "const fetchMore = useCallback", "\n }, [");// hasMore is kept so the footer survives the failed page, so the button stays// on screen. Without this it called a fetchMore that returned false forever.@@ -59,7 +56,7 @@ test("a dead feed is restarted by Load more, not left inert", async () => {});test("the restart is not allowed to defeat the backoff", async () => {- const search = await read("../src/features/hub/hooks/use-discover-search.ts");+ const search = await readText("../src/features/hub/hooks/use-discover-search.ts");const fn = body(search, "const fetchMore = useCallback", "\n }, [");// Only the explicit Retry clears the window. Clearing it from a path the// scroll observer can reach would re-probe a dead origin on every scroll.@@ -69,7 +66,7 @@ test("the restart is not allowed to defeat the backoff", async () => {});test("rows on screen do not hide that the feed failed", async () => {- const lists = await read("../src/features/hub/catalog/models-catalog-lists.tsx");+ const lists = await readText("../src/features/hub/catalog/models-catalog-lists.tsx");// A cached feed substituted after a failed refresh renders rows with// hasMore false, which skipped the footer and the panel alike: once the toast// went there was nothing on screen saying so and nothing left to click.@@ -78,7 +75,7 @@ test("rows on screen do not hide that the feed failed", async () => {assert.ok(footer.includes("failed={Boolean(searchError || searchFailure)}"));assert.ok(footer.includes("onRetry={onRetry}"));- const states = await read("../src/features/hub/catalog/catalog-states.tsx");+ const states = await readText("../src/features/hub/catalog/catalog-states.tsx");// To the next declaration: the prop destructuring contains a "\n}" of its own.const fn = body(states,@@ -90,7 +87,7 @@ test("rows on screen do not hide that the feed failed", async () => {});test("a live backoff is not bypassed by typing", async () => {- const search = await read("../src/features/hub/hooks/use-discover-search.ts");+ const search = await readText("../src/features/hub/hooks/use-discover-search.ts");// Ungating `enabled` is what let the error reach the panel, but it also let a// changed query, sort or channel build a new iterator and fire immediately.// Each attempt failed and re-armed the 30s window, so it never elapsed.@@ -108,17 +105,17 @@ test("a live backoff is not bypassed by typing", async () => {test("gating the search again does not re-hide the error", async () => {// This is only safe because the disabled path stopped clearing it. Pin both// halves together: restoring the null would silently undo the whole fix.- const paginated = await read(+ const paginated = await readText("../src/features/hub/hooks/use-hub-paginated-search.ts",);const disabled = body(paginated, "if (!enabled) {", "\n // Same query");assert.ok(!/error: null/.test(disabled), "disabling must not erase the cause");- const search = await read("../src/features/hub/hooks/use-discover-search.ts");+ const search = await readText("../src/features/hub/hooks/use-discover-search.ts");assert.match(search, /const searchError = isDiscoverTab \? rawSearchError : null;/);});test("a footer retained over an outage can still act", async () => {- const lists = await read("../src/features/hub/catalog/models-catalog-lists.tsx");+ const lists = await readText("../src/features/hub/catalog/models-catalog-lists.tsx");const footer = body(lists, "<DiscoverFetchMoreFooter", "/>");// An avatar or card failure marks the same origin, so the listing keeps its// rows and no searchError, and useHubInfiniteScroll is gated on `online`:@@ -137,7 +134,7 @@ test("a footer retained over an outage can still act", async () => {});test("the retained footer names the cause, not just the staleness", async () => {- const lists = await read("../src/features/hub/catalog/models-catalog-lists.tsx");+ const lists = await readText("../src/features/hub/catalog/models-catalog-lists.tsx");const footer = body(lists, "<DiscoverFetchMoreFooter", "/>");// This footer outlives the toast, so it is where the diagnosis has to live.// Reducing it to "out of date" threw away the thing this change exists for.@@ -145,7 +142,7 @@ test("the retained footer names the cause, not just the staleness", async () =>footer.includes("failureText={searchFailure?.message ?? searchError ?? \"\"}"),"the classified cause has to reach the one control that persists",);- const states = await read("../src/features/hub/catalog/catalog-states.tsx");+ const states = await readText("../src/features/hub/catalog/catalog-states.tsx");const fn = body(states,"export function DiscoverFetchMoreFooter",@@ -158,7 +155,7 @@ test("the retained footer names the cause, not just the staleness", async () =>});test("the notice outlives the backoff window, not the other way round", async () => {- const lists = await read("../src/features/hub/catalog/models-catalog-lists.tsx");+ const lists = await readText("../src/features/hub/catalog/models-catalog-lists.tsx");// `online` is the 30s TTL. It flips back on a timer with nothing proven, so// the notice and its Retry disappeared while getHubPhase() still said// "probing" and searchFailure still held the cause. Keying on the cause ties@@ -171,7 +168,7 @@ test("the notice outlives the backoff window, not the other way round", async ());// And the cause is only cleared by markRemoteNetworkOnline, which only// fetchWithTimeout calls, and only on a resolved response.- const network = await read("../src/features/hub/lib/network.ts");+ const network = await readText("../src/features/hub/lib/network.ts");const online = body(network, "export function markRemoteNetworkOnline", "\nexport function markRemoteNetworkOffline");assert.ok(online.includes("lastFailureByOrigin.delete(origin)"), "success clears it");const fetchFn = body(network, "export async function fetchWithTimeout", "\n } catch");@@ -179,7 +176,7 @@ test("the notice outlives the backoff window, not the other way round", async ()});test("a row the mapper rejects is not treated as an outage", async () => {- const paginated = await read(+ const paginated = await readText("../src/features/hub/hooks/use-hub-paginated-search.ts",);// next() already handed the item over, so the generator is fine. Letting the@@ -198,7 +195,7 @@ test("a row the mapper rejects is not treated as an outage", async () => {});test("pausing dataset fetches leaves the rendered rows alone", async () => {- const datasets = await read(+ const datasets = await readText("../src/features/hub/hooks/use-hub-dataset-search.ts",);// This hook's `enabled` does double duty: it gates the request AND returns []@@ -211,7 +208,7 @@ test("pausing dataset fetches leaves the rendered rows alone", async () => {"the pause has to reach the request and stop there",);- const search = await read("../src/features/hub/hooks/use-discover-search.ts");+ const search = await readText("../src/features/hub/hooks/use-discover-search.ts");const call = body(search, "const datasetSearch = useHubDatasetSearch", "\n });");assert.ok(call.includes("enabled: isDiscoverTab && isDatasetMode"),diff --git a/studio/frontend/tests/hub-shared-memory-display.test.ts b/studio/frontend/tests/hub-shared-memory-display.test.tsindex 4db37361591..297e74257fd 100644--- a/studio/frontend/tests/hub-shared-memory-display.test.ts+++ b/studio/frontend/tests/hub-shared-memory-display.test.ts@@ -2,17 +2,12 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const hubPage = readFileSync(- new URL("../src/features/hub/hub-page.tsx", import.meta.url),- "utf8",-);-const modelsHeader = readFileSync(- new URL("../src/features/hub/catalog/models-header.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const hubPage = readSrc("features/hub/hub-page.tsx");+const modelsHeader = readSrc("features/hub/catalog/models-header.tsx");test("Model Hub separates dedicated VRAM from shared GPU memory", () => {assert.match(hubPage, /gpu\.dedicatedMemoryTotalGb/);diff --git a/studio/frontend/tests/hydration-clears-stale-local-record.test.ts b/studio/frontend/tests/hydration-clears-stale-local-record.test.tsindex 229eabcb6cc..7fb5f9bf571 100644--- a/studio/frontend/tests/hydration-clears-stale-local-record.test.ts+++ b/studio/frontend/tests/hydration-clears-stale-local-record.test.ts@@ -15,7 +15,11 @@ import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";-import { installLocalStorageFake, registerStoreStubResolver } from "./helpers/kit.ts";+import {+ installLocalStorageFake,+ readSrc,+ registerStoreStubResolver,+} from "./helpers/kit.ts";registerStoreStubResolver();const { storage } = installLocalStorageFake();@@ -128,13 +132,7 @@ test("hydration does not mark itself saved when the write failed", () => {// background loads -- which read resolveInitialConfig and never open this panel --// still saw the stale record or none at all. Feeding the result back in makes it a// pending change instead, which is what puts Save (and its error toast) in reach.- const src = readFileSync(- new URL(- "../src/features/model-picker/components/model-config-page.tsx",- import.meta.url,- ),- "utf8",- ).replace(/\s+/g, " ");+ const src = readSrc("features/model-picker/components/model-config-page.tsx").replace(/\s+/g, " ");assert.match(src,@@ -148,13 +146,7 @@ test("hydration propagates what its own write evicted", () => {// clears their mirrored fields; hydration writes through the same budget, so a model// dropped here would keep applying its server row to API loads while quick select// read defaults for it, with nothing in the UI able to forget it.- const src = readFileSync(- new URL(- "../src/features/model-picker/components/model-config-page.tsx",- import.meta.url,- ),- "utf8",- ).replace(/\s+/g, " ");+ const src = readSrc("features/model-picker/components/model-config-page.tsx").replace(/\s+/g, " ");// The write hands savePerModelConfig somewhere to report evictions.assert.match(diff --git a/studio/frontend/tests/image-generation-defaults.test.ts b/studio/frontend/tests/image-generation-defaults.test.tsindex 233ff15f351..7517542398a 100644--- a/studio/frontend/tests/image-generation-defaults.test.ts+++ b/studio/frontend/tests/image-generation-defaults.test.ts@@ -7,6 +7,8 @@ import test from "node:test";import { defaultsFor } from "../src/features/images/image-generation-defaults.ts";+import { readSrc } from "./helpers/kit.ts";+test("distinguishes Klein base checkpoints from distilled checkpoints", () => {for (const size of ["4B", "9B"]) {assert.deepEqual(defaultsFor(`unsloth/FLUX.2-klein-base-${size}`), {@@ -36,10 +38,7 @@ test("keeps the existing family defaults and fallback", () => {});test("routed image picks apply and transactionally roll back model defaults", () => {- const source = readFileSync(- new URL("../src/features/images/images-page.tsx", import.meta.url),- "utf8",- );+ const source = readSrc("features/images/images-page.tsx");const routeStart = source.indexOf("const pick = diffusionRoutePick(",source.indexOf("const handledRouteModel"),@@ -57,10 +56,7 @@ test("routed image picks apply and transactionally roll back model defaults", ()});test("routed video picks apply and transactionally roll back model defaults", () => {- const source = readFileSync(- new URL("../src/features/video/video-page.tsx", import.meta.url),- "utf8",- );+ const source = readSrc("features/video/video-page.tsx");const routeStart = source.indexOf("const pick = diffusionRoutePick(",source.indexOf("const handledRouteModel"),@@ -90,12 +86,8 @@ test("failed image and video picks release their recipe hydration claims", () =>assert.match(source, /revertPick[\s\S]*r\.releaseRecipeClaim\?\.\(\)/);}- const hook = readFileSync(- new URL(- "../src/features/generation-presets/use-media-generation-presets.ts",- import.meta.url,- ),- "utf8",+ const hook = readSrc(+ "features/generation-presets/use-media-generation-presets.ts",);assert.match(hook,diff --git a/studio/frontend/tests/image-restore-settings-size.test.ts b/studio/frontend/tests/image-restore-settings-size.test.tsindex 3b81cadb464..61f81c810f4 100644--- a/studio/frontend/tests/image-restore-settings-size.test.ts+++ b/studio/frontend/tests/image-restore-settings-size.test.ts@@ -6,7 +6,6 @@// ImageGenerationPresetParams forbids -- 422ing every debounced preset PUT for the rest of the session.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -16,6 +15,8 @@ import {snapDim,} from "../src/features/images/image-size.ts";+import { readSrc } from "./helpers/kit.ts";+const withinSchema = ({ width, height }: { width: number; height: number }) =>width >= MIN_DIM &&width <= MAX_DIM &&@@ -76,10 +77,7 @@ test("a degenerate record still produces a usable size", () => {});const restoreSettingsBody = () => {- const source = readFileSync(- new URL("../src/features/images/images-page.tsx", import.meta.url),- "utf8",- );+ const source = readSrc("features/images/images-page.tsx");const start = source.indexOf("const restoreSettings = useCallback(");assert.ok(start > 0, "restoreSettings not found");return source.slice(start, source.indexOf("}, [", start));diff --git a/studio/frontend/tests/incognito-tagging-invariants.test.ts b/studio/frontend/tests/incognito-tagging-invariants.test.tsindex 5cfd9bfa474..f4f7251ecc2 100644--- a/studio/frontend/tests/incognito-tagging-invariants.test.ts+++ b/studio/frontend/tests/incognito-tagging-invariants.test.ts@@ -11,13 +11,11 @@// loaded under stubs, so what is pinned here is the shape of the decision.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const provider = readFileSync(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const provider = readSrc("features/chat/runtime-provider.tsx");/** ensureThreadRecord's body, code only. */function ensureThreadRecordBody(): string {diff --git a/studio/frontend/tests/keyboard-shortcuts.test.ts b/studio/frontend/tests/keyboard-shortcuts.test.tsindex fffa6572d9f..2f7ea0bffb4 100644--- a/studio/frontend/tests/keyboard-shortcuts.test.ts+++ b/studio/frontend/tests/keyboard-shortcuts.test.ts@@ -30,6 +30,15 @@ import {} from "../src/features/settings/stores/keyboard-shortcuts-store.ts";import { SETTINGS_TABS } from "../src/features/settings/stores/settings-dialog-store.ts";+import { readSrc, readSrcAsync } from "./helpers/kit.ts";++const SRC__ROOT = readSrc("app/routes/__root.tsx");+const APP_SIDEBAR = readSrc("components/app-sidebar.tsx");+const THREAD = readSrc("components/assistant-ui/thread.tsx");+const CHAT_PAGE = readSrc("features/chat/chat-page.tsx");+const KEYBOARD_SHORTCUTS_TAB = readSrc("features/settings/tabs/keyboard-shortcuts-tab.tsx");+const EN = readSrc("i18n/locales/en.ts");+function keyEvent(code: string,mods: Partial<{@@ -298,13 +307,9 @@ test("the tab-search chord counts as browser-owned on both platforms", () => {// The walk is the one chord whose end is a key coming up rather than going// down, so it is the one that a window losing focus can strand.test("the recent walk ends on losing the window, not just on keyup", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );- const at = sidebar.indexOf("const end = () =>");+ const at = APP_SIDEBAR.indexOf("const end = () =>");assert.ok(at !== -1, "the traversal listener moved");- const body = sidebar.slice(at, sidebar.indexOf("}, []);", at));+ const body = APP_SIDEBAR.slice(at, APP_SIDEBAR.indexOf("}, []);", at));// Both signals reach the same end, and both are torn down again.assert.match(body, /window\.addEventListener\("keyup", onKeyUp\);/);assert.match(body, /window\.addEventListener\("blur", end\);/);@@ -337,42 +342,34 @@ test("the private-window chord is reserved and carries no default", () => {// verdict, so they are the two workspace chords that can put a gate where the// user's workspace was.test("the workspace chords land where the guard lets them", async () => {- const root = await readFile(- new URL("../src/app/routes/__root.tsx", import.meta.url),- "utf8",- );assert.match(- root,+ SRC__ROOT,/const chatOnlyMeasured = usePlatformStore\(\n\s*\(s\) => s\.isChatOnly\(\) && !s\.capabilitiesUnknown\(\),/,);assert.match(- root,+ SRC__ROOT,/const routeShortcutEnabled = !isAuthFlowRoute && !settingsDialogOpen;/,);assert.match(- root,+ SRC__ROOT,/useShortcut\("switchToTrain", goTo\("\/studio"\), \{\n\s*enabled: routeShortcutEnabled && !chatOnlyMeasured,/,);// Video has its own predicate rather than the chat-only one: /video checks// auth and nothing else, so the chord would land on the unsupported-hardware// gate. Read through the same helper the disabled row reads.assert.match(- root,+ SRC__ROOT,/const videoDisabled =\n\s*videoNavHint\(chatOnlyMeasured, chatOnlyReason\) !== undefined;/,);assert.match(- root,+ SRC__ROOT,/useShortcut\("switchToVideo", goTo\("\/video"\), \{\n\s*enabled: routeShortcutEnabled && !videoDisabled,/,);- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );assert.match(- sidebar,+ APP_SIDEBAR,/const videoDisabledHint = videoNavHint\(chatOnlyMeasured, chatOnlyReason\);/,);- assert.match(sidebar, /disabled: videoDisabled,/);+ assert.match(APP_SIDEBAR, /disabled: videoDisabled,/);// The rest are on the allowlist, so they stay reachable and ungated: gating// them would take away a page the guard is happy to serve.@@ -381,13 +378,13 @@ test("the workspace chords land where the guard lets them", async () => {["switchToHub", "/hub"],["switchToExport", "/export"],] as const) {- const at = root.indexOf(`useShortcut("${id}"`);+ const at = SRC__ROOT.indexOf(`useShortcut("${id}"`);assert.ok(at !== -1, `${id} lost its call site`);assert.ok(- !root.slice(at, root.indexOf(");", at)).includes("chatOnlyMeasured"),+ !SRC__ROOT.slice(at, SRC__ROOT.indexOf(");", at)).includes("chatOnlyMeasured"),`${id} gated on a verdict its route does not answer to`,);- assert.match(root, new RegExp(`goTo\\("${path.replace("/", "\\/")}"\\)`));+ assert.match(SRC__ROOT, new RegExp(`goTo\\("${path.replace("/", "\\/")}"\\)`));}});@@ -616,15 +613,8 @@ test("bare Escape is the recorder's own exit, so only a prompt-gated row takes i// The recorder swallows every keydown, so bare Escape has to stay its way// out, except on the rows whose own chord it is.- const tab = await readFile(- new URL(- "../src/features/settings/tabs/keyboard-shortcuts-tab.tsx",- import.meta.url,- ),- "utf8",- );assert.match(- tab,+ KEYBOARD_SHORTCUTS_TAB,/event\.code === "Escape" &&\n(?:\s*![a-zA-Z.]+ &&\n)+\s*!def\?\.allowBareKey\n\s*\) \{\n\s*setRecording\(null\);/,);@@ -903,10 +893,7 @@ test("an unbound or unclaimed chord has no owner", () => {// browser eats leaves the Shortcuts tab itself hard to reach, so the General// reset has to cover this key or the user is stuck with it.test("Reset all local preferences clears the rebound chords", async () => {- const source = await readFile(- new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("features/settings/tabs/general-tab.tsx");const keys = source.slice(source.indexOf("const PREFS_KEYS"),source.indexOf("];", source.indexOf("const PREFS_KEYS")),@@ -959,14 +946,10 @@ test("every locale overlay carries the shortcut strings", async () => {});test("a cleared alternate keeps its row, so it can be restored", async () => {- const source = await readFile(- new URL("../src/features/settings/tabs/keyboard-shortcuts-tab.tsx", import.meta.url),- "utf8",- );// Clearing a slot stores null, so a row that keys off the resolved value// alone would hide the slot's own restore control along with the chord.assert.match(- source,+ KEYBOARD_SHORTCUTS_TAB,/hasAlternate =\s*\n\s*defaultBindingFor\(def, "alternate", mac\) !== null/,);});@@ -1037,13 +1020,9 @@ test("a chord's surface does not come back open on the next visit", async () =>// registry, so nothing stops another chord built on Escape from reaching it.// Clear all unreads ships one on macOS.test("only bare Escape drops the selection", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );- const at = sidebar.indexOf('if (event.key !== "Escape"');+ const at = APP_SIDEBAR.indexOf('if (event.key !== "Escape"');assert.notEqual(at, -1, "the selection listener moved");- const block = sidebar.slice(at, sidebar.indexOf("clearSelection();", at));+ const block = APP_SIDEBAR.slice(at, APP_SIDEBAR.indexOf("clearSelection();", at));// Every modifier, so ⇧Esc goes to Clear all unreads alone.for (const modifier of ["metaKey", "ctrlKey", "altKey", "shiftKey"]) {assert.ok(@@ -1092,21 +1071,17 @@ test("the workspace chords do not leave the mobile drawer over the workspace", a// gone unless the message is hovered. The assistant bar never mounted the fork// button, so any thread ending in a reply had no listener at all.test("the fork chord is registered where it mounts, not from an action bar", async () => {- const thread = await readFile(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );// The registration is its own component, rendering nothing.- const start = thread.indexOf("const ForkChatShortcut: FC = () => {");+ const start = THREAD.indexOf("const ForkChatShortcut: FC = () => {");assert.notEqual(start, -1, "the fork registration moved");- const block = thread.slice(start, thread.indexOf("\n};", start));+ const block = THREAD.slice(start, THREAD.indexOf("\n};", start));assert.match(block, /useShortcut\(\n\s*"forkChat",/);assert.match(block, /return null;/);// The button keeps the click and takes no part in the chord.- const buttonAt = thread.indexOf("const ForkMessageButton: FC = () => {");- const button = thread.slice(buttonAt, thread.indexOf("\n};", buttonAt));+ const buttonAt = THREAD.indexOf("const ForkMessageButton: FC = () => {");+ const button = THREAD.slice(buttonAt, THREAD.indexOf("\n};", buttonAt));assert.ok(!button.includes("useShortcut"),"an autohidden bar cannot hold the registration",@@ -1116,30 +1091,30 @@ test("the fork chord is registered where it mounts, not from an action bar", asy// the button's, so the in-flight flag cannot be either one's own state: the// chord followed by a click would post two forks with two thread ids.assert.match(- thread,+ THREAD,/const useForkInFlight = create<\{\n\s*forking: boolean;/,);- assert.match(thread, /const pending = useForkInFlight\(\(s\) => s\.forking\);/);+ assert.match(THREAD, /const pending = useForkInFlight\(\(s\) => s\.forking\);/);assert.match(- thread,+ THREAD,/if \(useForkInFlight\.getState\(\)\.forking\) return;/,);assert.ok(- !thread.includes("const [pending, setPending] = useState(false);"),+ !THREAD.includes("const [pending, setPending] = useState(false);"),"the per-instance flag is what let two forks run",);// Mounted from both roles, since either can be the last message, and only// for the last one, which is the message a fork may be taken from.- const mounts = thread.match(+ const mounts = THREAD.match(/<MessagePrimitive\.If last=\{true\}>\n\s*<ForkChatShortcut \/>\n\s*<\/MessagePrimitive\.If>/g,);assert.equal(mounts?.length, 2);for (const role of ["const AssistantMessage", "const UserMessage: FC"]) {- const at = thread.indexOf(role);+ const at = THREAD.indexOf(role);assert.notEqual(at, -1, `${role} moved`);assert.ok(- thread.slice(at, thread.indexOf("\n};", at)).includes("<ForkChatShortcut />"),+ THREAD.slice(at, THREAD.indexOf("\n};", at)).includes("<ForkChatShortcut />"),`${role} does not mount the fork chord`,);}@@ -1149,66 +1124,58 @@ test("the fork chord is registered where it mounts, not from an action bar", asy// pinned while no tour is running. A chord routed through it would open the// picker and lose it on the next tick.test("the model picker chord opens without the tour's pin", async () => {- const chatPage = await readFile(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );// The pin, and the effect that keys on it.assert.match(- chatPage,+ CHAT_PAGE,/const openModelSelector = useCallback\(\(\) => \{\n\s*setModelSelectorLocked\(true\);/,);assert.match(- chatPage,+ CHAT_PAGE,/if \(tour\.open\) return;\n\s*if \(!modelSelectorLocked\) return;[\s\S]{0,200}?setModelSelectorOpen\(false\);/,);// So the chord takes its own door, and stands aside while a step is on it.assert.match(- chatPage,+ CHAT_PAGE,/const toggleModelSelector = useCallback\(\(\) => \{\n(?:\s*\/\/[^\n]*\n)*\s*if \(modelSelectorLocked\) return;\n\s*setModelSelectorOpen\(\(open\) => !open\);/,);- assert.match(chatPage, /useShortcut\(\n\s*"openModelPicker",[\s\S]*?toggleModelSelector\(\);/);+ assert.match(CHAT_PAGE, /useShortcut\(\n\s*"openModelPicker",[\s\S]*?toggleModelSelector\(\);/);// Three mentions left, all the tour's: the declaration, the step builder's// argument, and that memo's dependency. Nothing else may pin it open.- assert.equal((chatPage.match(/openModelSelector/g) ?? []).length, 3);+ assert.equal((CHAT_PAGE.match(/openModelSelector/g) ?? []).length, 3);});// The inline rename pill is rendered by the row, so it needs the row to be on// screen. A chord has no row under the cursor, and the open chat may be behind// a collapsed section, past a folder's limit, or on a route with no chat list.test("the rename chord does not land in a surface only a row can show", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );// The chord asks for the dialog; the context menu, which has a row under the// cursor by definition, keeps the pill.assert.match(- sidebar,+ APP_SIDEBAR,/useShortcut\("renameChat", \(\) => \{[\s\S]*?withActiveChat\(\(item\) => openRenameChat\(item, false\)\);/,);- assert.match(sidebar, /onSelect=\{\(\) => openRenameChat\(item\)\}/);+ assert.match(APP_SIDEBAR, /onSelect=\{\(\) => openRenameChat\(item\)\}/);assert.match(- sidebar,+ APP_SIDEBAR,/function openRenameChat\(item: SidebarItem, inline = true\)/,);// The pill is gated on it, so a dialog rename cannot also arm a row that is// off screen and surprise the user when it comes back.assert.match(- sidebar,+ APP_SIDEBAR,/const isRenamingThis =\n\s*renamingTarget\?\.kind === "chat" &&\n\s*renamingTarget\.inline &&/,);// And the dialog takes chats now, which is what its chat strings were always// written for.assert.match(- sidebar,+ APP_SIDEBAR,/\(renamingTarget\.kind !== "chat" \|\| !renamingTarget\.inline\)/,);- assert.ok(sidebar.includes('t("shell.dialog.renameChat.title")'));+ assert.ok(APP_SIDEBAR.includes('t("shell.dialog.renameChat.title")'));});// Bare Escape has more than one owner. The sidebar answers it while rows are@@ -1262,17 +1229,13 @@ test("one Escape does not both drop a selection and deny a tool call", async ()});test("the composer chords outlive the recording bar", async () => {- const thread = await readFile(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );// Dictation swaps ComposerRightControls out for the recording bar, so a// chord registered in there could start dictation and never stop it.- const controls = thread.indexOf("const ComposerRightControls:");+ const controls = THREAD.indexOf("const ComposerRightControls:");assert.ok(controls !== -1, "the controls component moved");for (const id of ["startDictation", "sendMessage"]) {- const at = thread.indexOf(`useShortcut(\n "${id}"`);- const inline = thread.indexOf(`useShortcut("${id}"`);+ const at = THREAD.indexOf(`useShortcut(\n "${id}"`);+ const inline = THREAD.indexOf(`useShortcut("${id}"`);const found = at === -1 ? inline : at;assert.ok(found !== -1, `${id} lost its call site`);assert.ok(found < controls, `${id} registers inside the recording swap`);@@ -1280,43 +1243,32 @@ test("the composer chords outlive the recording bar", async () => {// Send goes through the form, which runs the parking, queueing and refusing// that the runtime's own send knows nothing about, and through the recording// bar's own path while dictation is running.- assert.match(thread, /formRef\.current\?\.requestSubmit\(\);/);+ assert.match(THREAD, /formRef\.current\?\.requestSubmit\(\);/);assert.match(- thread,+ THREAD,/if \(isDictating\) \{\n\s*if \(!dictationBlocked\) sendAfterDictation\(\);/,);});test("a collapsed sidebar section is not published for the chords", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );// Navigation and Select all walk what is on screen, so a section the user// closed counts as gone, the same as a closed project folder.assert.match(- sidebar,+ APP_SIDEBAR,/chatListsOnScreen && pinnedOpen \? sortedPinnedChatItems/,);assert.match(- sidebar,+ APP_SIDEBAR,/chatListsOnScreen && chatOpen \? sortedRecentChatItems/,);- assert.match(sidebar, /organizeBy !== "project" \|\| !projectsOpen/);+ assert.match(APP_SIDEBAR, /organizeBy !== "project" \|\| !projectsOpen/);// And the published lists are the filtered ones.- assert.match(sidebar, /pinnedItems: visiblePinnedItems,/);- assert.match(sidebar, /recentItems: visibleRecentItems,/);+ assert.match(APP_SIDEBAR, /pinnedItems: visiblePinnedItems,/);+ assert.match(APP_SIDEBAR, /recentItems: visibleRecentItems,/);});test("the MCP chord does not live behind the MCP pill", async () => {- const button = await readFile(- new URL("../src/features/chat/mcp-composer-button.tsx", import.meta.url),- "utf8",- );- const page = await readFile(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );+ const button = await readSrcAsync("features/chat/mcp-composer-button.tsx");// MCP ships off for a chat and the pill only renders once it is on, so a// chord registered inside the pill would do nothing until it was found by// hand. The dialog and its chord mount for the chat instead.@@ -1330,28 +1282,21 @@ test("the MCP chord does not live behind the MCP pill", async () => {// Mounted through the route change, not gated on `active`: the flag lives in// a store, so a dialog left open has to be closed on the way out rather than// unmounted with it still set.- assert.match(page, /\n\s*<McpServersDialogMount \/>/);+ assert.match(CHAT_PAGE, /\n\s*<McpServersDialogMount \/>/);assert.match(button, /if \(!chatActive && open\) setOpen\(false\);/);assert.match(button, /open=\{chatActive && open\}/);});test("the copy chords keep their gesture across the read", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );- const clipboard = await readFile(- new URL("../src/lib/copy-to-clipboard.ts", import.meta.url),- "utf8",- );+ const clipboard = await readSrcAsync("lib/copy-to-clipboard.ts");// Both copies read storage first, and a strict engine drops the gesture// across that await, leaving writeText and its execCommand fallback with// nothing to run inside. The write starts with a promised payload instead.assert.match(clipboard, /"text\/plain": payload\.then\(/);for (const fn of ["copyChatItemAsMarkdown", "copyChatSessionId"]) {- const at = sidebar.indexOf(`async function ${fn}(`);+ const at = APP_SIDEBAR.indexOf(`async function ${fn}(`);assert.ok(at !== -1, `${fn} moved`);- const body = sidebar.slice(at, sidebar.indexOf("\n }", at));+ const body = APP_SIDEBAR.slice(at, APP_SIDEBAR.indexOf("\n }", at));assert.ok(body.includes("copyToClipboardFrom(async () =>"),`${fn} awaits its read before starting the write`,@@ -1360,82 +1305,58 @@ test("the copy chords keep their gesture across the read", async () => {});test("the project picker chord is described by what it does", async () => {- const page = await readFile(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );// The header switcher navigates to the chosen project's landing; moving a// chat between projects is a different flow, on the chat row's own menu.- assert.match(page, /onSelectProject=\{openProjectLanding\}/);- const strings = await readFile(- new URL("../src/i18n/locales/en.ts", import.meta.url),- "utf8",- );- const at = strings.indexOf("openProjectPicker: {");- const entry = strings.slice(at, strings.indexOf("},", at));+ assert.match(CHAT_PAGE, /onSelectProject=\{openProjectLanding\}/);+ const at = EN.indexOf("openProjectPicker: {");+ const entry = EN.slice(at, EN.indexOf("},", at));assert.ok(!/move/i.test(entry), "no move-to-project promise");assert.ok(entry.includes("project"));});test("the new-chat chords stay out of the auth flow", async () => {- const root = await readFile(- new URL("../src/app/routes/__root.tsx", import.meta.url),- "utf8",- );// /login has no shell, and requireAuth bounces /chat straight back, so these// are gated like the workspace chords beside them.for (const id of ["newChat", "newTemporaryChat", "newStandaloneChat"]) {// The id, not the whole call: two of the three wrap onto their own line.- const at = root.indexOf(`"${id}"`);+ const at = SRC__ROOT.indexOf(`"${id}"`);assert.ok(at !== -1, `${id} is registered`);- const call = root.slice(at, root.indexOf("\n );", at) + 5);+ const call = SRC__ROOT.slice(at, SRC__ROOT.indexOf("\n );", at) + 5);assert.match(call, /enabled: routeShortcutEnabled/, `${id} is gated`);}});test("switching back to Chat lands on the view the user left", async () => {- const root = await readFile(- new URL("../src/app/routes/__root.tsx", import.meta.url),- "utf8",- );// ChatPage renders the frozen search while off-route, and a bare /chat is a// fresh chat, so the chord has to hand that search back to the router.- const at = root.indexOf('"switchToChat"');+ const at = SRC__ROOT.indexOf('"switchToChat"');assert.ok(at !== -1, "switchToChat is registered");- const call = root.slice(at, root.indexOf("\n );", at) + 5);+ const call = SRC__ROOT.slice(at, SRC__ROOT.indexOf("\n );", at) + 5);assert.match(call, /navigate\(\{ to: "\/chat", search: chatSearch \}\)/);assert.match(call, /enabled: routeShortcutEnabled/);// The other workspaces keep the bare helper; only chat carries a search.- assert.match(root, /useShortcut\("switchToImages", goTo\("\/images"\)/);+ assert.match(SRC__ROOT, /useShortcut\("switchToImages", goTo\("\/images"\)/);// location.search is the raw URL's, not the matched route's, so a seeded// freeze would hand /images?project=x to the chord as a chat never opened.- assert.match(root, /useState<ChatSearch>\(\{\}\)/);+ assert.match(SRC__ROOT, /useState<ChatSearch>\(\{\}\)/);});test("opening a chat by chord drops the selection, as clicking a row does", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );// Archive, pin and mark-unread prefer the selection when there is one, so a// stale one sends them to rows that are no longer on screen.- const at = sidebar.indexOf("function openChatItem(");- const body = sidebar.slice(at, sidebar.indexOf("\n }", at));+ const at = APP_SIDEBAR.indexOf("function openChatItem(");+ const body = APP_SIDEBAR.slice(at, APP_SIDEBAR.indexOf("\n }", at));assert.ok(body.includes("clearSelection()"), "the shared opener clears it");// One path only: the row reaches it through the same function.assert.ok(- !sidebar.includes("clearSelection();\n openChatItem(item);"),+ !APP_SIDEBAR.includes("clearSelection();\n openChatItem(item);"),"the row no longer clears it separately",);});test("effort chords only run for a model whose effort is read", async () => {- const page = await readFile(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );- const at = page.indexOf("const shiftReasoningEffort");- const body = page.slice(at, page.indexOf("useShortcut(\"cycleReasoningEffort\"", at));+ const at = CHAT_PAGE.indexOf("const shiftReasoningEffort");+ const body = CHAT_PAGE.slice(at, CHAT_PAGE.indexOf("useShortcut(\"cycleReasoningEffort\"", at));// enable_thinking models still list levels, but the request drops the effort.assert.match(body, /state\.reasoningStyle === "reasoning_effort"/);assert.match(body, /state\.reasoningStyle === "enable_thinking_effort"/);@@ -1443,33 +1364,25 @@ test("effort chords only run for a model whose effort is read", async () => {});test("New chat inherits the project on screen, inferred or not", async () => {- const root = await readFile(- new URL("../src/app/routes/__root.tsx", import.meta.url),- "utf8",- );- const page = await readFile(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );// On Chat the runtime's project is the visible one, inferred ones included:// the page resolves it from the thread or the compare pair when the URL// carries no ?project=, so a chat in a project stays in it.- assert.match(root, /isChatRoute \? chatRuntime\.activeProjectId : null/);- assert.match(page, /const projectId = thread\?\.projectId \?\? null;/);- assert.match(page, /const projectId = threads\[0\]\?\.projectId \?\? null;/);- assert.match(page, /setCurrentProjectId\(projectId\);\n\s*useChatRuntimeStore\.getState\(\)\.setActiveProjectId\(projectId\);/);+ assert.match(SRC__ROOT, /isChatRoute \? chatRuntime\.activeProjectId : null/);+ assert.match(CHAT_PAGE, /const projectId = thread\?\.projectId \?\? null;/);+ assert.match(CHAT_PAGE, /const projectId = threads\[0\]\?\.projectId \?\? null;/);+ assert.match(CHAT_PAGE, /setCurrentProjectId\(projectId\);\n\s*useChatRuntimeStore\.getState\(\)\.setActiveProjectId\(projectId\);/);// The page's own New chat button starts from the same value, so the chord// and the button cannot disagree about which project a new chat is in.- assert.match(page, /runtime\.setActiveProjectId\(currentProjectId\);/);+ assert.match(CHAT_PAGE, /runtime\.setActiveProjectId\(currentProjectId\);/);// Off Chat the page is hidden rather than unmounted, so the runtime still// names a project the user is not looking at. That one stays excluded.- assert.match(root, /isChatRoute \? chatRuntime\.activeProjectId : null/);+ assert.match(SRC__ROOT, /isChatRoute \? chatRuntime\.activeProjectId : null/);// Leaving the project is its own action, so this one must not also do it.assert.match(- root,+ SRC__ROOT,/useShortcut\("newStandaloneChat", \(\) => startNewChat\(\{ standalone: true \}\)/,);- assert.match(root, /const projectId = options\?\.standalone \? null : openProjectId;/);+ assert.match(SRC__ROOT, /const projectId = options\?\.standalone \? null : openProjectId;/);});test("every settings tab survives a reload", () => {@@ -1509,21 +1422,17 @@ test("a Super chord off macOS records nothing rather than a different chord", ()// user sees outside the shortcuts tab. Hard-coded, they keep advertising the// shipped chord after a rebind, and a dead one after a clear.test("the sidebar hints render the bound chord, not the shipped default", async () => {- const source = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );for (const literal of ['"⌘K"', '"Ctrl+K"', "<DropdownMenuShortcut>⌘,"]) {assert.ok(- !source.includes(literal),+ !APP_SIDEBAR.includes(literal),`app-sidebar still hard-codes ${literal}`,);}- assert.ok(source.includes('useShortcutLabel("searchChats")'));- assert.ok(source.includes('useShortcutLabel("openSettings")'));+ assert.ok(APP_SIDEBAR.includes('useShortcutLabel("searchChats")'));+ assert.ok(APP_SIDEBAR.includes('useShortcutLabel("openSettings")'));// Unassigned actions must drop the hint rather than render an empty key cap.- assert.ok(source.includes("{searchShortcutLabel && ("));- assert.ok(source.includes("{settingsShortcutLabel && ("));+ assert.ok(APP_SIDEBAR.includes("{searchShortcutLabel && ("));+ assert.ok(APP_SIDEBAR.includes("{settingsShortcutLabel && ("));});test("a hint label follows the override and disappears when cleared", () => {@@ -1546,13 +1455,9 @@ test("a hint label follows the override and disappears when cleared", () => {// A row with no i18n keys renders a raw key path, and one missing from the// search index cannot be found from the settings search box.test("every action is translated and indexed for settings search", async () => {- const en = await readFile(- new URL("../src/i18n/locales/en.ts", import.meta.url),- "utf8",- );- const at = en.indexOf(" keyboardShortcuts: {");+ const at = EN.indexOf(" keyboardShortcuts: {");assert.notEqual(at, -1);- const subtree = en.slice(at, en.indexOf("\n },", at));+ const subtree = EN.slice(at, EN.indexOf("\n },", at));for (const def of SHORTCUT_DEFS) {assert.ok(subtree.includes(`${def.id}: {`),@@ -1568,10 +1473,7 @@ test("every action is translated and indexed for settings search", async () => {);}- const index = await readFile(- new URL("../src/features/settings/settings-search.ts", import.meta.url),- "utf8",- );+ const index = await readSrcAsync("features/settings/settings-search.ts");for (const def of SHORTCUT_DEFS) {assert.ok(index.includes(`"${def.labelKey}"`),@@ -1657,14 +1559,10 @@ test("auto-repeat only reaches the actions that walk a list", async () => {// The chords read the published lists, so those have to end where the screen// does: whole-sidebar gates included, not just each section's disclosure.test("the published chat lists stop where the sidebar stops", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );// The same two conditions the three chat groups render behind, plus the// icon rail, which hides them in CSS rather than dropping them.assert.match(- sidebar,+ APP_SIDEBAR,/const chatListsOnScreen =\n\s*!isStudioRoute &&\n\s*!showTrainingRecents &&\n\s*\(isMobile \|\| sidebarState !== "collapsed"\);/,);for (const group of [@@ -1672,18 +1570,18 @@ test("the published chat lists stop where the sidebar stops", async () => {/\(chatListsOnScreen && pinnedOpen \? sortedPinnedChatItems : \[\]\)/,/\(chatListsOnScreen && chatOpen \? sortedRecentChatItems : \[\]\)/,]) {- assert.match(sidebar, group);+ assert.match(APP_SIDEBAR, group);}// Select All reads the same three arrays, so it cannot reach further than// the walk does.- const selectAll = sidebar.indexOf("const selectAllChats = useCallback(");+ const selectAll = APP_SIDEBAR.indexOf("const selectAllChats = useCallback(");assert.ok(selectAll !== -1, "selectAllChats moved");assert.match(- sidebar.slice(selectAll, sidebar.indexOf("\n }, [", selectAll)),+ APP_SIDEBAR.slice(selectAll, APP_SIDEBAR.indexOf("\n }, [", selectAll)),/\.\.\.visiblePinnedItems,\n\s*\.\.\.renderedProjectChatItems,\n\s*\.\.\.visibleRecentItems,/,);// Gating the arrays is enough because nothing renders from them.- const rendered = sidebar.slice(sidebar.indexOf("return (", selectAll));+ const rendered = APP_SIDEBAR.slice(APP_SIDEBAR.indexOf("return (", selectAll));for (const name of ["visiblePinnedItems","visibleRecentItems",@@ -1697,71 +1595,67 @@ test("the published chat lists stop where the sidebar stops", async () => {// no presence outside the rows, so one carried off screen is invisible and// still live.test("a selection does not outlive the rows it was made on", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );// The whole sidebar going takes the whole selection with it.assert.match(- sidebar,+ APP_SIDEBAR,/if \(!chatRowsOnScreen\) \{\n\s*clearSelection\(\);\n\s*return;\n\s*\}/,);// Which is the stricter of the two: the lists can exist while their rows do// not, because a closed mobile sheet unmounts them the way the rail does.assert.match(- sidebar,+ APP_SIDEBAR,/const chatRowsOnScreen = chatListsOnScreen && \(!isMobile \|\| openMobile\);/,);// Select All is the one that builds a selection out of nothing, so it takes// the same gate rather than waiting for the cleanup to undo it.assert.match(- sidebar,+ APP_SIDEBAR,/const selectAllChats = useCallback\(\(\) => \{\n\s*if \(!chatRowsOnScreen\) return;/,);// Navigation is deliberately left on the looser one.assert.match(- sidebar,+ APP_SIDEBAR,/\(chatListsOnScreen && chatOpen \? sortedRecentChatItems : \[\]\)/,);// A single section closing takes only its own rows: the rest are still on// screen, so the selection is held to what is rendered rather than dropped.assert.match(- sidebar,+ APP_SIDEBAR,/for \(const id of prev\) \{\n\s*if \(renderedChatIds\.has\(id\)\) kept\.add\(id\);/,);assert.match(- sidebar,+ APP_SIDEBAR,/return kept\.size === prev\.size \? prev : kept;/,);assert.match(- sidebar,+ APP_SIDEBAR,/\}, \[chatRowsOnScreen, clearSelection, renderedChatIds, renderedProjectIds\]\);/,);// Folder rows are selectable too, and selectionActive counts them, so one// left behind by a closed section keeps the tool card's Escape standing// aside for a selection with nothing on screen to show for it.assert.match(- sidebar,+ APP_SIDEBAR,/for \(const id of prev\) \{\n\s*if \(renderedProjectIds\.has\(id\)\) kept\.add\(id\);/,);assert.match(- sidebar,+ APP_SIDEBAR,/if \(projectAnchor && !renderedProjectIds\.has\(projectAnchor\)\) \{\n\s*projectAnchorRef\.current = null;/,);// The three ways a folder row leaves without the sidebar going with it.assert.match(- sidebar,+ APP_SIDEBAR,/const renderedProjectIds = useMemo\(\(\) => \{\n\s*if \(!chatListsOnScreen \|\| organizeBy !== "project" \|\| !projectsOpen\) \{\n\s*return new Set<string>\(\);\n\s*\}\n\s*return new Set\(visibleProjectRecords\.map\(\(project\) => project\.id\)\);/,);// Both counts feed the flag, which is why both have to be pruned.assert.match(- sidebar,+ APP_SIDEBAR,/const selectionActive =\n?\s*selectionCount > 0 \|\| projectSelectionCount > 0;/,);// Built from the three arrays that already carry every disclosure state, so// a collapse or a "show less" needs nothing restated here.assert.match(- sidebar,+ APP_SIDEBAR,/const renderedChatIds = useMemo\(\(\) => \{[\s\S]*?visiblePinnedItems[\s\S]*?renderedProjectChatItems[\s\S]*?visibleRecentItems/,);// Which is what makes the four bulk branches safe to leave as they are.@@ -1771,10 +1665,10 @@ test("a selection does not outlive the rows it was made on", async () => {"togglePinChat","deleteSelectedChats",]) {- const at = sidebar.indexOf(`useShortcut("${id}"`);+ const at = APP_SIDEBAR.indexOf(`useShortcut("${id}"`);assert.ok(at !== -1, `${id} lost its call site`);assert.match(- sidebar.slice(at, sidebar.indexOf("\n });", at)),+ APP_SIDEBAR.slice(at, APP_SIDEBAR.indexOf("\n });", at)),/selectionCount > 0/,`${id} no longer prefers the selection`,);@@ -1782,7 +1676,7 @@ test("a selection does not outlive the rows it was made on", async () => {// The anchor goes with its row, so a later shift-click cannot reach back to// one that is no longer there.assert.match(- sidebar,+ APP_SIDEBAR,/if \(anchor && !renderedChatIds\.has\(anchor\.id\)\) \{\n\s*selectionAnchorRef\.current = null;/,);});@@ -1791,15 +1685,11 @@ test("a selection does not outlive the rows it was made on", async () => {// selectionCount as 0. Without a latch it archives the open chat, which was// never selected, and says nothing about it.test("a selection chord does not fall through to the open chat", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );- assert.match(sidebar, /const SELECTION_ACTION_GRACE_MS = \d+;/);+ assert.match(APP_SIDEBAR, /const SELECTION_ACTION_GRACE_MS = \d+;/);for (const id of ["archiveChat", "markChatUnread", "togglePinChat"]) {- const body = sidebar.slice(- sidebar.indexOf(`useShortcut("${id}"`),- sidebar.indexOf("\n });", sidebar.indexOf(`useShortcut("${id}"`)),+ const body = APP_SIDEBAR.slice(+ APP_SIDEBAR.indexOf(`useShortcut("${id}"`),+ APP_SIDEBAR.indexOf("\n });", APP_SIDEBAR.indexOf(`useShortcut("${id}"`)),);// Both halves name the action. A shared latch would hold back Archive// after Pin took the selection, and that is a different command the user@@ -1818,9 +1708,9 @@ test("a selection chord does not fall through to the open chat", async () => {);}// deleteSelectedChats needs none of this: it has no open-chat branch.- const del = sidebar.slice(- sidebar.indexOf('useShortcut("deleteSelectedChats"'),- sidebar.indexOf("\n });", sidebar.indexOf('useShortcut("deleteSelectedChats"')),+ const del = APP_SIDEBAR.slice(+ APP_SIDEBAR.indexOf('useShortcut("deleteSelectedChats"'),+ APP_SIDEBAR.indexOf("\n });", APP_SIDEBAR.indexOf('useShortcut("deleteSelectedChats"')),);assert.doesNotMatch(del, /withActiveChat\(/);});@@ -1828,13 +1718,9 @@ test("a selection chord does not fall through to the open chat", async () => {// The only action with no menu item anywhere and no undo, so a silent wipe// leaves the user nothing to tell it apart from a dead key.test("clearing every unread says what it cleared", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );- const body = sidebar.slice(- sidebar.indexOf('useShortcut("clearAllUnreads"'),- sidebar.indexOf("\n });", sidebar.indexOf('useShortcut("clearAllUnreads"')),+ const body = APP_SIDEBAR.slice(+ APP_SIDEBAR.indexOf('useShortcut("clearAllUnreads"'),+ APP_SIDEBAR.indexOf("\n });", APP_SIDEBAR.indexOf('useShortcut("clearAllUnreads"')),);// Counted before the wipe, or the toast reports zero every time. Rows, not// threads: a Compare row is backed by two and would be cleared as two chats.@@ -1847,10 +1733,7 @@ test("clearing every unread says what it cleared", async () => {// order picks the winner. Compare panes make that easy to get wrong: the// backend reuses "call_0" per response, so the store key cannot be it.test("a parked tool request is keyed by its own approval, not call_0", async () => {- const adapter = await readFile(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );+ const adapter = await readSrcAsync("features/chat/api/chat-adapter.ts");// Scope first, so two panes differ even before the approval token does.assert.match(adapter,@@ -1892,10 +1775,6 @@ test("a parked tool request is keyed by its own approval, not call_0", async ()// effect again, without end. React error #185, which took down the whole chat// route rather than just the sidebar.test("the rows the selection guard reads keep their identity", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );for (const name of ["visibleProjectRecords","visiblePinnedItems",@@ -1903,10 +1782,10 @@ test("the rows the selection guard reads keep their identity", async () => {"renderedProjectChatItems","renderedChatIds",]) {- const at = sidebar.indexOf(`const ${name} = `);+ const at = APP_SIDEBAR.indexOf(`const ${name} = `);assert.notEqual(at, -1, `${name} is gone`);assert.match(- sidebar.slice(at, at + name.length + 40),+ APP_SIDEBAR.slice(at, at + name.length + 40),/= useMemo\(/,`${name} is rebuilt every render and feeds a selection effect`,);@@ -1918,10 +1797,7 @@ test("the rows the selection guard reads keep their identity", async () => {// identity on every render, which is what made the selection guard's effect// re-run without end.test("the sidebar item lists are built once per change, not per render", async () => {- const hook = await readFile(- new URL("../src/features/chat/hooks/use-chat-sidebar-items.ts", import.meta.url),- "utf8",- );+ const hook = await readSrcAsync("features/chat/hooks/use-chat-sidebar-items.ts");for (const name of ["items", "archivedItems"]) {const at = hook.indexOf(`const ${name} = `);assert.notEqual(at, -1, `${name} is gone`);@@ -1937,14 +1813,10 @@ test("the sidebar item lists are built once per change, not per render", async (// chat-only chords used to read that as "no selection" and act on the open// chat, so Archive archived a chat the user had not pointed at.test("the chat-only chords stand aside for a project selection", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );for (const id of ["archiveChat", "markChatUnread", "togglePinChat"]) {- const at = sidebar.indexOf(`useShortcut("${id}", () => {`);+ const at = APP_SIDEBAR.indexOf(`useShortcut("${id}", () => {`);assert.notEqual(at, -1, `${id} is gone`);- const body = sidebar.slice(at, sidebar.indexOf("\n });", at));+ const body = APP_SIDEBAR.slice(at, APP_SIDEBAR.indexOf("\n });", at));const stand = body.indexOf("projectsOnlySelected()");assert.notEqual(stand, -1, `${id} acts on the open chat under a project selection`);assert.ok(@@ -1954,7 +1826,7 @@ test("the chat-only chords stand aside for a project selection", async () => {}// Only when no chat is selected: a mixed selection still has chats to act on.assert.match(- sidebar,+ APP_SIDEBAR,/const projectsOnlySelected = \(\) =>\n\s*selectionCount === 0 && projectSelectionCount > 0;/,);});@@ -1991,12 +1863,5 @@ test("the logout row is not offered on the desktop build", async () => {SHORTCUT_DEFS.filter((def) => def.webOnly).map((def) => def.id),["logOut"],);- const tab = await readFile(- new URL(- "../src/features/settings/tabs/keyboard-shortcuts-tab.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(tab, /!\(isTauri && def\.webOnly\)/);+ assert.match(KEYBOARD_SHORTCUTS_TAB, /!\(isTauri && def\.webOnly\)/);});diff --git a/studio/frontend/tests/lan-access-state.test.ts b/studio/frontend/tests/lan-access-state.test.tsindex 3037126b83c..95ced09d1fa 100644--- a/studio/frontend/tests/lan-access-state.test.ts+++ b/studio/frontend/tests/lan-access-state.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";// lan-access-section.tsx pulls in hugeicons, so runtime tests stay on pure helpers.@@ -19,16 +18,12 @@ import {validLanAccessPort,} from "../src/features/settings/api/lan-access-state.ts";+import { readSrc } from "./helpers/kit.ts";+const LAN = "http://192.168.1.24:8888";const SECOND = "http://10.0.0.7:8888";const PUBLIC = "http://64.227.100.5:8888";-const SECTION_SOURCE = readFileSync(- new URL(- "../src/features/settings/components/lan-access-section.tsx",- import.meta.url,- ),- "utf8",-);+const SECTION_SOURCE = readSrc("features/settings/components/lan-access-section.tsx");function apiStatus(over: Partial<ApiLanAccessStatus> = {}): ApiLanAccessStatus {return {diff --git a/studio/frontend/tests/linked-folders-lease-gate.test.ts b/studio/frontend/tests/linked-folders-lease-gate.test.tsindex a635a04455c..329f9f997f7 100644--- a/studio/frontend/tests/linked-folders-lease-gate.test.ts+++ b/studio/frontend/tests/linked-folders-lease-gate.test.ts@@ -8,42 +8,19 @@// No React renderer here, so this asserts on source, like ~50 sibling tests.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-const HOOK = readFileSync(- fileURLToPath(- new URL("../src/features/rag/components/use-linked-folders.ts", import.meta.url),- ),- "utf8",-);+import { readSrc, readText } from "./helpers/kit.ts";-const MANAGER = readFileSync(- fileURLToPath(- new URL("../src/features/rag/components/linked-folders-manager.tsx", import.meta.url),- ),- "utf8",-);+const HOOK = readSrc("features/rag/components/use-linked-folders.ts");-const COMMANDS = readFileSync(- fileURLToPath(- new URL("../../src-tauri/src/commands.rs", import.meta.url),- ),- "utf8",-);+const MANAGER = readSrc("features/rag/components/linked-folders-manager.tsx");-const READINESS = readFileSync(- fileURLToPath(- new URL("../src/features/native-intents/use-native-readiness.ts", import.meta.url),- ),- "utf8",-);+const COMMANDS = readText("../../src-tauri/src/commands.rs");-const PREFLIGHT = readFileSync(- fileURLToPath(new URL("../../src-tauri/src/preflight.rs", import.meta.url)),- "utf8",-);+const READINESS = readSrc("features/native-intents/use-native-readiness.ts");++const PREFLIGHT = readText("../../src-tauri/src/preflight.rs");test("the picker is gated on the backend capability, not on isTauri alone", () => {assert.match(diff --git a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts b/studio/frontend/tests/llama-extra-args-diagnostics.test.tsindex ae60eccda9c..3dd86f66c98 100644--- a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts+++ b/studio/frontend/tests/llama-extra-args-diagnostics.test.ts@@ -2,9 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import { test } from "node:test";-import { fileURLToPath } from "node:url";import type { LlamaFlagCatalog } from "../src/features/model-picker/api/llama-flags.ts";import {diagnoseExtraArgs,@@ -14,6 +12,8 @@ import {sanitizeStoredExtraArgs,} from "../src/features/model-picker/model-config/llama-extra-args.ts";+import { readSrc } from "./helpers/kit.ts";+// The row is the backend's judgement shown early. Where these disagree, the panel// accepts an argument the load then refuses, or warns about one that works.@@ -581,15 +581,7 @@ test("what the quoting makes of an argument counts on Windows", () => {// The harness has no DOM renderer, so the row's contract is pinned the way the// sibling model-config tests do it.-const pageSource = readFileSync(- fileURLToPath(- new URL(- "../src/features/model-picker/components/model-config-page.tsx",- import.meta.url,- ),- ),- "utf8",-);+const pageSource = readSrc("features/model-picker/components/model-config-page.tsx");test("the row stores argv tokens, not the typed string", () => {const row = pageSource.slice(pageSource.indexOf("function ExtraArgsRow("));@@ -675,15 +667,7 @@ test("the row does not withdraw its objection when it unmounts", () => {});test("a config that never read the stored value is not sent as a clear", () => {- const overrides = readFileSync(- fileURLToPath(- new URL(- "../src/features/model-picker/api/model-overrides.ts",- import.meta.url,- ),- ),- "utf8",- ).replace(/\s+/g, " ");+ const overrides = readSrc("features/model-picker/api/model-overrides.ts").replace(/\s+/g, " ");// The route preserves llama_extra_args when omitted, which is what kept CLI-set// flags alive while this panel had no control. Sending [] for a config that never// loaded them would wipe them on the first save.@@ -694,12 +678,7 @@ test("a config that never read the stored value is not sent as a clear", () => {});test("the load sends the flags only once they are known", () => {- const composer = readFileSync(- fileURLToPath(- new URL("../src/features/chat/shared-composer.tsx", import.meta.url),- ),- "utf8",- ).replace(/\s+/g, " ");+ const composer = readSrc("features/chat/shared-composer.tsx").replace(/\s+/g, " ");assert.match(composer,/ownConfig\.llamaExtraArgs !== undefined \? .* \{ llama_extra_args: ownConfig\.llamaExtraArgs \?\? \[\] \} : \{\}/,@@ -710,15 +689,7 @@ test("the panel's own Load goes through the runtime, which sends them too", () =// Found by loading a model from the panel and reading the emitted command: the// flags were in the config and absent from the argv, because this hook is the// path the Load button takes and it built the payload field by field.- const runtime = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- ),- "utf8",- ).replace(/\s+/g, " ");+ const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts").replace(/\s+/g, " ");assert.match(runtime,/const loadLlamaExtraArgs = pendingLoadConfig\?\.llamaExtraArgs/,@@ -803,15 +774,7 @@ test("hydration asks under the keys the load path uses", () => {});test("a rollback restores the previous model with its arguments", () => {- const runtime = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- ),- "utf8",- ).replace(/\s+/g, " ");+ const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts").replace(/\s+/g, " ");// By the time this runs the TARGET is resident, so an omitted field inherits// across models, which the route refuses, and the previous model would come back// without the arguments it had been running.@@ -861,15 +824,7 @@ test("a hydrated list is judged even when the row cannot be", () => {});test("the runtime preflight is sized with the arguments the load sends", () => {- const runtime = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- ),- "utf8",- ).replace(/\s+/g, " ");+ const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts").replace(/\s+/g, " ");// A --ctx-size or cache override changes the memory /validate estimates. During// training an approval it did not size for means unloading the resident model and// having /load refuse the target, which is a rollback the user never asked for.@@ -884,15 +839,7 @@ test("the runtime preflight is sized with the arguments the load sends", () => {});test("a catalogue read from the previous binary is discarded", () => {- const flagsApi = readFileSync(- fileURLToPath(- new URL(- "../src/features/model-picker/api/llama-flags.ts",- import.meta.url,- ),- ),- "utf8",- ).replace(/\s+/g, " ");+ const flagsApi = readSrc("features/model-picker/api/llama-flags.ts").replace(/\s+/g, " ");// A switch that completes mid-request must not have the old build's flags written// back, and the next caller must not be handed that same promise.assert.match(flagsApi, /catalogGeneration \+= 1;/);@@ -1305,15 +1252,7 @@ test("the attached spelling is refused wherever it is judged", () => {});test("the managed answer is invalidated with the catalogue", () => {- const flagsApi = readFileSync(- fileURLToPath(- new URL(- "../src/features/model-picker/api/llama-flags.ts",- import.meta.url,- ),- ),- "utf8",- ).replace(/\s+/g, " ");+ const flagsApi = readSrc("features/model-picker/api/llama-flags.ts").replace(/\s+/g, " ");// Its denylist is Unsloth's own, but it carries defaultParallelSlots beside it and// that is the EFFECTIVE count: a build without --kv-unified serves one slot however// many are configured. Updating llama.cpp from the banner left a tab that had@@ -1404,15 +1343,7 @@ test("a quoted value that begins with a hyphen is a value, not a flag", () => {});test("a managed answer from the previous binary is never published", () => {- const flagsApi = readFileSync(- fileURLToPath(- new URL(- "../src/features/model-picker/api/llama-flags.ts",- import.meta.url,- ),- ),- "utf8",- ).replace(/\s+/g, " ");+ const flagsApi = readSrc("features/model-picker/api/llama-flags.ts").replace(/\s+/g, " ");// Clearing the cache is not enough on its own: a managed request already on the// wire when llama.cpp is replaced would resolve afterwards and put the old// build's defaultParallelSlots back, where it would stay for the session. Thediff --git a/studio/frontend/tests/llama-extra-args-status-hydration.test.ts b/studio/frontend/tests/llama-extra-args-status-hydration.test.tsindex 8cd40dfb123..5dfe6e8d05d 100644--- a/studio/frontend/tests/llama-extra-args-status-hydration.test.ts+++ b/studio/frontend/tests/llama-extra-args-status-hydration.test.ts@@ -14,18 +14,13 @@// seed test next door: the applier is one large object literal with no seam to call.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import path from "node:path";import { test } from "node:test";-import { fileURLToPath } from "node:url";-const HERE = path.dirname(fileURLToPath(import.meta.url));-const read = (relative: string) =>- readFileSync(path.join(HERE, "..", relative), "utf8");+import { readSrc } from "./helpers/kit.ts";-const APPLIER = read("src/features/chat/lib/apply-inference-status-to-store.ts");-const RUNTIME = read("src/features/chat/hooks/use-chat-model-runtime.ts");-const API_TYPES = read("src/features/chat/types/api.ts");+const APPLIER = readSrc("features/chat/lib/apply-inference-status-to-store.ts");+const RUNTIME = readSrc("features/chat/hooks/use-chat-model-runtime.ts");+const API_TYPES = readSrc("features/chat/types/api.ts");test("the status type carries the running arguments", () => {assert.match(API_TYPES, /requested_llama_extra_args\?: string\[\] \| null;/);diff --git a/studio/frontend/tests/llama-job-lifecycle.test.ts b/studio/frontend/tests/llama-job-lifecycle.test.tsindex a1f1b8969e6..96d5f619413 100644--- a/studio/frontend/tests/llama-job-lifecycle.test.ts+++ b/studio/frontend/tests/llama-job-lifecycle.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {llamaReleaseChanged,@@ -12,6 +11,8 @@ import {ownedLlamaSwitchOutcome,} from "../src/lib/llama-job-lifecycle.ts";+import { readSrc } from "./helpers/kit.ts";+const SWITCH_STARTED_AT = "2026-08-12T15:00:00Z";test("an owned switch recognizes only its explicit running and terminal states", () => {@@ -127,10 +128,7 @@ test("a release change still needs both tags to name it", () => {});test("the banner asks the helper rather than comparing the two tags itself", () => {- const banner = readFileSync(- new URL("../src/components/llama-update-banner.tsx", import.meta.url),- "utf8",- );+ const banner = readSrc("components/llama-update-banner.tsx");assert.match(banner, /const versionChanged = llamaReleaseChanged\(/);assert.doesNotMatch(banner, /installedTag !== latestTag/);});diff --git a/studio/frontend/tests/loaded-build-panel-rows.test.ts b/studio/frontend/tests/loaded-build-panel-rows.test.tsindex 2a7d9dc4ab3..36965772686 100644--- a/studio/frontend/tests/loaded-build-panel-rows.test.ts+++ b/studio/frontend/tests/loaded-build-panel-rows.test.ts@@ -9,14 +9,11 @@*/import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import test from "node:test";-const source = readFileSync(- fileURLToPath(new URL("../src/features/images/images-page.tsx", import.meta.url)),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/images/images-page.tsx");test("the Memory recipe row renders on an offload with no memory mode", () => {// The native engine reports memory_mode null (it has no torchao path to choose one for) whilediff --git a/studio/frontend/tests/loaded-models-barrel-order.test.ts b/studio/frontend/tests/loaded-models-barrel-order.test.tsindex c3cde354d70..c224e22edde 100644--- a/studio/frontend/tests/loaded-models-barrel-order.test.ts+++ b/studio/frontend/tests/loaded-models-barrel-order.test.ts@@ -19,17 +19,13 @@// which is why it is pinned here rather than left to the build.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-function read(path: string): string {- return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");-}+import { readText } from "./helpers/kit.ts";-const BARREL = read("../src/features/loaded-models/index.ts");-const GENERAL_TAB = read("../src/features/settings/tabs/general-tab.tsx");-const INDICATOR = read(+const BARREL = readText("../src/features/loaded-models/index.ts");+const GENERAL_TAB = readText("../src/features/settings/tabs/general-tab.tsx");+const INDICATOR = readText("../src/features/loaded-models/loaded-models-indicator.tsx",);diff --git a/studio/frontend/tests/loaded-models-dismiss.test.ts b/studio/frontend/tests/loaded-models-dismiss.test.tsindex 0456e1ed969..e686f93b3b2 100644--- a/studio/frontend/tests/loaded-models-dismiss.test.ts+++ b/studio/frontend/tests/loaded-models-dismiss.test.ts@@ -6,10 +6,13 @@// waved away, and would otherwise also reopen one deliberately turned off.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { installLocalStorageFake } from "./helpers/kit.ts";+import { installLocalStorageFake, readSrc } from "./helpers/kit.ts";++const LOADED_MODELS_INDICATOR = readSrc(+ "features/loaded-models/loaded-models-indicator.tsx",+);const { store } = installLocalStorageFake();@@ -105,34 +108,24 @@ test("setting the dismissal to what it already is changes nothing", () => {});test("the dismissal key is cleared by Reset all local preferences", () => {- const generalTab = readFileSync(- new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),- "utf8",- );+ const generalTab = readSrc("features/settings/tabs/general-tab.tsx");assert.match(generalTab, /LOADED_MODELS_PREFERENCE_KEYS\.dismissed,/);});test("the card carries a close button, and a load brings it back", () => {- const indicator = readFileSync(- new URL(- "../src/features/loaded-models/loaded-models-indicator.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(indicator, /aria-label="Close loaded models"/);+ assert.match(LOADED_MODELS_INDICATOR, /aria-label="Close loaded models"/);assert.match(- indicator,+ LOADED_MODELS_INDICATOR,/onClick=\{\(\) => setLoadedModelsDismissed\(true\)\}/,);// Reopened on the START of a load, so the card is up for as long as the toast.assert.match(- indicator,+ LOADED_MODELS_INDICATOR,/subscribeModelLifecycle\(\(\{ loading \}\) => \{\s*if \(loading\) \{\s*setLoadedModelsDismissed\(false\);/,);// And the gate reads it. Reachability is hoisted so tracking can share it.assert.match(- indicator,+ LOADED_MODELS_INDICATOR,/const enabled = showIndicator && !dismissed && reachable;/,);});@@ -140,37 +133,23 @@ test("the card carries a close button, and a load brings it back", () => {// Requested by name: hugeicons.com/icon/sparkle. Singular, so NOT the free// set's SparklesIcon (two stars) nor lib/sparkles-icon, which is a shield.test("the card is badged with the single sparkle, not the brain", () => {- const indicator = readFileSync(- new URL(- "../src/features/loaded-models/loaded-models-indicator.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(indicator, /icon=\{SparkleIcon\}/);- assert.match(indicator, /from "@\/lib\/sparkle-icon"/);- assert.doesNotMatch(indicator, /AiBrain01Icon|SparklesIcon/);+ assert.match(LOADED_MODELS_INDICATOR, /icon=\{SparkleIcon\}/);+ assert.match(LOADED_MODELS_INDICATOR, /from "@\/lib\/sparkle-icon"/);+ assert.doesNotMatch(LOADED_MODELS_INDICATOR, /AiBrain01Icon|SparklesIcon/);});// Releasing the weights is not the same act as closing the card, so it must not// wear the same X.test("a row ejects with the eject glyph, the header closes with an X", () => {- const indicator = readFileSync(- new URL(- "../src/features/loaded-models/loaded-models-indicator.tsx",- import.meta.url,- ),- "utf8",- );- const row = indicator.slice(- indicator.indexOf("function LoadedModelRow"),- indicator.indexOf("export function LoadedModelsIndicator"),+ const row = LOADED_MODELS_INDICATOR.slice(+ LOADED_MODELS_INDICATOR.indexOf("function LoadedModelRow"),+ LOADED_MODELS_INDICATOR.indexOf("export function LoadedModelsIndicator"),);assert.match(row, /icon=\{RemoveCircleIcon\}/);assert.doesNotMatch(row, /icon=\{Cancel01Icon\}/);// The close button keeps the X, as the Live monitor's does.- const header = indicator.slice(- indicator.indexOf('aria-label="Close loaded models"'),+ const header = LOADED_MODELS_INDICATOR.slice(+ LOADED_MODELS_INDICATOR.indexOf('aria-label="Close loaded models"'),);assert.match(header, /icon=\{Cancel01Icon\}/);});@@ -182,23 +161,19 @@ test("a row ejects with the eject glyph, the header closes with an X", () => {// 401 ran authFetch's refresh-then-redirect ladder against no session at all.// Asserted by reading the source, since the node suite has no DOM to mount in.test("recording follows the route and auth gate, but not the dismissal", () => {- const INDICATOR = readFileSync(- new URL(- "../src/features/loaded-models/loaded-models-indicator.tsx",- import.meta.url,- ),- "utf8",- );// The auth gate lives in canShowIndicator, so `reachable` is what carries it.- assert.match(INDICATOR, /const reachable = canShowIndicator\(pathname\);/);assert.match(- INDICATOR,+ LOADED_MODELS_INDICATOR,+ /const reachable = canShowIndicator\(pathname\);/,+ );+ assert.match(+ LOADED_MODELS_INDICATOR,/hasAuthToken\(\) && !mustChangePassword\(\)/,"canShowIndicator must still be the thing that gates on auth",);- const call = INDICATOR.slice(- INDICATOR.indexOf("useLoadedModels("),- INDICATOR.indexOf("useLoadedModels(") + 200,+ const call = LOADED_MODELS_INDICATOR.slice(+ LOADED_MODELS_INDICATOR.indexOf("useLoadedModels("),+ LOADED_MODELS_INDICATOR.indexOf("useLoadedModels(") + 200,);assert.match(call, /showIndicator && reachable/, "track must be gated too");assert.doesNotMatch(diff --git a/studio/frontend/tests/loaded-models-drag-restore.test.ts b/studio/frontend/tests/loaded-models-drag-restore.test.tsindex 38d723b6d73..1c48c761494 100644--- a/studio/frontend/tests/loaded-models-drag-restore.test.ts+++ b/studio/frontend/tests/loaded-models-drag-restore.test.ts@@ -16,21 +16,15 @@// reading the source, since the node suite has no DOM to mount into.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import { clampToViewport } from "../src/features/loaded-models/use-drag-position.ts";-const SOURCE = readFileSync(- fileURLToPath(- new URL(- "../src/features/loaded-models/use-drag-position.ts",- import.meta.url,- ),- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const USE_DRAG_POSITION = readSrc("features/loaded-models/use-drag-position.ts");++const SOURCE = readSrc("features/loaded-models/use-drag-position.ts");const CARD = { width: 268, height: 160 };const LAPTOP = { width: 1280, height: 800 };@@ -167,31 +161,14 @@ test("the drag captures the pointer", () => {// leave a stale flag for the pill, and the pill's click always reads its own// press. Verified in a real browser: dragging by the grip, collapsing, and// clicking the pill once reopens the card.-const INDICATOR = readFileSync(- fileURLToPath(- new URL(- "../src/features/loaded-models/loaded-models-indicator.tsx",- import.meta.url,- ),- ),- "utf8",-);+const INDICATOR = readSrc("features/loaded-models/loaded-models-indicator.tsx");test("every drag handle goes through startDrag, which resets the sentinel", () => {- const HOOK = readFileSync(- fileURLToPath(- new URL(- "../src/features/loaded-models/use-drag-position.ts",- import.meta.url,- ),- ),- "utf8",- );// The reset lives in startDrag's body, so it runs for the pill and the grip// alike. Move it out and a stale flag becomes reachable.- const startDrag = HOOK.slice(- HOOK.indexOf("const startDrag = useCallback("),- HOOK.indexOf("// One paint per frame"),+ const startDrag = USE_DRAG_POSITION.slice(+ USE_DRAG_POSITION.indexOf("const startDrag = useCallback("),+ USE_DRAG_POSITION.indexOf("// One paint per frame"),);assert.match(startDrag, /movedRef\.current = false;/);// Both handles, so neither can start a drag without arming that reset.@@ -213,25 +190,16 @@ test("only the pill consumes the sentinel, since only it has a click", () => {// large monitor, and going back to that monitor left the card where the laptop// had put it. Only a landed drag is stored; the read path clamps anyway.test("only a drag persists a position, never a reclamp", () => {- const HOOK = readFileSync(- fileURLToPath(- new URL(- "../src/features/loaded-models/use-drag-position.ts",- import.meta.url,- ),- ),- "utf8",- );- const settleAt = HOOK.indexOf("const settle = useCallback(");- const settle = HOOK.slice(+ const settleAt = USE_DRAG_POSITION.indexOf("const settle = useCallback(");+ const settle = USE_DRAG_POSITION.slice(settleAt,- HOOK.indexOf("}, [applyPending, storageKey]);", settleAt),+ USE_DRAG_POSITION.indexOf("}, [applyPending, storageKey]);", settleAt),);assert.match(settle, /store\(storageKey, landed\)/);// The old shape: an effect on `position`, which every reclamp also changed.- assert.doesNotMatch(HOOK, /useEffect\(\(\) => \{\s*if \(pressing\) return;\s*store\(/);+ assert.doesNotMatch(USE_DRAG_POSITION, /useEffect\(\(\) => \{\s*if \(pressing\) return;\s*store\(/);assert.equal(- HOOK.split("store(storageKey").length - 1,+ USE_DRAG_POSITION.split("store(storageKey").length - 1,1,"one write, in settle",);diff --git a/studio/frontend/tests/loaded-models-eject-unverified.test.ts b/studio/frontend/tests/loaded-models-eject-unverified.test.tsindex d5f358e7f44..d154d8b3a69 100644--- a/studio/frontend/tests/loaded-models-eject-unverified.test.ts+++ b/studio/frontend/tests/loaded-models-eject-unverified.test.ts@@ -14,16 +14,11 @@// distinguishable, and the unreadable one must not be spelled `null`.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-const SOURCE = readFileSync(- fileURLToPath(- new URL("../src/features/loaded-models/loaded-models-api.ts", import.meta.url),- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const SOURCE = readSrc("features/loaded-models/loaded-models-api.ts");test("an unreadable verification is its own outcome, not `ejected`", () => {assert.match(@@ -66,12 +61,7 @@ test("the sentinel is checked before the truthiness test that would hide it", ()});test("the user is told it was not confirmed, not that it worked", () => {- const HOOK = readFileSync(- fileURLToPath(- new URL("../src/features/loaded-models/use-loaded-models.ts", import.meta.url),- ),- "utf8",- );+ const HOOK = readSrc("features/loaded-models/use-loaded-models.ts");const branch = HOOK.slice(HOOK.indexOf('outcome.status === "unverified"'),HOOK.indexOf('outcome.status === "replaced"'),diff --git a/studio/frontend/tests/loaded-models-pending-reset.test.ts b/studio/frontend/tests/loaded-models-pending-reset.test.tsindex a813f677f00..6e12520229b 100644--- a/studio/frontend/tests/loaded-models-pending-reset.test.ts+++ b/studio/frontend/tests/loaded-models-pending-reset.test.ts@@ -14,9 +14,7 @@// the hook into.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import {type LoadedModelEntry,@@ -24,15 +22,9 @@ import {withPendingLoads,} from "../src/features/loaded-models/loaded-models-sources.ts";-const SOURCE = readFileSync(- fileURLToPath(- new URL(- "../src/features/loaded-models/use-loaded-models.ts",- import.meta.url,- ),- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const SOURCE = readSrc("features/loaded-models/use-loaded-models.ts");test("a stale pending entry outlives every poll, so it must not survive a disable", () => {const pending = new Map<LoadedModelSource, string | null>([@@ -173,15 +165,7 @@ test("an unnamed announcement defers to any row for its runtime", () => {// on, since the poll synthesises their loading rows; images and video have no// such fallback, so the card stayed hidden for the whole load.test("recording is gated on the preference, not on whether the card shows", () => {- const SOURCE = readFileSync(- fileURLToPath(- new URL(- "../src/features/loaded-models/use-loaded-models.ts",- import.meta.url,- ),- ),- "utf8",- );+ const SOURCE = readSrc("features/loaded-models/use-loaded-models.ts");assert.match(SOURCE,/track: boolean = enabled/,@@ -194,14 +178,8 @@ test("recording is gated on the preference, not on whether the card shows", () =assert.match(subscribe, /if \(!track\) return;/);assert.doesNotMatch(subscribe, /if \(!enabled\) return;/);- const INDICATOR = readFileSync(- fileURLToPath(- new URL(- "../src/features/loaded-models/loaded-models-indicator.tsx",- import.meta.url,- ),- ),- "utf8",+ const INDICATOR = readSrc(+ "features/loaded-models/loaded-models-indicator.tsx",);// Dismissal must not stop the recording, or the card cannot reopen for the// load. Reachability must, since it carries the auth gate: tracking on thediff --git a/studio/frontend/tests/loaded-models-settled-retire.test.ts b/studio/frontend/tests/loaded-models-settled-retire.test.tsindex 4549c8e92bf..50762f845c3 100644--- a/studio/frontend/tests/loaded-models-settled-retire.test.ts+++ b/studio/frontend/tests/loaded-models-settled-retire.test.ts@@ -9,16 +9,12 @@// loading off the card, on the strength of a request that failed.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-function read(path: string): string {- return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");-}+import { readText } from "./helpers/kit.ts";-const HOOK = read("../src/features/loaded-models/use-loaded-models.ts");-const API = read("../src/features/loaded-models/loaded-models-api.ts");+const HOOK = readText("../src/features/loaded-models/use-loaded-models.ts");+const API = readText("../src/features/loaded-models/loaded-models-api.ts");test("the read reports which sources it could not see", () => {assert.match(API, /export type LoadedModelsRead = \{/);diff --git a/studio/frontend/tests/loaded-models-surface.test.ts b/studio/frontend/tests/loaded-models-surface.test.tsindex 0ea3a7cc6cc..28112855289 100644--- a/studio/frontend/tests/loaded-models-surface.test.ts+++ b/studio/frontend/tests/loaded-models-surface.test.ts@@ -5,21 +5,13 @@// do not. Read from the source: the node suite has no DOM to compute styles in.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const CSS = readFileSync(new URL("../src/index.css", import.meta.url), "utf8");-const INDICATOR = readFileSync(- new URL(- "../src/features/loaded-models/loaded-models-indicator.tsx",- import.meta.url,- ),- "utf8",-);-const BANNER = readFileSync(- new URL("../src/components/llama-update-banner.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const CSS = readSrc("index.css");+const INDICATOR = readSrc("features/loaded-models/loaded-models-indicator.tsx");+const BANNER = readSrc("components/llama-update-banner.tsx");function surface(source: string, anchor: string): string {const at = source.indexOf(anchor);diff --git a/studio/frontend/tests/mac-titlebar-optical-alignment.test.ts b/studio/frontend/tests/mac-titlebar-optical-alignment.test.tsindex c95ee348b5d..06cfd4062b7 100644--- a/studio/frontend/tests/mac-titlebar-optical-alignment.test.ts+++ b/studio/frontend/tests/mac-titlebar-optical-alignment.test.ts@@ -1,14 +1,12 @@import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-const source = (path: string) =>- readFile(new URL(`../src/${path}`, import.meta.url), "utf8");+import { readSrc } from "./helpers/kit.ts";test("mac titlebar navigation shifts buttons with centered glyphs", async () => {const [titlebar, provider] = await Promise.all([- source("components/tauri/window-titlebar.tsx"),- source("app/provider.tsx"),+ readSrc("components/tauri/window-titlebar.tsx"),+ readSrc("app/provider.tsx"),]);const macStyle = provider.match(/const MAC_NATIVE_CHROME_STYLE = \{[\s\S]*?\} as CSSProperties;/,@@ -28,10 +26,10 @@ test("mac titlebar navigation shifts buttons with centered glyphs", async () =>test("mac chat and media headers share the lowered control row", async () => {const [provider, chat, images, video] = await Promise.all([- source("app/provider.tsx"),- source("features/chat/chat-page.tsx"),- source("features/images/images-page.tsx"),- source("features/video/video-page.tsx"),+ readSrc("app/provider.tsx"),+ readSrc("features/chat/chat-page.tsx"),+ readSrc("features/images/images-page.tsx"),+ readSrc("features/video/video-page.tsx"),]);const macStyle = provider.match(diff --git a/studio/frontend/tests/manage-chats-bulk-selection.test.ts b/studio/frontend/tests/manage-chats-bulk-selection.test.tsindex b80d5c7659f..d176883cc7c 100644--- a/studio/frontend/tests/manage-chats-bulk-selection.test.ts+++ b/studio/frontend/tests/manage-chats-bulk-selection.test.ts@@ -5,11 +5,11 @@// view pulls in the whole app, so it is read as text; the store runs for real.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {installLocalStorageFake,+ readSrcAsync,registerBundlerResolver,} from "./helpers/kit.ts";@@ -24,12 +24,8 @@ const { rangeBetween } = await import();async function manageChatsSource(): Promise<string> {- return await readFile(- new URL(- "../src/features/settings/components/manage-chats-view.tsx",- import.meta.url,- ),- "utf8",+ return await readSrcAsync(+ "features/settings/components/manage-chats-view.tsx",);}diff --git a/studio/frontend/tests/manage-chats-open-project.test.ts b/studio/frontend/tests/manage-chats-open-project.test.tsindex b21cb4b5598..066b69e9077 100644--- a/studio/frontend/tests/manage-chats-open-project.test.ts+++ b/studio/frontend/tests/manage-chats-open-project.test.ts@@ -5,16 +5,13 @@// The .tsx view pulls in the whole app, so it is read as text.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readSrcAsync } from "./helpers/kit.ts";+async function openChatSource(): Promise<string> {- const src = await readFile(- new URL(- "../src/features/settings/components/manage-chats-view.tsx",- import.meta.url,- ),- "utf8",+ const src = await readSrcAsync(+ "features/settings/components/manage-chats-view.tsx",);const start = src.indexOf("function openChat(");assert.ok(start !== -1, "openChat not found in manage-chats-view.tsx");diff --git a/studio/frontend/tests/markdown-block-boundary.test.ts b/studio/frontend/tests/markdown-block-boundary.test.tsindex 0738154462d..61575857655 100644--- a/studio/frontend/tests/markdown-block-boundary.test.ts+++ b/studio/frontend/tests/markdown-block-boundary.test.ts@@ -11,6 +11,8 @@ import {markdownBlockFallback,} from "../src/components/assistant-ui/markdown-block-fallback.ts";+import { readSrc } from "./helpers/kit.ts";+/*** Streamdown loads the syntax highlighted code body and the Mermaid renderer* through `React.lazy`, and it fetches them the first time a reply contains@@ -439,13 +441,7 @@ test("the whole-block boundary is still the catch-all above them", () => {});test("the boundary does not retry the import it caught", () => {- const boundary = readFileSync(- new URL(- "../src/components/assistant-ui/markdown-block-boundary.tsx",- import.meta.url,- ),- "utf8",- );+ const boundary = readSrc("components/assistant-ui/markdown-block-boundary.tsx");// React and the browser's module map both cache a rejected dynamic import// (whatwg/html#6768), so a boundary that resets on new props rethrows on everydiff --git a/studio/frontend/tests/markdown-image-recovery.test.ts b/studio/frontend/tests/markdown-image-recovery.test.tsindex e4504e106a3..81ee08f4d0d 100644--- a/studio/frontend/tests/markdown-image-recovery.test.ts+++ b/studio/frontend/tests/markdown-image-recovery.test.ts@@ -2,20 +2,15 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { runInNewContext } from "node:vm";import ts from "typescript";+import { readSrc } from "./helpers/kit.ts";+// Exercise production event handlers with a deterministic state seam.function renderer() {- const source = readFileSync(- new URL(- "../src/components/assistant-ui/markdown-text.tsx",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("components/assistant-ui/markdown-text.tsx");const parsed = ts.createSourceFile("markdown-text.tsx",source,diff --git a/studio/frontend/tests/markdown-sandbox-image.test.ts b/studio/frontend/tests/markdown-sandbox-image.test.tsindex 1d6ca77e23b..d2636c90b02 100644--- a/studio/frontend/tests/markdown-sandbox-image.test.ts+++ b/studio/frontend/tests/markdown-sandbox-image.test.ts@@ -2,9 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import {SANDBOX_INLINE_IMAGE_EXTS,@@ -15,6 +13,8 @@ import {} from "../src/components/assistant-ui/sandbox-files.ts";import { safeMarkdownUrl } from "../src/lib/safe-markdown-url.ts";+import { readText } from "./helpers/kit.ts";+/** THREE PIECES ONLY WORK TOGETHER, and nothing in the type system joins them:*@@ -31,13 +31,10 @@ import { safeMarkdownUrl } from "../src/lib/safe-markdown-url.ts";* change that does nothing.*/-const read = (relative: string): string =>- readFileSync(new URL(relative, import.meta.url), "utf8");--const MARKDOWN_TEXT = read("../src/components/assistant-ui/markdown-text.tsx");-const HOOK = read("../src/components/assistant-ui/use-sandbox-image.ts");-const TOOL_UI = read("../src/components/assistant-ui/tool-ui-python.tsx");-const BACKEND = read(+const MARKDOWN_TEXT = readText("../src/components/assistant-ui/markdown-text.tsx");+const HOOK = readText("../src/components/assistant-ui/use-sandbox-image.ts");+const TOOL_UI = readText("../src/components/assistant-ui/tool-ui-python.tsx");+const BACKEND = readText("../../backend/routes/inference.py",);diff --git a/studio/frontend/tests/math-block-containment-wiring.test.ts b/studio/frontend/tests/math-block-containment-wiring.test.tsindex c2b978fed05..0fc9d5495f9 100644--- a/studio/frontend/tests/math-block-containment-wiring.test.ts+++ b/studio/frontend/tests/math-block-containment-wiring.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -14,6 +13,8 @@ import {MATH_BLOCK_CONTAINMENT_ON,} from "../src/components/assistant-ui/math-block-mode.ts";+import { readText } from "./helpers/kit.ts";+/** THE THREE PIECES ONLY WORK TOGETHER, and nothing in the type system joins them:*@@ -29,16 +30,15 @@ import {* change that does nothing.*/-const read = (relative: string): string =>- readFileSync(new URL(relative, import.meta.url), "utf8");--const MARKDOWN_TEXT = read("../src/components/assistant-ui/markdown-text.tsx");-const INDEX_CSS = read("../src/index.css");-const MAIN_TSX = read("../src/main.tsx");-const MATH_BLOCK_MODE = read(+const MARKDOWN_TEXT = readText(+ "../src/components/assistant-ui/markdown-text.tsx",+);+const INDEX_CSS = readText("../src/index.css");+const MAIN_TSX = readText("../src/main.tsx");+const MATH_BLOCK_MODE = readText("../src/components/assistant-ui/math-block-mode.ts",);-const CONTAINMENT = read(+const CONTAINMENT = readText("../src/components/assistant-ui/math-block-containment.ts",);diff --git a/studio/frontend/tests/mcp-server-arguments.test.ts b/studio/frontend/tests/mcp-server-arguments.test.tsindex 81b49559ac8..48f40676c4b 100644--- a/studio/frontend/tests/mcp-server-arguments.test.ts+++ b/studio/frontend/tests/mcp-server-arguments.test.ts@@ -19,6 +19,14 @@ import {waitForPendingMcpServerMutations,} from "../src/features/chat/api/mcp-server-mutation-tracker.ts";+import { readSrc } from "./helpers/kit.ts";++const MCP_SERVERS_API = readSrc("features/chat/api/mcp-servers-api.ts");+const CHAT_MCP_SERVERS_DIALOG = readSrc(+ "features/chat/chat-mcp-servers-dialog.tsx",+);+const MCP_COMPOSER_BUTTON = readSrc("features/chat/mcp-composer-button.tsx");+function deferred<T>() {let resolve!: (value: T | PromiseLike<T>) => void;let reject!: (reason?: unknown) => void;@@ -96,100 +104,111 @@ test("command, order, value, and intentional empty argument changes require enco});test("the helper never parses, splits, joins, trims, or quotes commands", () => {- const helper = readFileSync(- new URL("../src/features/chat/mcp-server-form.ts", import.meta.url),- "utf8",- );+ const helper = readSrc("features/chat/mcp-server-form.ts");assert.doesNotMatch(helper, /\.(?:split|join|trim)\s*\(/);assert.doesNotMatch(helper, /JSON\.stringify|replace\s*\(/);});test("the dialog wires backend codec calls, stale guards, and a stdio-only editor", () => {- const dialog = readFileSync(- new URL(- "../src/features/chat/chat-mcp-servers-dialog.tsx",- import.meta.url,- ),- "utf8",- );- const api = readFileSync(- new URL("../src/features/chat/api/mcp-servers-api.ts", import.meta.url),- "utf8",- );-- assert.match(api, /mcpRequest\("\/stdio\/decode"/);- assert.match(api, /mcpRequest\("\/stdio\/encode"/);- assert.match(dialog, /await decodeMcpStdioCommand\(server\.url\)/);- assert.match(dialog, /await encodeMcpStdioCommand\(\{/);- assert.match(dialog, /formGenerationRef\.current !== generation/);- assert.match(dialog, /activeEditIdRef\.current !== server\.id/);- assert.match(- dialog,+ assert.match(MCP_SERVERS_API, /mcpRequest\("\/stdio\/decode"/);+ assert.match(MCP_SERVERS_API, /mcpRequest\("\/stdio\/encode"/);+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,+ /await decodeMcpStdioCommand\(server\.url\)/,+ );+ assert.match(CHAT_MCP_SERVERS_DIALOG, /await encodeMcpStdioCommand\(\{/);+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,+ /formGenerationRef\.current !== generation/,+ );+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,+ /activeEditIdRef\.current !== server\.id/,+ );+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,/function handleOpenChange[\s\S]*formGenerationRef\.current \+= 1;[\s\S]*onOpenChange\(next\)/,);- assert.match(dialog, /addressIsCommand && \(\s*<ArgumentsEditor/);- assert.match(dialog, /const addressIsCommand = form\.transport === "stdio"/);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,+ /addressIsCommand && \(\s*<ArgumentsEditor/,+ );+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,+ /const addressIsCommand = form\.transport === "stdio"/,+ );+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,/function formWithAddress[\s\S]*transportFromAddress\([\s\S]*preservePartialHttp \? form\.credentialTransport : null[\s\S]*headers: transportChanged \? \[\] : form\.headers/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/queueMicrotask\(\(\) => \{\s*if \(cancelled\) return;[\s\S]*setView\(\{ kind: "list" \}\)/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/function ArgumentsEditor[\s\S]*\{ id: newRowId\(\), value: "" \}/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/form\.transport === "http" && \([\s\S]*Use OAuth sign-in/,);- assert.match(dialog, /const decision = resolveMcpStdioUrl\(/);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,+ /const decision = resolveMcpStdioUrl\(/,+ );+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,/decision\.kind === "reuse"[\s\S]*url = view\.kind === "edit" \? undefined : decision\.url/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/const url = stdio\s*\? await encodeStdioForGeneration\([\s\S]*testMcpServer\(\{\s*url,/,);- assert.match(dialog, /return rows\.map\(\(row\) => row\.value\)/);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,+ /return rows\.map\(\(row\) => row\.value\)/,+ );+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,/function ArgumentsEditor[\s\S]*data-reload-snapshot-sensitive/,);- assert.match(api, /export function testMcpServer[\s\S]*body: \{\s*url:/);+ assert.match(+ MCP_SERVERS_API,+ /export function testMcpServer[\s\S]*body: \{\s*url:/,+ );assert.doesNotMatch(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/npx -y @modelcontextprotocol\/server-filesystem \/tmp/,);- assert.match(dialog, /URL or executable/);- assert.match(dialog, /https:\/\/example\.com\/mcp or npx/);- assert.match(dialog, /Add local arguments in the Arguments rows/);+ assert.match(CHAT_MCP_SERVERS_DIALOG, /URL or executable/);+ assert.match(CHAT_MCP_SERVERS_DIALOG, /https:\/\/example\.com\/mcp or npx/);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,+ /Add local arguments in the Arguments rows/,+ );+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,/setForm\(\(prev\) => formWithAddress\(prev, url, true\)\)/,);- assert.doesNotMatch(dialog, /form\.url\.(?:split|join)\s*\(/);- assert.doesNotMatch(dialog, /form\.arguments[^;\n]*\.join\s*\(/);+ assert.doesNotMatch(+ CHAT_MCP_SERVERS_DIALOG,+ /form\.url\.(?:split|join)\s*\(/,+ );+ assert.doesNotMatch(+ CHAT_MCP_SERVERS_DIALOG,+ /form\.arguments[^;\n]*\.join\s*\(/,+ );});test("every mutable MCP form editor is locked for the full pending interval", () => {- const dialog = readFileSync(- new URL(- "../src/features/chat/chat-mcp-servers-dialog.tsx",- import.meta.url,- ),- "utf8",- );const argumentsEditor = sourceBetween(- dialog,+ CHAT_MCP_SERVERS_DIALOG,"function ArgumentsEditor","function HeadersEditor",);const headersEditor = sourceBetween(- dialog,+ CHAT_MCP_SERVERS_DIALOG,"function HeadersEditor","export interface ChatMcpServersDialogProps",);@@ -205,122 +224,99 @@ test("every mutable MCP form editor is locked for the full pending interval", ()"header/env add, key, value, and remove must all be locked",);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/const formPending = importing \|\| codecPending \|\| testing \|\| saving/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/id="mcp-display-name"[\s\S]*?disabled=\{formPending\}[\s\S]*?\/>/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/id="mcp-url"[\s\S]*?disabled=\{formPending\}[\s\S]*?\/>/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/<ArgumentsEditor[\s\S]*?disabled=\{formPending\}[\s\S]*?\/>/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/id="mcp-oauth"[\s\S]*?disabled=\{formPending\}[\s\S]*?\/>/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/<HeadersEditor[\s\S]*?disabled=\{formPending\}[\s\S]*?\/>/,);});test("a decode error is announced and executable edits unlock manual recovery", () => {- const dialog = readFileSync(- new URL(- "../src/features/chat/chat-mcp-servers-dialog.tsx",- import.meta.url,- ),- "utf8",- );-assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/id="mcp-url"[\s\S]*?onChange=\{\(e\) => \{[\s\S]*?setCodecError\(null\)[\s\S]*?formWithAddress/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/role="alert"\s*aria-live="assertive"[\s\S]*?\{codecError\}/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/aria-busy=\{decodingCommand\}[\s\S]*role="status"\s*aria-live="polite"[\s\S]*Reading local command…/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/codecError && \([\s\S]*view\.kind === "edit"[\s\S]*void startEdit\(server\)[\s\S]*Retry/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/disabled=\{\s*formPending \|\|\s*codecError !== null \|\|\s*form\.transport === "unknown" \|\|\s*!form\.url\.trim\(\)/,);});test("dialog actions and reconciliation stop when the dialog closes", () => {- const dialog = readFileSync(- new URL(- "../src/features/chat/chat-mcp-servers-dialog.tsx",- import.meta.url,- ),- "utf8",- );-assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/useEffect\(\(\) => \{\s*if \(!open\) \{[\s\S]*subscribeToMcpServerMutationSettlements/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/actionGenerationRef\.current !== generation \|\| !openRef\.current/,);- assert.match(dialog, /open=\{open && confirmingDelete !== null\}/);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,+ /open=\{open && confirmingDelete !== null\}/,+ );+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,/<Button size="sm" onClick=\{startCreate\} disabled=\{importing \|\| blenderBusy\}>/,);});test("pending MCP actions remain keyed to their own server", () => {- const dialog = readFileSync(- new URL(- "../src/features/chat/chat-mcp-servers-dialog.tsx",- import.meta.url,- ),- "utf8",- );- const composer = readFileSync(- new URL("../src/features/chat/mcp-composer-button.tsx", import.meta.url),- "utf8",+ assert.match(+ MCP_COMPOSER_BUTTON,+ /pendingUrlsRef = useRef\(new Set<string>\(\)\)/,);-- assert.match(composer, /pendingUrlsRef = useRef\(new Set<string>\(\)\)/);assert.match(- composer,+ MCP_COMPOSER_BUTTON,/pendingUrlsRef\.current\.delete\(norm\);\s*setPendingUrls\(new Set\(pendingUrlsRef\.current\)\)/,);- assert.match(dialog, /refreshingIdsRef = useRef\(new Set<string>\(\)\)/);- assert.match(dialog, /togglingIdsRef = useRef\(new Set<string>\(\)\)/);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,+ /refreshingIdsRef = useRef\(new Set<string>\(\)\)/,+ );+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,+ /togglingIdsRef = useRef\(new Set<string>\(\)\)/,+ );+ assert.match(+ CHAT_MCP_SERVERS_DIALOG,/if \(!togglingIdsRef\.current\.has\(row\.id\)\) return row;[\s\S]*is_enabled: optimistic\.is_enabled/,);});test("dialog closure is blocked while a CRUD mutation is in flight", () => {- const dialog = readFileSync(- new URL(- "../src/features/chat/chat-mcp-servers-dialog.tsx",- import.meta.url,- ),- "utf8",- );const closeHandler = sourceBetween(- dialog,+ CHAT_MCP_SERVERS_DIALOG,"function handleOpenChange","async function encodeStdioForGeneration",);@@ -331,99 +327,82 @@ test("dialog closure is blocked while a CRUD mutation is in flight", () => {"the in-flight mutation guard must run before close invalidates the form generation",);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/<DialogContent[\s\S]*?showCloseButton=\{!blenderBusy && !\(saving && !codecPending\) && busyIds\.size === 0\}[\s\S]*?>/,"the built-in close control must disappear during the same mutation window",);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/onClick=\{cancelForm\}[\s\S]*?disabled=\{saving && !codecPending\}/,"the visible Cancel action must use the same mutation boundary",);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/async function encodeStdioForGeneration[\s\S]*setCodecPending\(true\);[\s\S]*await encodeMcpStdioCommand/,"codec encoding remains distinguishable so it can still be cancelled before CRUD starts",);});test("composer applies mutation responses before releasing each preset", () => {- const composer = readFileSync(- new URL("../src/features/chat/mcp-composer-button.tsx", import.meta.url),- "utf8",- );-assert.match(- composer,+ MCP_COMPOSER_BUTTON,/const applyServer = useCallback[\s\S]*setServers\(\(current\)[\s\S]*candidate\.id === server\.id/,);assert.match(- composer,+ MCP_COMPOSER_BUTTON,/applyServer\(\s*await createMcpServer\([\s\S]*pendingUrlsRef\.current\.delete\(norm\)/,);assert.match(- composer,+ MCP_COMPOSER_BUTTON,/applyServer\(\s*await updateMcpServer\([\s\S]*pendingUrlsRef\.current\.delete\(norm\)/,);assert.match(- composer,+ MCP_COMPOSER_BUTTON,/const \[serversLoaded, setServersLoaded\] = useState\(false\)[\s\S]*const hasLoadedServerSnapshotRef = useRef\(false\);[\s\S]*setServersLoaded\(false\);[\s\S]*setServers\(rows\);\s*hasLoadedServerSnapshotRef\.current = true;\s*setServersLoaded\(true\)/,);assert.match(- composer,+ MCP_COMPOSER_BUTTON,/catch \{\s*if \(\s*listRefreshGenerationRef\.current === generation &&\s*hasLoadedServerSnapshotRef\.current\s*\) \{\s*setServersLoaded\(true\);/,);assert.match(- composer,+ MCP_COMPOSER_BUTTON,/disabled=\{!serversLoaded \|\| pendingUrls\.has\(normalizeMcpUrl\(opts\.url\)\)\}/,);});test("MCP configuration remains reachable when the loaded model lacks tools", () => {- const composer = readFileSync(- new URL("../src/features/chat/mcp-composer-button.tsx", import.meta.url),- "utf8",- );-- assert.doesNotMatch(composer, /aria-disabled=\{true\}/);- assert.match(composer, /The loaded model cannot use MCP tools/);- assert.doesNotMatch(composer, /disabled=\{[^}]*!usable/);+ assert.doesNotMatch(MCP_COMPOSER_BUTTON, /aria-disabled=\{true\}/);+ assert.match(MCP_COMPOSER_BUTTON, /The loaded model cannot use MCP tools/);+ assert.doesNotMatch(MCP_COMPOSER_BUTTON, /disabled=\{[^}]*!usable/);assert.match(- composer,+ MCP_COMPOSER_BUTTON,/<DropdownMenuItem\s+onSelect=\{\(\) => \{\s*setMenuOpen\(false\);\s*setDialogOpen\(true\);/,);});test("full unmount invalidates cancellable stdio encode continuations", async () => {- const dialog = readFileSync(- new URL(- "../src/features/chat/chat-mcp-servers-dialog.tsx",- import.meta.url,- ),- "utf8",- );const refsAndCleanup = sourceBetween(- dialog,+ CHAT_MCP_SERVERS_DIALOG,"const formGenerationRef = useRef(0)","const refresh = useCallback",);const openLifecycle = sourceBetween(- dialog,+ CHAT_MCP_SERVERS_DIALOG,"useEffect(() => {\n formGenerationRef.current += 1;","function startCreate",);const encode = sourceBetween(- dialog,+ CHAT_MCP_SERVERS_DIALOG,"async function encodeStdioForGeneration","async function testConnection",);const testContinuation = sourceBetween(- dialog,+ CHAT_MCP_SERVERS_DIALOG,"async function testConnection","async function submitForm",);const crudContinuation = sourceBetween(- dialog,+ CHAT_MCP_SERVERS_DIALOG,"async function submitForm","async function onImportFile",);@@ -737,33 +716,18 @@ test("every list consumer uses the shared pending-mutation read barrier", () =>const chatRoot = fileURLToPath(new URL("../src/features/chat/", import.meta.url),);- const dialog = readFileSync(- new URL(- "../src/features/chat/chat-mcp-servers-dialog.tsx",- import.meta.url,- ),- "utf8",- );- const api = readFileSync(- new URL("../src/features/chat/api/mcp-servers-api.ts", import.meta.url),- "utf8",- );- const composer = readFileSync(- new URL("../src/features/chat/mcp-composer-button.tsx", import.meta.url),- "utf8",- );const listApi = sourceBetween(- api,+ MCP_SERVERS_API,"export function listMcpServers","export function createMcpServer",);const dialogRefresh = sourceBetween(- dialog,+ CHAT_MCP_SERVERS_DIALOG,"const refresh = useCallback","useEffect(() =>",);const composerRefresh = sourceBetween(- composer,+ MCP_COMPOSER_BUTTON,"const refresh = useCallback","// Load the server list on mount",);@@ -785,7 +749,7 @@ test("every list consumer uses the shared pending-mutation read barrier", () =>]);assert.equal(- api.match(/return trackMcpServerMutation\(/g)?.length,+ MCP_SERVERS_API.match(/return trackMcpServerMutation\(/g)?.length,5,"create, update, delete, import, and managed Blender updates must register at the API boundary",);@@ -822,11 +786,11 @@ test("every list consumer uses the shared pending-mutation read barrier", () =>/await listMcpServers\(\{\s*waitForPendingMutations,\s*minimumMutationEpoch,\s*\}\)/,);assert.match(- dialog,+ CHAT_MCP_SERVERS_DIALOG,/subscribeToMcpServerMutationSettlements\(\(epoch\) => \{\s*void refresh\(false, epoch\)/,);assert.match(- composer,+ MCP_COMPOSER_BUTTON,/subscribeToMcpServerMutationSettlements\(\(epoch\) => \{\s*void refresh\(false, epoch\)/,);assert.match(@@ -837,8 +801,11 @@ test("every list consumer uses the shared pending-mutation read barrier", () =>composerRefresh,/listRefreshGenerationRef\.current !== generation/,);- assert.doesNotMatch(dialog, /waitForPendingMcpServerMutations/);- assert.doesNotMatch(composer, /waitForPendingMcpServerMutations/);- assert.doesNotMatch(dialog, /await refresh\(\)/);- assert.doesNotMatch(composer, /await refresh\(\)/);+ assert.doesNotMatch(+ CHAT_MCP_SERVERS_DIALOG,+ /waitForPendingMcpServerMutations/,+ );+ assert.doesNotMatch(MCP_COMPOSER_BUTTON, /waitForPendingMcpServerMutations/);+ assert.doesNotMatch(CHAT_MCP_SERVERS_DIALOG, /await refresh\(\)/);+ assert.doesNotMatch(MCP_COMPOSER_BUTTON, /await refresh\(\)/);});diff --git a/studio/frontend/tests/media-eject-busy-state.test.ts b/studio/frontend/tests/media-eject-busy-state.test.tsindex 1d0d30be0ed..fcedc8460b9 100644--- a/studio/frontend/tests/media-eject-busy-state.test.ts+++ b/studio/frontend/tests/media-eject-busy-state.test.ts@@ -13,9 +13,9 @@// navigating away and back does not reset it either -- only a reload did.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";++import { readText } from "./helpers/kit.ts";// The runtime name is singular ("image"), the page is not: keep them apart, or// the listener lookup silently finds nothing and every check passes vacuously.@@ -24,12 +24,8 @@ const PAGES = [["Video", "video", "../src/features/video/video-page.tsx"],] as const;-function read(path: string): string {- return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");-}-for (const [page, runtime, path] of PAGES) {- const SOURCE = read(path);+ const SOURCE = readText(path);const listener = SOURCE.slice(SOURCE.indexOf(`subscribeModelEjected("${runtime}"`),// Wide enough for the pending-start fence the listener grew around that clear.diff --git a/studio/frontend/tests/media-generation-preset-claims.test.ts b/studio/frontend/tests/media-generation-preset-claims.test.tsindex 6f0bff9773e..e1aa804217f 100644--- a/studio/frontend/tests/media-generation-preset-claims.test.ts+++ b/studio/frontend/tests/media-generation-preset-claims.test.ts@@ -12,17 +12,13 @@// assert on the source, like the other page-wiring tests here.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-function read(path: string) {- return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");-}+import { readText } from "./helpers/kit.ts";-const IMAGES = read("../src/features/images/images-page.tsx");-const VIDEO = read("../src/features/video/video-page.tsx");-const HOOK = read(+const IMAGES = readText("../src/features/images/images-page.tsx");+const VIDEO = readText("../src/features/video/video-page.tsx");+const HOOK = readText("../src/features/generation-presets/use-media-generation-presets.ts",);diff --git a/studio/frontend/tests/media-idle-unload-api-only.test.ts b/studio/frontend/tests/media-idle-unload-api-only.test.tsindex a1fe2939ce6..b195f999023 100644--- a/studio/frontend/tests/media-idle-unload-api-only.test.ts+++ b/studio/frontend/tests/media-idle-unload-api-only.test.ts@@ -9,19 +9,11 @@// was unusable without re-enabling chat unloading first.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";--const SECTION = readFileSync(- fileURLToPath(- new URL(- "../src/features/settings/components/model-auto-switch-section.tsx",- import.meta.url,- ),- ),- "utf8",-);++import { readSrc } from "./helpers/kit.ts";++const SECTION = readSrc("features/settings/components/model-auto-switch-section.tsx");// The JSX guard the given row is rendered under: the nearest conditional above it at the// section's own indentation, so a `{settings.foo}` prop inside a neighbouring row is notdiff --git a/studio/frontend/tests/media-load-cancel.test.ts b/studio/frontend/tests/media-load-cancel.test.tsindex 916c50af950..e10cee7b563 100644--- a/studio/frontend/tests/media-load-cancel.test.ts+++ b/studio/frontend/tests/media-load-cancel.test.ts@@ -15,25 +15,21 @@// aria-hidden span, mouse-only by design).import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";++import { readText } from "./helpers/kit.ts";const PAGES = [["Images", "../src/features/images/images-page.tsx"],["Video", "../src/features/video/video-page.tsx"],] as const;-function read(path: string): string {- return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");-}--const DOWNLOAD_PANEL = read(+const DOWNLOAD_PANEL = readText("../src/features/hub/download-manager/download-manager-panel.tsx",);for (const [page, path] of PAGES) {- const SOURCE = read(path);+ const SOURCE = readText(path);test(`the ${page} load toast offers a Cancel action`, () => {assert.match(@@ -174,7 +170,6 @@ for (const [page, path] of PAGES) {);});-test(`the ${page} cancel fences the pending start request`, () => {// Cancel is reachable the instant `busy` turns "loading", which is before the start request// has even been sent. Its unload can therefore reach the backend BEFORE begin_load registers@@ -341,13 +336,12 @@ test("the download manager keeps its own, differently named cancel", () => {assert.match(DOWNLOAD_PANEL, /"Cancel download"/);});-test("cancelling a deploy does not leave the adapter queued", () => {// handleDeployAdapter parks the trained adapter in pendingDeploy and loads its base. That ref// is applied to whatever LoRA-capable model becomes resident NEXT, so a cancelled deploy would// silently mix a discarded adapter into an unrelated model's generations. Clearing it belongs// in dropResidentState, which every cancel and every eject already runs.- const SOURCE = read("../src/features/images/images-page.tsx");+ const SOURCE = readText("../src/features/images/images-page.tsx");const drop = SOURCE.slice(SOURCE.indexOf("const dropResidentState = useCallback("),// Anchored from the opening, so the deps can grow without silently widening this slice.diff --git a/studio/frontend/tests/media-status-sequencing.test.ts b/studio/frontend/tests/media-status-sequencing.test.tsindex 269435134aa..01c3333420c 100644--- a/studio/frontend/tests/media-status-sequencing.test.ts+++ b/studio/frontend/tests/media-status-sequencing.test.ts@@ -12,13 +12,9 @@// which the node suite cannot mount.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-function source(path: string): string {- return readFileSync(fileURLToPath(new URL(`../src/${path}`, import.meta.url)), "utf8");-}+import { readSrc } from "./helpers/kit.ts";const PAGES = [["images", "features/images/images-page.tsx", "getDiffusionStatus", "unloadDiffusionModel"],@@ -27,7 +23,7 @@ const PAGES = [for (const [name, path, read, unload] of PAGES) {test(`the ${name} page lets only the newest status read write`, () => {- const page = source(path);+ const page = readSrc(path);assert.match(page, /const statusTicket = useRef\(0\);/);assert.match(page,@@ -53,7 +49,7 @@ for (const [name, path, read, unload] of PAGES) {});test(`the ${name} page claims its ticket before awaiting, not after`, () => {- const page = source(path);+ const page = readSrc(path);// Claiming after the await would hand every read the newest ticket and// defeat the whole thing.assert.match(page, /const ticket = \+\+statusTicket\.current;\s*\n\s*try \{/);diff --git a/studio/frontend/tests/memory-estimate-standing-defaults.test.ts b/studio/frontend/tests/memory-estimate-standing-defaults.test.tsindex cbb93cf694d..cd7d88d27ab 100644--- a/studio/frontend/tests/memory-estimate-standing-defaults.test.ts+++ b/studio/frontend/tests/memory-estimate-standing-defaults.test.ts@@ -10,27 +10,16 @@// already uses for logic that lives inside the component.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import path from "node:path";import test from "node:test";-import { fileURLToPath } from "node:url";import { DEFAULT_VRAM_FRACTION } from "../src/hooks/gpu-vram.ts";-const HERE = path.dirname(fileURLToPath(import.meta.url));-const read = (relative: string) =>- readFileSync(path.join(HERE, "..", relative), "utf8");+import { readSrc, readText } from "./helpers/kit.ts";-const CONFIG_PAGE = read(- "src/features/model-picker/components/model-config-page.tsx",-);-const APPLY_CONFIG = read(- "src/features/model-picker/model-config/apply-per-model-config.ts",-);-const NORMALIZE_CONFIG = read(- "src/features/model-picker/model-config/per-model-config.ts",-);-const BUDGET_SETTINGS = read("../backend/utils/vram_budget_settings.py");+const CONFIG_PAGE = readSrc("features/model-picker/components/model-config-page.tsx");+const APPLY_CONFIG = readSrc("features/model-picker/model-config/apply-per-model-config.ts");+const NORMALIZE_CONFIG = readSrc("features/model-picker/model-config/per-model-config.ts");+const BUDGET_SETTINGS = readText("../../backend/utils/vram_budget_settings.py");test("only Manual is persisted per model, so an absent mode is not Auto", () => {// The premise of the whole fix. If this stopped holding, reading the absence asdiff --git a/studio/frontend/tests/memory-shared-core.test.ts b/studio/frontend/tests/memory-shared-core.test.tsindex 0d3c0c3d5b8..876e39646f7 100644--- a/studio/frontend/tests/memory-shared-core.test.ts+++ b/studio/frontend/tests/memory-shared-core.test.ts@@ -36,6 +36,8 @@ import {worseMemoryFit,} from "../src/lib/memory/verdict.ts";+import { readSrc } from "./helpers/kit.ts";+const GIB = 1024 ** 3;// ---------------------------------------------------------------------------@@ -256,14 +258,7 @@ test("an absent or unusable budget falls back rather than refusing everything",test("the badge's call sites read the live fraction", async () => {// The classifier taking a fraction is worthless if nothing passes one. Asserted// on source because these are .tsx call sites the runner cannot render.- const { readFileSync } = await import("node:fs");- const card = readFileSync(- new URL(- "../src/features/hub/catalog/gguf-download-card.tsx",- import.meta.url,- ),- "utf8",- );+ const card = readSrc("features/hub/catalog/gguf-download-card.tsx");assert.match(card,/useVramBudgetFraction\(\)/,@@ -328,14 +323,11 @@ test("every fit-scoring surface reads the saved budget, not just the Hub card",// The Hub download card got the live fraction; the On Device card did not, and// it renders a memory bar (which uses the saved value) directly above a quant// menu sorted by classifyGgufFit (which did not). One card, two budgets.- const { readFileSync } = await import("node:fs");- const read = (rel: string) =>- readFileSync(new URL(rel, import.meta.url), "utf8");for (const rel of [- "../src/features/hub/catalog/gguf-download-card.tsx",- "../src/features/hub/catalog/local-on-device-card.tsx",+ "features/hub/catalog/gguf-download-card.tsx",+ "features/hub/catalog/local-on-device-card.tsx",]) {- const source = read(rel);+ const source = readSrc(rel);assert.match(source,/useVramBudgetFraction\(\)/,@@ -355,12 +347,7 @@ test("the budget read is shared, not one request per mounted card", async () =>// requests overlap in time. A Hub catalog mounts a card per repo progressively// through scrolling and filtering, so a per-card call is a GET per card, and a// 404 per card on a backend predating the route.- const source = await import("node:fs").then(({ readFileSync }) =>- readFileSync(- new URL("../src/hooks/use-vram-budget-fraction.ts", import.meta.url),- "utf8",- ),- );+ const source = readSrc("hooks/use-vram-budget-fraction.ts");assert.match(source,/let cachedFraction/,diff --git a/studio/frontend/tests/message-jsonl-import.test.ts b/studio/frontend/tests/message-jsonl-import.test.tsindex af9adb5aac7..58c2e4d73ad 100644--- a/studio/frontend/tests/message-jsonl-import.test.ts+++ b/studio/frontend/tests/message-jsonl-import.test.ts@@ -2,13 +2,14 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import vm from "node:vm";import { after, before, test } from "node:test";import ts from "typescript";import { type ViteDevServer, createServer } from "vite";import type { ParsedConversation } from "../src/features/chat/types.ts";+import { readSrc } from "./helpers/kit.ts";+let vite: ViteDevServer;let parseImportText: (text: string, filename: string) => ParsedConversation[];let messageToOpenAI: (message: {@@ -18,13 +19,7 @@ let messageToOpenAI: (message: {}) => unknown[];function loadMessageToOpenAI(): typeof messageToOpenAI {- const source = readFileSync(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("features/chat/prompt-storage/prompt-storage-dialog.tsx");const start = source.indexOf("type OAIContentPart =");const end = source.indexOf("// ShareGPT training JSONL", start);assert.notEqual(start, -1, "message serializer start marker must exist");diff --git a/studio/frontend/tests/microphone-permission-reset.test.ts b/studio/frontend/tests/microphone-permission-reset.test.tsindex 6dd84fd0e71..a75a37172b1 100644--- a/studio/frontend/tests/microphone-permission-reset.test.ts+++ b/studio/frontend/tests/microphone-permission-reset.test.ts@@ -13,6 +13,8 @@ import { register } from "node:module";import test from "node:test";import { fileURLToPath } from "node:url";+import { readSrc, readText } from "./helpers/kit.ts";+register("./helpers/tauri-core-resolver.mjs", import.meta.url);// A file:// URL, not a native path. `import()` takes a URL or a relative specifier, and@@ -24,25 +26,11 @@ const MODULE = new URL(import.meta.url,).href;-const VOICE_TAB = readFileSync(- fileURLToPath(new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url)),- "utf8",-);--const ADAPTER = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/adapters/studio-web-speech-dictation-adapter.ts",- import.meta.url,- ),- ),- "utf8",-);--const MAIN_RS = readFileSync(- fileURLToPath(new URL("../../src-tauri/src/main.rs", import.meta.url)),- "utf8",-);+const VOICE_TAB = readSrc("features/settings/tabs/voice-tab.tsx");++const ADAPTER = readSrc("features/chat/adapters/studio-web-speech-dictation-adapter.ts");++const MAIN_RS = readText("../../src-tauri/src/main.rs");type StubControl = { calls: { command: string }[]; mode: "ok" | "rejects" };@@ -134,10 +122,7 @@ test("the blocked toast only promises another prompt on the desktop", () => {});test("the browser message still points at the page permission", () => {- const en = readFileSync(- fileURLToPath(new URL("../src/i18n/locales/en.ts", import.meta.url)),- "utf8",- );+ const en = readSrc("i18n/locales/en.ts");const blocked = en.match(/micAccessBlocked:\s*\n?\s*"([^"]+)"/);assert.ok(blocked, "micAccessBlocked is missing");assert.match(blocked[1], /for this Unsloth page/);diff --git a/studio/frontend/tests/mirrored-settings-write-authority.test.ts b/studio/frontend/tests/mirrored-settings-write-authority.test.tsindex dfec781a973..d01d8b270f8 100644--- a/studio/frontend/tests/mirrored-settings-write-authority.test.ts+++ b/studio/frontend/tests/mirrored-settings-write-authority.test.ts@@ -12,15 +12,12 @@// sits in both graphs), so these pin the source the way the sibling store tests do.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-function read(path: string): string {- return readFileSync(new URL(path, import.meta.url), "utf8");-}+import { readText } from "./helpers/kit.ts";-const store = read("../src/features/chat/stores/chat-runtime-store.ts");-const storage = read("../src/features/chat/utils/chat-settings-storage.ts");+const store = readText("../src/features/chat/stores/chat-runtime-store.ts");+const storage = readText("../src/features/chat/utils/chat-settings-storage.ts");function slice(source: string, from: string, to: string): string {const start = source.indexOf(from);diff --git a/studio/frontend/tests/model-config-run-selection.test.ts b/studio/frontend/tests/model-config-run-selection.test.tsindex e1f1f210432..747a80d4a3c 100644--- a/studio/frontend/tests/model-config-run-selection.test.ts+++ b/studio/frontend/tests/model-config-run-selection.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import ts from "typescript";@@ -14,6 +13,7 @@ import type {} from "../src/features/model-picker/components/model-selector/types.ts";import {installLocalStorageFake,+ readText,registerBundlerResolver,} from "./helpers/kit.ts";@@ -29,7 +29,7 @@ const { DEFAULT_PER_MODEL_CONFIG } = await import(function readSource(relativePath: string): ts.SourceFile {return ts.createSourceFile(relativePath,- readFileSync(new URL(relativePath, import.meta.url), "utf8"),+ readText(relativePath),ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX,diff --git a/studio/frontend/tests/model-disclaimer-preference.test.ts b/studio/frontend/tests/model-disclaimer-preference.test.tsindex 48f8357f790..1af691bc43f 100644--- a/studio/frontend/tests/model-disclaimer-preference.test.ts+++ b/studio/frontend/tests/model-disclaimer-preference.test.ts@@ -2,11 +2,10 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import { register } from "node:module";import test from "node:test";-import { installLocalStorageFake } from "./helpers/kit.ts";+import { installLocalStorageFake, readSrcAsync } from "./helpers/kit.ts";register("./helpers/settings-api-resolver.mjs", import.meta.url);const { store: localStorage } = installLocalStorageFake();@@ -85,12 +84,8 @@ test("the model disclaimer is hidden by default", () => {});test("a saved payload without the model disclaimer key defaults to hidden", async () => {- const source = await readFile(- new URL(- "../src/features/chat/stores/chat-preferences-store.ts",- import.meta.url,- ),- "utf8",+ const source = await readSrcAsync(+ "features/chat/stores/chat-preferences-store.ts",);assert.match(source, MISSING_DISCLAIMER_DEFAULT_PATTERN);});diff --git a/studio/frontend/tests/monitor-frame-ownership.test.ts b/studio/frontend/tests/monitor-frame-ownership.test.tsindex 29f7521a395..641a5cced3a 100644--- a/studio/frontend/tests/monitor-frame-ownership.test.ts+++ b/studio/frontend/tests/monitor-frame-ownership.test.ts@@ -12,34 +12,20 @@// source, since the node suite has no DOM to mount two panels into.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import {type MonitorFrame,useMonitorFrameStore,} from "../src/features/settings/stores/monitor-frame-store.ts";-const PANEL_SOURCE = readFileSync(- fileURLToPath(- new URL("../src/components/floating-monitor.tsx", import.meta.url),- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";-const ROOT_SOURCE = readFileSync(- fileURLToPath(new URL("../src/app/routes/__root.tsx", import.meta.url)),- "utf8",-);-const SETTINGS_MOUNT_SOURCE = readFileSync(- fileURLToPath(- new URL(- "../src/features/settings/settings-dialog-mount.tsx",- import.meta.url,- ),- ),- "utf8",+const PANEL_SOURCE = readSrc("components/floating-monitor.tsx");++const ROOT_SOURCE = readSrc("app/routes/__root.tsx");+const SETTINGS_MOUNT_SOURCE = readSrc(+ "features/settings/settings-dialog-mount.tsx",);/** The Live monitor where it opens by default: bottom-right, w-64, inset-4. */@@ -192,15 +178,7 @@ test("dropping one publisher leaves the other's box intact", () => {// A composer that is hidden measures 0x0, and publishing that would pull the// union out to the top-left corner and pin the stack there.test("the publish hook drops an unmeasurable box rather than publishing it", () => {- const HOOK = readFileSync(- fileURLToPath(- new URL(- "../src/features/settings/hooks/use-published-frame.ts",- import.meta.url,- ),- ),- "utf8",- );+ const HOOK = readSrc("features/settings/hooks/use-published-frame.ts");assert.match(HOOK, /box\.width === 0 && box\.height === 0/);assert.match(HOOK, /observer\?\.disconnect\(\)/, "and it must unsubscribe");assert.match(@@ -211,15 +189,7 @@ test("the publish hook drops an unmeasurable box rather than publishing it", ()});test("closed lazy settings surfaces cannot leave load failures on screen", () => {- const mount = readFileSync(- fileURLToPath(- new URL(- "../src/features/settings/settings-dialog-mount.tsx",- import.meta.url,- ),- ),- "utf8",- );+ const mount = readSrc("features/settings/settings-dialog-mount.tsx");// Keep rejected boundaries mounted for a later retry, but only show their errors while the user is// still asking for that surface. A slow rejected chunk must not outlive a quick Open -> Close.for (const [open, testId] of [diff --git a/studio/frontend/tests/more-menu-separator-gap.test.ts b/studio/frontend/tests/more-menu-separator-gap.test.tsindex f412a5d0429..41a22132531 100644--- a/studio/frontend/tests/more-menu-separator-gap.test.ts+++ b/studio/frontend/tests/more-menu-separator-gap.test.ts@@ -2,9 +2,10 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readSrcAsync } from "./helpers/kit.ts";+// The More flyout ends with a rule and the Customize sidebar row. The rule's// vertical margin has to equal the menu's own padding, or the gap above that// last row reads as bigger than the one below it.@@ -17,10 +18,7 @@ function spacing(classes: string, prefix: string): number {}test("the More flyout's rule sits as far from its rows as the menu's own edge", async () => {- const source = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("components/app-sidebar.tsx");const menu =/<DropdownMenuContent\s+side="right"\s+align="start"\s+sideOffset=\{6\}\s+className="([^"]*)"/.exec(diff --git a/studio/frontend/tests/native-drop-paths.test.ts b/studio/frontend/tests/native-drop-paths.test.tsindex 51383087d4e..9f69899779a 100644--- a/studio/frontend/tests/native-drop-paths.test.ts+++ b/studio/frontend/tests/native-drop-paths.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -56,7 +55,7 @@ import {isAudioOnly3gpBytes,isVideoFile,} from "../src/lib/video-utils.ts";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, readText, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -64,6 +63,13 @@ const { useNativeIntentStore } = await import("../src/features/native-intents/store.ts");+const THREAD = readSrc("components/assistant-ui/thread.tsx");+const ATTACHMENT_CONTENT = readSrc("features/chat/attachment-content.ts");+const RUNTIME_PROVIDER = readSrc("features/chat/runtime-provider.tsx");+const SHARED_COMPOSER = readSrc("features/chat/shared-composer.tsx");+const TEXT_ATTACHMENT_ACCEPT_2 = readSrc("features/chat/text-attachment-accept.ts");+const REFERENCE_PICKER = readSrc("features/video/reference-picker.tsx");+const BACKEND_UPLOAD_EXTS_RE = /UPLOAD_EXTS\s*=\s*\{([^}]+)\}/s;const RUST_ATTACHMENT_EXTS_RE = /ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;const RUST_OPEN_DOCUMENT_ATTACHMENT_EXTS_RE =@@ -150,40 +156,20 @@ test("OpenDocument picker types are accepted by native drops", () => {assert.ok(SUPPORTED_DROP_HINT.includes(extension));}- const providerSource = readFileSync(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",- );- assert.match(providerSource, OPEN_DOCUMENT_ADAPTER_ACCEPT_RE);+ assert.match(RUNTIME_PROVIDER, OPEN_DOCUMENT_ADAPTER_ACCEPT_RE);- const nativeDropSource = readFileSync(- new URL(- "../src/features/native-intents/use-native-drop.ts",- import.meta.url,- ),- "utf8",- );+ const nativeDropSource = readSrc("features/native-intents/use-native-drop.ts");assert.match(nativeDropSource, OPEN_DOCUMENT_DROP_TO_COMPOSER_RE);assert.match(nativeDropSource, OPEN_DOCUMENT_REGISTRATION_CLASS_RE);assert.match(nativeDropSource, OPEN_DOCUMENT_IMAGE_REGISTRATION_RE);assert.match(nativeDropSource, OPEN_DOCUMENT_BACKEND_GATE_RE);- const chatPageSource = readFileSync(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );+ const chatPageSource = readSrc("features/chat/chat-page.tsx");assert.match(chatPageSource, OPEN_DOCUMENT_CHAT_QUEUE_RE);- const threadSource = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );- assert.match(threadSource, OPEN_DOCUMENT_DRAIN_RE);+ assert.match(THREAD, OPEN_DOCUMENT_DRAIN_RE);- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),- "utf8",- );+ const rustSource = readText("../../src-tauri/src/native_path_policy.rs");const rust = [...(rustSource.match(RUST_OPEN_DOCUMENT_ATTACHMENT_EXTS_RE)?.[1]@@ -287,14 +273,8 @@ test("registering image drops hold the gate before the queue can", () => {test("frontend, backend, and Rust accept the same document extensions", () => {const frontend = RAG_UPLOAD_ACCEPT.split(",").sort();- const backendSource = readFileSync(- new URL("../../backend/core/rag/config.py", import.meta.url),- "utf8",- );- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),- "utf8",- );+ const backendSource = readText("../../backend/core/rag/config.py");+ const rustSource = readText("../../src-tauri/src/native_path_policy.rs");const backend = [...(backendSource.match(BACKEND_UPLOAD_EXTS_RE)?.[1]@@ -318,10 +298,7 @@ test("frontend and Rust accept the same chat image extensions", () => {const frontend = CHAT_IMAGE_DROP_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase()).sort();- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),- "utf8",- );+ const rustSource = readText("../../src-tauri/src/native_path_policy.rs");const rust = [...(rustSource.match(RUST_IMAGE_ATTACHMENT_EXTS_RE)?.[1]@@ -337,21 +314,14 @@ test("frontend and Rust accept the same chat image extensions", () => {// composer routes by MIME, so a type VisionImageAdapter does not claim lands on// the wrong adapter or nowhere.test("every MIME type Rust stamps is one the vision adapter claims", () => {- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_intents.rs", import.meta.url),- "utf8",- );+ const rustSource = readText("../../src-tauri/src/native_intents.rs");const stamped = [...new Set([...rustSource.matchAll(RUST_MIME_ARM_RE)].map((match) => match[1]),),].sort();- const providerSource = readFileSync(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",- );- const accepted = providerSource+ const accepted = RUNTIME_PROVIDER.match(VISION_ADAPTER_ACCEPT_RE)?.[1].split(",").map((type) => type.trim())@@ -367,10 +337,7 @@ test("every MIME type Rust stamps is one the vision adapter claims", () => {// The join between the two tests above: without it an extension can reach both// allow-lists with no MIME arm, and the reader refuses it after the drop.test("every accepted image extension has a Rust MIME arm", () => {- const policySource = readFileSync(- new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),- "utf8",- );+ const policySource = readText("../../src-tauri/src/native_path_policy.rs");const accepted = [...(policySource.match(RUST_IMAGE_ATTACHMENT_EXTS_RE)?.[1]@@ -379,10 +346,7 @@ test("every accepted image extension has a Rust MIME arm", () => {.map((match) => match[1]).sort();- const intentsSource = readFileSync(- new URL("../../src-tauri/src/native_intents.rs", import.meta.url),- "utf8",- );+ const intentsSource = readText("../../src-tauri/src/native_intents.rs");const body = intentsSource.match(MIME_MATCH_BODY_RE)?.[1];assert.ok(body, "attachment_mime_type match block not found");const mapped = [...body.matchAll(MIME_ARM_EXTENSION_RE)]@@ -397,11 +361,7 @@ test("every accepted image extension has a Rust MIME arm", () => {// The one constant drop-paths.ts names in its own "keep in sync" comment.test("the drop image list matches the composer's file picker", () => {- const composerSource = readFileSync(- new URL("../src/features/chat/shared-composer.tsx", import.meta.url),- "utf8",- );- const picker = composerSource+ const picker = SHARED_COMPOSER.match(COMPOSER_IMAGE_ACCEPT_RE)?.[1].split(",").map((type) => type.trim().replace("image/", ""))@@ -596,10 +556,7 @@ test("frontend and Rust accept the same chat video extensions", () => {const frontend = CHAT_VIDEO_DROP_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase()).sort();- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),- "utf8",- );+ const rustSource = readText("../../src-tauri/src/native_path_policy.rs");const rust = [...(rustSource.match(RUST_VIDEO_ATTACHMENT_EXTS_RE)?.[1]@@ -614,10 +571,7 @@ test("frontend and Rust accept the same chat video extensions", () => {// Same seam as the vision and audio checks: a video MIME the adapter does not// claim would be read off disk and then refused by the composer.test("every video MIME Rust stamps is one the video adapter claims", () => {- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_intents.rs", import.meta.url),- "utf8",- );+ const rustSource = readText("../../src-tauri/src/native_intents.rs");const claimed = new Set(VIDEO_ACCEPT.split(",").map((token) => token.trim().toLowerCase()),);@@ -641,10 +595,7 @@ test("frontend and Rust accept the same chat audio extensions", () => {const frontend = CHAT_AUDIO_DROP_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase()).sort();- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),- "utf8",- );+ const rustSource = readText("../../src-tauri/src/native_path_policy.rs");const rust = [...(rustSource.match(RUST_AUDIO_ATTACHMENT_EXTS_RE)?.[1]@@ -659,10 +610,7 @@ test("frontend and Rust accept the same chat audio extensions", () => {// Same seam as the vision check: an audio MIME the adapter does not claim// lands nowhere.test("every audio MIME Rust stamps is one the audio adapter claims", () => {- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_intents.rs", import.meta.url),- "utf8",- );+ const rustSource = readText("../../src-tauri/src/native_intents.rs");const claimed = new Set(AUDIO_ACCEPT.split(",").map((token) => token.trim().toLowerCase()),);@@ -682,10 +630,7 @@ test("every audio MIME Rust stamps is one the audio adapter claims", () => {// bounds the data URL it builds from it. Set to the base64 figure, Rust reads// and encodes 96 MiB (128 MiB over the bridge) for a clip the picker rejects.test("the native video cap is the raw limit the reference picker enforces", () => {- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_intents.rs", import.meta.url),- "utf8",- );+ const rustSource = readText("../../src-tauri/src/native_intents.rs");const rustCap = Number(rustSource.match(/const MAX_NATIVE_VIDEO_BYTES: u64 = ([0-9_]+);/)?.[1]@@ -721,18 +666,11 @@ test("the picker remains able to show extensionless text basenames", () => {".txt,text/plain",);- const threadSource = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );- assert.match(threadSource, PICKER_BASENAME_CALL_RE);+ assert.match(THREAD, PICKER_BASENAME_CALL_RE);});test("frontend and Rust accept the same extensionless text names", () => {- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),- "utf8",- );+ const rustSource = readText("../../src-tauri/src/native_path_policy.rs");const rust = [...(rustSource.match(RUST_TEXT_ATTACHMENT_NAMES_RE)?.[1]@@ -965,10 +903,7 @@ test("the browser text cap matches the native one", () => {// Reading happens while attaching now, so an unbounded .mbox would decode// gigabytes into the webview before the user could send it.assert.equal(MAX_TEXT_ATTACHMENT_BYTES, 20 * 1024 * 1024);- const rust = readFileSync(- new URL("../../src-tauri/src/native_intents.rs", import.meta.url),- "utf8",- );+ const rust = readText("../../src-tauri/src/native_intents.rs");const native = rust.match(/const MAX_NATIVE_TEXT_BYTES: u64 = (\d+) \* 1024 \* 1024;/,)?.[1];@@ -999,13 +934,9 @@ test("a text attachment is read once, not once per stage", async () => {});test("both attachment stages go through the decode-once path", () => {- const provider = readFileSync(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",- );- const adapter = provider.slice(- provider.indexOf("class TextAttachmentAdapter"),- provider.indexOf("class HtmlAttachmentAdapter"),+ const adapter = RUNTIME_PROVIDER.slice(+ RUNTIME_PROVIDER.indexOf("class TextAttachmentAdapter"),+ RUNTIME_PROVIDER.indexOf("class HtmlAttachmentAdapter"),);assert.ok(adapter.length > 0, "text adapter not found");assert.equal(adapter.includes("readTextAttachmentOnce"), true);@@ -1104,13 +1035,9 @@ test("compare mode takes the same audio files the chat composer does", () => {);assert.equal(isAudioAttachmentFile(new File([], "notes.txt", { type: "" })), false);// The compare composer classifies through the shared helper, not file.type.- const composer = readFileSync(- new URL("../src/features/chat/shared-composer.tsx", import.meta.url),- "utf8",- );- assert.equal(/file\.type\.match\(\/\^audio/.test(composer), false);- assert.match(composer, /isAudioAttachmentFile\(file\)/);- assert.match(composer, /accept=\{AUDIO_PICKER_ACCEPT\}/);+ assert.equal(/file\.type\.match\(\/\^audio/.test(SHARED_COMPOSER), false);+ assert.match(SHARED_COMPOSER, /isAudioAttachmentFile\(file\)/);+ assert.match(SHARED_COMPOSER, /accept=\{AUDIO_PICKER_ACCEPT\}/);});test("a declaration past the first pages is not missed", async () => {@@ -1143,14 +1070,7 @@ test("a declaration past the first pages is not missed", async () => {},);// The source carries no byte ceiling on the scan for a cutoff to creep back in.- const source = readFileSync(- new URL(- "../src/features/chat/text-attachment-accept.ts",- import.meta.url,- ),- "utf8",- );- assert.equal(source.includes("DECLARATION_SCAN_BYTES"), false);+ assert.equal(TEXT_ATTACHMENT_ACCEPT_2.includes("DECLARATION_SCAN_BYTES"), false);});test("a header-shaped line in the body is not a declaration", async () => {@@ -1354,10 +1274,7 @@ test("the tracker magic tables agree, and cover ProTracker's second marker", asy// it at 1080 beside M.K., and a 31-sample module puts byte 470 inside a// sample name rather than the order table, so the Soundtracker fallback does// not catch one either and the module was read as UTF-8 text.- const rust = readFileSync(- new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),- "utf8",- );+ const rust = readText("../../src-tauri/src/native_path_policy.rs");const table = rust.match(/const TRACKER_MOD_MAGICS: &\[&\[u8; 4\]\] = &\[([\s\S]*?)\];/,);@@ -1368,11 +1285,7 @@ test("the tracker magic tables agree, and cover ProTracker's second marker", asyassert.ok(rustMagics.includes("!PM!"), "Rust table is missing !PM!");const module = await import("../src/features/chat/text-attachment-accept.ts");- const source = readFileSync(- new URL("../src/features/chat/text-attachment-accept.ts", import.meta.url),- "utf8",- );- const tsTable = source.match(/const TRACKER_MOD_MAGICS = new Set\(\[([\s\S]*?)\]\)/);+ const tsTable = TEXT_ATTACHMENT_ACCEPT_2.match(/const TRACKER_MOD_MAGICS = new Set\(\[([\s\S]*?)\]\)/);assert.ok(tsTable, "TRACKER_MOD_MAGICS not found in text-attachment-accept.ts");const tsMagics = [...tsTable[1]!.matchAll(/"((?:[^"\\]|\\.){1,8})"/g)].map((m) =>m[1]!.replace(/\\0/g, "\0"),@@ -1583,10 +1496,7 @@ test("frontend and Rust accept the same dropped text extensions", () => {const frontend = TEXT_ATTACHMENT_EXTENSIONS.map((ext) => ext.toLowerCase()).filter((ext) => !docs.includes(ext)).sort();- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),- "utf8",- );+ const rustSource = readText("../../src-tauri/src/native_path_policy.rs");const rust = [...(rustSource.match(RUST_TEXT_ATTACHMENT_EXTS_RE)?.[1]@@ -1599,25 +1509,17 @@ test("frontend and Rust accept the same dropped text extensions", () => {});test("the composer adapter reads the shared text accept list", () => {- const src = readFileSync(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",- );assert.match(- src,+ RUNTIME_PROVIDER,/class TextAttachmentAdapter implements AttachmentAdapter \{[\s\S]*?accept = TEXT_ATTACHMENT_ACCEPT;/,);- assert.match(src, /if \(await isBinaryTrackerModule\(file\)\)/);+ assert.match(RUNTIME_PROVIDER, /if \(await isBinaryTrackerModule\(file\)\)/);for (const ext of [".cs", ".php", ".js"]) {assert.ok(TEXT_ATTACHMENT_ACCEPT.includes(ext), ext);}- const attachmentContentSource = readFileSync(- new URL("../src/features/chat/attachment-content.ts", import.meta.url),- "utf8",- );assert.match(- attachmentContentSource,+ ATTACHMENT_CONTENT,/import \{[\s\S]*?TEXT_ATTACHMENT_ACCEPT[\s\S]*?decodeTextAttachmentBytes[\s\S]*?\} from "\.\/text-attachment-accept";/,);});@@ -1724,13 +1626,7 @@ test("a file dialog offers 3GP recordings, and routing still does not", () => {assert.equal(AUDIO_ATTACHMENT_ACCEPT.split(",").includes(".3gp"), false);assert.ok(AUDIO_PICKER_ACCEPT.startsWith(AUDIO_ATTACHMENT_ACCEPT));- const adapter = readFileSync(- new URL(- "../src/features/chat/audio-attachment-adapter.ts",- import.meta.url,- ),- "utf8",- );+ const adapter = readSrc("features/chat/audio-attachment-adapter.ts");assert.match(adapter, /accept = AUDIO_ATTACHMENT_ACCEPT;/);assert.equal(/AUDIO_PICKER_ACCEPT/.test(adapter), false);});@@ -1747,19 +1643,11 @@ test("a 3GP clip picked through the audio dialog is still refused as video", asytest("the composer classifies before an adapter is picked", () => {// A composite matches on name and MIME synchronously, so the restamping has// to happen in the wrapper above it rather than inside an adapter.- const src = readFileSync(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",- );assert.match(- src,+ RUNTIME_PROVIDER,/class PreStreamAwareAttachmentAdapter[\s\S]*?if \(!needsAttachmentTrackInspection\(state\.file\)\)[\s\S]*?await classifiedAttachmentFile\(state\.file\)/,);- const composer = readFileSync(- new URL("../src/features/chat/shared-composer.tsx", import.meta.url),- "utf8",- );- assert.match(composer, /await classifiedAttachmentFiles\(input\)/);+ assert.match(SHARED_COMPOSER, /await classifiedAttachmentFiles\(input\)/);});test("a From line separates messages in an archive, not in one message", async () => {@@ -1978,11 +1866,7 @@ test("the reference picker takes the formats its drop path does", async () => {assert.ok(REFERENCE_PICKER_ACCEPT.video.split(",").includes(ext), ext);}- const picker = readFileSync(- new URL("../src/features/video/reference-picker.tsx", import.meta.url),- "utf8",- );- assert.match(picker, /accept=\{REFERENCE_PICKER_ACCEPT\[kind\]\}/);+ assert.match(REFERENCE_PICKER, /accept=\{REFERENCE_PICKER_ACCEPT\[kind\]\}/);});test("one vCard declaration speaks for its property, not for the file", async () => {@@ -2149,11 +2033,7 @@ test("the audio reference picker reads a 3GP recording's tracks", async () => {"Please choose a video file",);- const picker = readFileSync(- new URL("../src/features/video/reference-picker.tsx", import.meta.url),- "utf8",- );- assert.match(picker, /await classifiedAttachmentFile\(picked\)/);+ assert.match(REFERENCE_PICKER, /await classifiedAttachmentFile\(picked\)/);});test("only a real charset parameter is a charset declaration", async () => {@@ -2244,10 +2124,7 @@ test("a 3GP is inspected however large the surface taking it allows", async () =// Nothing in the predicate turns on size any more, so no surface's limit can// drift past it again.- const source = readFileSync(- new URL("../src/lib/video-utils.ts", import.meta.url),- "utf8",- );+ const source = readSrc("lib/video-utils.ts");assert.match(source,/export function needsAttachmentTrackInspection[^)]*\)[^{]*\{\s*return \/\\\.3gp\$\/i\.test\(file\.name\);\s*\}/,@@ -2320,12 +2197,8 @@ test("a preview finds a declaration that sits past its own slice", async () => {"string",);- const source = readFileSync(- new URL("../src/features/chat/attachment-content.ts", import.meta.url),- "utf8",- );- assert.match(source, /decodeTextAttachmentBytes\(bytes, file\.name, truncated, whole\)/);- assert.match(source, /DECLARES_ITS_CHARSET_RE/);+ assert.match(ATTACHMENT_CONTENT, /decodeTextAttachmentBytes\(bytes, file\.name, truncated, whole\)/);+ assert.match(ATTACHMENT_CONTENT, /DECLARES_ITS_CHARSET_RE/);});test("a 3GP typed as audio by the platform is still inspected", async () => {@@ -2376,11 +2249,7 @@ test("the reference drop zone takes what its dialog offers", async () => {assert.ok(REFERENCE_DROP_ACCEPT.video.split(",").includes(ext), ext);}- const picked = readFileSync(- new URL("../src/features/video/reference-picker.tsx", import.meta.url),- "utf8",- );- assert.match(picked, /accept: REFERENCE_DROP_ACCEPT\[kind\]/);+ assert.match(REFERENCE_PICKER, /accept: REFERENCE_DROP_ACCEPT\[kind\]/);});test("a quoted parameter value resolves its escapes", async () => {@@ -2410,14 +2279,8 @@ test("a quoted parameter value resolves its escapes", async () => {test("the clipboard reader takes what the native side hands it", () => {// Rust reads a pasted clip to MAX_CLIPBOARD_VIDEO_BYTES; refusing it here// threw away a file already read and encoded, and dropped the paste with it.- const source = readFileSync(- new URL("../src/features/chat/utils/clipboard-files.ts", import.meta.url),- "utf8",- );- const rust = readFileSync(- new URL("../../src-tauri/src/native_clipboard.rs", import.meta.url),- "utf8",- );+ const source = readSrc("features/chat/utils/clipboard-files.ts");+ const rust = readText("../../src-tauri/src/native_clipboard.rs");const rustLimit = (name: string): number => {const raw = rust.match(new RegExp(`const ${name}: u64 = ([0-9_]+(?:\\\\s*\\\\*\\\\s*[0-9_]+)*)`),diff --git a/studio/frontend/tests/native-drop-targets.test.ts b/studio/frontend/tests/native-drop-targets.test.tsindex 328cd013d9f..7b8b4b7ed6e 100644--- a/studio/frontend/tests/native-drop-targets.test.ts+++ b/studio/frontend/tests/native-drop-targets.test.ts@@ -2,10 +2,9 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, readText, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -27,6 +26,9 @@ const { nativeDropTargetAt, registerNativeDropTarget } = await import("../src/features/native-intents/native-drop-targets.ts");+const IMAGE_DROPZONE = readSrc("components/image-dropzone.tsx");+const USE_NATIVE_DROP = readSrc("features/native-intents/use-native-drop.ts");+const asElement = (value: FakeElement) => value as unknown as HTMLElement;test("no registered target means the window handler keeps the drop", () => {@@ -143,54 +145,36 @@ for (const ratio of [3, 1.5]) {// The chat-wide handler has to ask before acting, or a drop aimed at a dialog's// own zone lands as a chat attachment behind it.test("the chat drop handler defers to a registered target", async () => {- const source = await readFile(- new URL(- "../src/features/native-intents/use-native-drop.ts",- import.meta.url,- ),- "utf8",- );assert.match(- source,+ USE_NATIVE_DROP,/if \(nativeDropTargetAt\(event\.payload\.position\)\) \{\s*publish\(\{ status: "idle" \}\);\s*return;/,);});test("the shared image picker owns native drops and ignores stale reads", async () => {- const source = await readFile(- new URL("../src/components/image-dropzone.tsx", import.meta.url),- "utf8",- );- assert.match(source, /const nativeDropRef = useNativeDropTarget\(\{/);- assert.match(source, /ref=\{nativeDropRef\}/);- assert.match(source, /registerNativeAttachmentPath\(path\)/);- assert.match(source, /readNativeAttachmentFile\(intent\.path\.token\)/);+ assert.match(IMAGE_DROPZONE, /const nativeDropRef = useNativeDropTarget\(\{/);+ assert.match(IMAGE_DROPZONE, /ref=\{nativeDropRef\}/);+ assert.match(IMAGE_DROPZONE, /registerNativeAttachmentPath\(path\)/);+ assert.match(IMAGE_DROPZONE, /readNativeAttachmentFile\(intent\.path\.token\)/);// A read outliving the picker would land on whoever holds `onChange` now, and// the native policy takes fewer formats than the picker's own image/*.- assert.match(source, /if \(!mounted\.current \|\| claimed !== selection\.current\) return;/);- assert.match(source, /NATIVE_IMAGE_EXTS\.includes\(/);+ assert.match(IMAGE_DROPZONE, /if \(!mounted\.current \|\| claimed !== selection\.current\) return;/);+ assert.match(IMAGE_DROPZONE, /NATIVE_IMAGE_EXTS\.includes\(/);// Index-keyed reference slots keep the picker mounted when one is removed.- assert.match(source, /if \(seen\.current === value\) return;\s*seen\.current = value;\s*selection\.current \+= 1;/);+ assert.match(IMAGE_DROPZONE, /if \(seen\.current === value\) return;\s*seen\.current = value;\s*selection\.current \+= 1;/);});// The picker rejects a format the native side would refuse anyway, so the two// lists have to stay in step or a droppable image starts being turned away.test("the picker's droppable formats match the native path policy", async () => {- const picker = await readFile(- new URL("../src/components/image-dropzone.tsx", import.meta.url),- "utf8",- );- const rust = await readFile(- new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),- "utf8",- );+ const rust = readText("../../src-tauri/src/native_path_policy.rs");const listed = (source: string, pattern: RegExp) =>[...(source.match(pattern)?.[1].matchAll(/"([a-z0-9]+)"/g) ?? [])].map((match) => match[1]).sort();assert.deepEqual(- listed(picker, /NATIVE_IMAGE_EXTS\s*=\s*\[([^\]]+)\]/),+ listed(IMAGE_DROPZONE, /NATIVE_IMAGE_EXTS\s*=\s*\[([^\]]+)\]/),listed(rust, /IMAGE_ATTACHMENT_EXTS:\s*&\[&str\]\s*=\s*&\[([^\]]+)\]/),);});@@ -198,16 +182,9 @@ test("the picker's droppable formats match the native path policy", async () =>// Tauri repeats "over" for every cursor move, and useNativeModelDrop sits in// ChatPage, so an unconditional setState there rerenders the page per event.test("the chat drop overlay only publishes a changed state", async () => {- const source = await readFile(- new URL(- "../src/features/native-intents/use-native-drop.ts",- import.meta.url,- ),- "utf8",- );assert.match(- source,+ USE_NATIVE_DROP,/setDropState\(\(prev\) => \(sameDropState\(prev, next\) \? prev : next\)\)/,);- assert.doesNotMatch(source, /payload\.type !== "drop"\) \{\s*setDropState\(/);+ assert.doesNotMatch(USE_NATIVE_DROP, /payload\.type !== "drop"\) \{\s*setDropState\(/);});diff --git a/studio/frontend/tests/native-training-dataset-drop.test.ts b/studio/frontend/tests/native-training-dataset-drop.test.tsindex 0f45820a2ca..337fea79e6c 100644--- a/studio/frontend/tests/native-training-dataset-drop.test.ts+++ b/studio/frontend/tests/native-training-dataset-drop.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -15,6 +14,8 @@ import {nativePathFilename,} from "../src/features/training/lib/native-dataset-drop.ts";+import { readSrc, readText } from "./helpers/kit.ts";+const BACKEND_DATASET_EXTENSIONS_PATTERN =/LOCAL_UPLOAD_EXTS\s*=\s*\{([^}]+)\}/s;const BACKEND_DOCUMENT_EXTENSIONS_PATTERN =@@ -147,13 +148,7 @@ test("hit testing takes a macOS drop position as-is", () => {});test("native dataset drops track runtime window scale changes", () => {- const source = readFileSync(- new URL(- "../src/features/studio/sections/use-dataset-uploads.ts",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("features/studio/sections/use-dataset-uploads.ts");assert.equal(source.includes("currentWindow.onScaleChanged("), true);assert.equal(source.includes("scaleFactor = payload.scaleFactor"), true);@@ -161,14 +156,10 @@ test("native dataset drops track runtime window scale changes", () => {});test("frontend, backend, and Rust accept the same native dataset extensions", () => {- const backendSource = readFileSync(- new URL("../../backend/hub/services/datasets/local.py", import.meta.url),- "utf8",- );- const rustSource = readFileSync(- new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),- "utf8",+ const backendSource = readText(+ "../../backend/hub/services/datasets/local.py",);+ const rustSource = readText("../../src-tauri/src/native_path_policy.rs");const backend = [...(backendSource.match(BACKEND_DATASET_EXTENSIONS_PATTERN)?.[1]@@ -193,16 +184,9 @@ test("frontend, backend, and Rust accept the same native dataset extensions", ()});test("training document redirects match Data Recipes", () => {- const backendSource = readFileSync(- new URL("../../backend/routes/data_recipe/seed.py", import.meta.url),- "utf8",- );- const recipeSource = readFileSync(- new URL(- "../src/features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsx",- import.meta.url,- ),- "utf8",+ const backendSource = readText("../../backend/routes/data_recipe/seed.py");+ const recipeSource = readSrc(+ "features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsx",);const backend = extractLiteralExtensions(backendSource,diff --git a/studio/frontend/tests/openwebui-import.test.ts b/studio/frontend/tests/openwebui-import.test.tsindex abaf77339a0..7d88c8b1251 100644--- a/studio/frontend/tests/openwebui-import.test.ts+++ b/studio/frontend/tests/openwebui-import.test.ts@@ -28,6 +28,15 @@ function chatRecord(chat: Record<string, unknown>, outer: Record<string, unknownreturn { id: "rec", user_id: "u", title: "t", chat, created_at: 1_700_000_000, ...outer };}+/** One history graph with the branch `currentId` open, the shape most cases use. */+function recordOf(+ messages: Record<string, unknown>[],+ currentId: string | null,+ chat: Record<string, unknown> = {},+) {+ return chatRecord({ ...chat, history: historyOf(messages, currentId) });+}+function historyOf(messages: Record<string, unknown>[], currentId: string | null) {const map: Record<string, unknown> = {};for (const message of messages) map[message.id as string] = message;@@ -35,7 +44,7 @@ function historyOf(messages: Record<string, unknown>[], currentId: string | null}test("detection separates an Open WebUI record from the OpenAI and ShareGPT lines we already import", () => {- assert.equal(isOpenWebUIRecord(chatRecord({ history: historyOf([], null) })), true);+ assert.equal(isOpenWebUIRecord(recordOf([], null)), true);// Legacy bare chat: the record IS the chat blob.assert.equal(isOpenWebUIRecord({@@ -59,18 +68,16 @@ test("detection separates an Open WebUI record from the OpenAI and ShareGPT linetest("the branch the user had open is imported last, so the thread reopens where they left it", () => {// one user turn, three assistant replies; currentId points at the middle one.- const record = chatRecord({- title: "regens",- history: historyOf(- [- { id: "u1", parentId: null, childrenIds: ["a1", "a2", "a3"], role: "user", content: "q", timestamp: 100 },- { id: "a1", parentId: "u1", childrenIds: [], role: "assistant", content: "first", timestamp: 101 },- { id: "a2", parentId: "u1", childrenIds: [], role: "assistant", content: "kept", timestamp: 102 },- { id: "a3", parentId: "u1", childrenIds: [], role: "assistant", content: "third", timestamp: 103 },- ],- "a2",- ),- });+ const record = recordOf(+ [+ { id: "u1", parentId: null, childrenIds: ["a1", "a2", "a3"], role: "user", content: "q", timestamp: 100 },+ { id: "a1", parentId: "u1", childrenIds: [], role: "assistant", content: "first", timestamp: 101 },+ { id: "a2", parentId: "u1", childrenIds: [], role: "assistant", content: "kept", timestamp: 102 },+ { id: "a3", parentId: "u1", childrenIds: [], role: "assistant", content: "third", timestamp: 103 },+ ],+ "a2",+ { title: "regens" },+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -89,40 +96,34 @@ test("the branch the user had open is imported last, so the thread reopens where});test("a parent cycle and a dangling currentId are imported instead of hanging or dropping the chat", () => {- const cycle = chatRecord({- history: historyOf(- [- { id: "a", parentId: "b", childrenIds: ["b"], role: "user", content: "one", timestamp: 1 },- { id: "b", parentId: "a", childrenIds: ["a"], role: "assistant", content: "two", timestamp: 2 },- ],- "b",- ),- });+ const cycle = recordOf(+ [+ { id: "a", parentId: "b", childrenIds: ["b"], role: "user", content: "one", timestamp: 1 },+ { id: "b", parentId: "a", childrenIds: ["a"], role: "assistant", content: "two", timestamp: 2 },+ ],+ "b",+ );const fromCycle = openWebUIRecordToConversation(cycle, "fallback");assert.ok(fromCycle);assert.equal(fromCycle.messages.length, 2);- const dangling = chatRecord({- history: historyOf(- [- { id: "u", parentId: null, childrenIds: ["a"], role: "user", content: "q", timestamp: 1 },- { id: "a", parentId: "u", childrenIds: [], role: "assistant", content: "a", timestamp: 2 },- ],- "does-not-exist",- ),- });+ const dangling = recordOf(+ [+ { id: "u", parentId: null, childrenIds: ["a"], role: "user", content: "q", timestamp: 1 },+ { id: "a", parentId: "u", childrenIds: [], role: "assistant", content: "a", timestamp: 2 },+ ],+ "does-not-exist",+ );const fromDangling = openWebUIRecordToConversation(dangling, "fallback");assert.ok(fromDangling);assert.equal(fromDangling.messages.length, 2);});test("a message whose parent was deleted becomes a root rather than vanishing", () => {- const record = chatRecord({- history: historyOf(- [{ id: "orphan", parentId: "gone", childrenIds: [], role: "assistant", content: "kept", timestamp: 5 }],- "orphan",- ),- });+ const record = recordOf(+ [{ id: "orphan", parentId: "gone", childrenIds: [], role: "assistant", content: "kept", timestamp: 5 }],+ "orphan",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);assert.equal(conversation.messages.length, 1);@@ -130,17 +131,15 @@ test("a message whose parent was deleted becomes a root rather than vanishing",});test("a turn that renders to nothing is dropped and its children relink to the surviving ancestor", () => {- const record = chatRecord({- history: historyOf(- [- { id: "u1", parentId: null, childrenIds: ["err"], role: "user", content: "q", timestamp: 1 },- // A failed turn: Open WebUI keeps the row with empty content and an error blob.- { id: "err", parentId: "u1", childrenIds: ["u2"], role: "assistant", content: "", error: { content: "boom" }, timestamp: 2 },- { id: "u2", parentId: "err", childrenIds: [], role: "user", content: "retry", timestamp: 3 },- ],- "u2",- ),- });+ const record = recordOf(+ [+ { id: "u1", parentId: null, childrenIds: ["err"], role: "user", content: "q", timestamp: 1 },+ // A failed turn: Open WebUI keeps the row with empty content and an error blob.+ { id: "err", parentId: "u1", childrenIds: ["u2"], role: "assistant", content: "", error: { content: "boom" }, timestamp: 2 },+ { id: "u2", parentId: "err", childrenIds: [], role: "user", content: "retry", timestamp: 3 },+ ],+ "u2",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);assert.equal(conversation.messages.length, 2);@@ -152,12 +151,10 @@ test("older assistant turns keep their inlined tool call and reasoning as real p'<details type="reasoning" done="true" duration="7">\n<summary>Thought for 7 seconds</summary>\n> weighing options\n</details>\n' +'<details type="tool_calls" done="true" id="call_1" name="get_weather" arguments="{"city": "Lisbon"}" result="{"c": 21}">\n<summary>Tool Executed</summary>\n</details>\n' +"It is 21 degrees.";- const record = chatRecord({- history: historyOf(- [{ id: "a", parentId: null, childrenIds: [], role: "assistant", content, timestamp: 1 }],- "a",- ),- });+ const record = recordOf(+ [{ id: "a", parentId: null, childrenIds: [], role: "assistant", content, timestamp: 1 }],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -181,12 +178,10 @@ test("a tool result that contains a code fence is still lifted into a tool-call"```json\n{\"rows\": 3}\n```\n" +"</details>\n" +"So there are three rows.";- const record = chatRecord({- history: historyOf(- [{ id: "a", parentId: null, childrenIds: [], role: "assistant", content, timestamp: 1 }],- "a",- ),- });+ const record = recordOf(+ [{ id: "a", parentId: null, childrenIds: [], role: "assistant", content, timestamp: 1 }],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -205,12 +200,10 @@ test("a details block quoted inside a code fence stays text, because the chat is"Look at this:\n\n```html\n" +'<details type="tool_calls" done="true" name="not_a_call">\n<summary>example</summary>\n</details>\n' +"```\n\nThat is the markup.";- const record = chatRecord({- history: historyOf(- [{ id: "a", parentId: null, childrenIds: [], role: "assistant", content, timestamp: 1 }],- "a",- ),- });+ const record = recordOf(+ [{ id: "a", parentId: null, childrenIds: [], role: "assistant", content, timestamp: 1 }],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -220,34 +213,32 @@ test("a details block quoted inside a code fence stays text, because the chat is});test("modern assistant turns rebuild their tool call from the output items, result included", () => {- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- childrenIds: [],- role: "assistant",- content: "Lisbon is sunny.",- timestamp: 1,- output: [- { type: "reasoning", id: "rs_1", summary: [{ type: "output_text", text: "check the tool" }] },- { type: "function_call", call_id: "call_9", name: "web_search", arguments: '{"query":"lisbon"}' },- {- type: "function_call_output",- call_id: "call_9",- output: [- { type: "input_text", text: "sunny, 21C" },- { type: "input_image", image_url: "data:image/png;base64,AAAA" },- ],- },- { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Lisbon is sunny." }] },- ],- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ childrenIds: [],+ role: "assistant",+ content: "Lisbon is sunny.",+ timestamp: 1,+ output: [+ { type: "reasoning", id: "rs_1", summary: [{ type: "output_text", text: "check the tool" }] },+ { type: "function_call", call_id: "call_9", name: "web_search", arguments: '{"query":"lisbon"}' },+ {+ type: "function_call_output",+ call_id: "call_9",+ output: [+ { type: "input_text", text: "sunny, 21C" },+ { type: "input_image", image_url: "data:image/png;base64,AAAA" },+ ],+ },+ { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Lisbon is sunny." }] },+ ],+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -263,33 +254,31 @@ test("modern assistant turns rebuild their tool call from the output items, resu});test("an inline image survives; a document keeps its name but not the text Open WebUI extracted", () => {- const record = chatRecord({- history: historyOf(- [- {- id: "u",- parentId: null,- childrenIds: [],- role: "user",- content: "what is in these?",- timestamp: 1,- files: [- { type: "image", url: "data:image/png;base64,IMG" },- // A file url is a dead Open WebUI route once exported, so the bytes are gone either way.- { type: "image", url: "/api/v1/files/abc" },- {- type: "file",- id: "f1",- name: "spec.pdf",- url: "/api/v1/files/f1",- file: { filename: "spec.pdf", data: { content: "SECRET EXTRACTED TEXT" } },- },- ],- },- ],- "u",- ),- });+ const record = recordOf(+ [+ {+ id: "u",+ parentId: null,+ childrenIds: [],+ role: "user",+ content: "what is in these?",+ timestamp: 1,+ files: [+ { type: "image", url: "data:image/png;base64,IMG" },+ // A file url is a dead Open WebUI route once exported, so the bytes are gone either way.+ { type: "image", url: "/api/v1/files/abc" },+ {+ type: "file",+ id: "f1",+ name: "spec.pdf",+ url: "/api/v1/files/f1",+ file: { filename: "spec.pdf", data: { content: "SECRET EXTRACTED TEXT" } },+ },+ ],+ },+ ],+ "u",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -329,7 +318,7 @@ test("a chat with no history falls back to the flat active branch, and archived});test("an empty chat imports as nothing rather than as a blank thread", () => {- assert.equal(openWebUIRecordToConversation(chatRecord({ history: historyOf([], null) }), "x"), null);+ assert.equal(openWebUIRecordToConversation(recordOf([], null), "x"), null);assert.equal(openWebUIRecordToConversation(chatRecord({}), "x"), null);});@@ -357,49 +346,45 @@ test("epoch seconds on the record and milliseconds on the blob both land in thetest("a tool result stored as a plain string is kept, not flattened to nothing", () => {// The Responses API documents `output` as a string OR a content array, and a// string is what a tool returning text produces.- const record = chatRecord({- history: historyOf(+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ childrenIds: [],+ role: "assistant",+ content: "Lisbon is sunny.",+ timestamp: 1,+ output: [+ { type: "function_call", call_id: "call_1", name: "web_search", arguments: '{"query":"lisbon"}' },+ { type: "function_call_output", call_id: "call_1", output: '{"temp":"21C"}' },+ { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Lisbon is sunny." }] },+ ],+ },+ ],+ "a",+ );++ const conversation = openWebUIRecordToConversation(record, "fallback");+ assert.ok(conversation);+ const toolCall = parts(conversation, 0).find((part) => part.type === "tool-call");+ assert.ok(toolCall);+ assert.equal(toolCall.result, '{"temp":"21C"}');++ // An orphan string output, with no call to attach it to, still shows as text.+ const orphan = openWebUIRecordToConversation(+ recordOf([{id: "a",parentId: null,- childrenIds: [],role: "assistant",- content: "Lisbon is sunny.",timestamp: 1,- output: [- { type: "function_call", call_id: "call_1", name: "web_search", arguments: '{"query":"lisbon"}' },- { type: "function_call_output", call_id: "call_1", output: '{"temp":"21C"}' },- { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Lisbon is sunny." }] },- ],+ output: [{ type: "function_call_output", call_id: "call_gone", output: "21C" }],},],"a",),- });-- const conversation = openWebUIRecordToConversation(record, "fallback");- assert.ok(conversation);- const toolCall = parts(conversation, 0).find((part) => part.type === "tool-call");- assert.ok(toolCall);- assert.equal(toolCall.result, '{"temp":"21C"}');-- // An orphan string output, with no call to attach it to, still shows as text.- const orphan = openWebUIRecordToConversation(- chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- timestamp: 1,- output: [{ type: "function_call_output", call_id: "call_gone", output: "21C" }],- },- ],- "a",- ),- }),"fallback",);assert.ok(orphan);@@ -409,23 +394,21 @@ test("a tool result stored as a plain string is kept, not flattened to nothing",test("a user turn that uploaded a file without typing survives, and keeps its descendants", () => {// Open WebUI sends an empty prompt with a file attached, so real exports// contain turns whose only content is the upload.- const record = chatRecord({- history: historyOf(- [- {- id: "u",- parentId: null,- childrenIds: ["a"],- role: "user",- content: "",- timestamp: 1,- files: [{ type: "file", id: "f1", name: "spec.pdf", url: "/api/v1/files/f1" }],- },- { id: "a", parentId: "u", childrenIds: [], role: "assistant", content: "It is a spec.", timestamp: 2 },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "u",+ parentId: null,+ childrenIds: ["a"],+ role: "user",+ content: "",+ timestamp: 1,+ files: [{ type: "file", id: "f1", name: "spec.pdf", url: "/api/v1/files/f1" }],+ },+ { id: "a", parentId: "u", childrenIds: [], role: "assistant", content: "It is a spec.", timestamp: 2 },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -457,7 +440,7 @@ test("a chat thousands of messages deep converts instead of exhausting the calltimestamp: index + 1,}));const conversation = openWebUIRecordToConversation(- chatRecord({ history: historyOf(messages, "m19999") }),+ recordOf(messages, "m19999"),"fallback",);assert.ok(conversation);@@ -470,15 +453,13 @@ test("details markup a user typed stays text rather than becoming reasoning", ()const typed ='Why does this render oddly?\n<details type="reasoning" done="true">\n<summary>Thought</summary>\n> a plan\n</details>';const conversation = openWebUIRecordToConversation(- chatRecord({- history: historyOf(- [- { id: "u", parentId: null, role: "user", content: typed, timestamp: 1 },- { id: "a", parentId: "u", role: "assistant", content: typed, timestamp: 2 },- ],- "a",- ),- }),+ recordOf(+ [+ { id: "u", parentId: null, role: "user", content: typed, timestamp: 1 },+ { id: "a", parentId: "u", role: "assistant", content: typed, timestamp: 2 },+ ],+ "a",+ ),"fallback",);assert.ok(conversation);@@ -504,12 +485,10 @@ test("a prompt keeps the whitespace it was written with", () => {// Leading indentation is a markdown code block, so trimming rewrites the prompt.const indented = " const x = 1;\n const y = 2;\n";const conversation = openWebUIRecordToConversation(- chatRecord({- history: historyOf(- [{ id: "u", parentId: null, role: "user", content: indented, timestamp: 1 }],- "u",- ),- }),+ recordOf(+ [{ id: "u", parentId: null, role: "user", content: indented, timestamp: 1 }],+ "u",+ ),"fallback",);assert.ok(conversation);@@ -536,22 +515,20 @@ test("a legacy chat with no chat-level date is dated from its earliest message",});test("the assistant answer survives next to a tool result no call in this turn matched", () => {- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- timestamp: 1,- content: "It is sunny in Lisbon.",- // The call itself was recorded on the previous turn.- output: [{ type: "function_call_output", call_id: "call_earlier", output: "sunny, 21C" }],- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ timestamp: 1,+ content: "It is sunny in Lisbon.",+ // The call itself was recorded on the previous turn.+ output: [{ type: "function_call_output", call_id: "call_earlier", output: "sunny, 21C" }],+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -604,24 +581,22 @@ test("a timestamped OpenAI conversation is not mistaken for an Open WebUI chat",});test("a generated image comes over as an image, not as a dropped output item", () => {- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- timestamp: 1,- content: "Here it is.",- output: [- { type: "image_generation_call", id: "img_1", result: "AAAA", output_format: "png" },- { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Here it is." }] },- ],- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ timestamp: 1,+ content: "Here it is.",+ output: [+ { type: "image_generation_call", id: "img_1", result: "AAAA", output_format: "png" },+ { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Here it is." }] },+ ],+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -634,12 +609,10 @@ test("a generated image comes over as an image, not as a dropped output item", (test("a plain details block the model wrote keeps its markup", () => {const answer = "Here:\n<details><summary>Spoiler</summary>secret</details>\nDone.";const conversation = openWebUIRecordToConversation(- chatRecord({- history: historyOf(- [{ id: "a", parentId: null, role: "assistant", content: answer, timestamp: 1 }],- "a",- ),- }),+ recordOf(+ [{ id: "a", parentId: null, role: "assistant", content: answer, timestamp: 1 }],+ "a",+ ),"fallback",);assert.ok(conversation);@@ -666,31 +639,29 @@ test("an empty history map falls back to the flat branch instead of dropping the});test("built-in Responses tools import as tool parts rather than disappearing", () => {- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- timestamp: 1,- content: "Lisbon is sunny.",- output: [- {- type: "web_search_call",- id: "ws_1",- status: "completed",- action: { type: "search", query: "lisbon weather" },- },- { type: "shell_call", call_id: "sh_1", action: { type: "exec", commands: ["ls -la"] } },- { type: "shell_call_output", call_id: "sh_1", output: "total 0" },- { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Lisbon is sunny." }] },- ],- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ timestamp: 1,+ content: "Lisbon is sunny.",+ output: [+ {+ type: "web_search_call",+ id: "ws_1",+ status: "completed",+ action: { type: "search", query: "lisbon weather" },+ },+ { type: "shell_call", call_id: "sh_1", action: { type: "exec", commands: ["ls -la"] } },+ { type: "shell_call_output", call_id: "sh_1", output: "total 0" },+ { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Lisbon is sunny." }] },+ ],+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -739,24 +710,22 @@ test("a multimodal turn keeps its text and image when detection routes it here",test("hex and decimal character references in details attributes are decoded", () => {// Open WebUI decodes these with a full html-entities pass, so an apostrophe// arrives as ' as readily as ' and both have to survive.- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- timestamp: 1,- content:- '<details type="tool_calls" done="true" id="c1" name="ask" ' +- 'arguments="{"q": "it's ok"}" ' +- 'result="{"a": "it's done"}">\n' +- "<summary>Tool executed</summary>\n</details>\nfinished",- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ timestamp: 1,+ content:+ '<details type="tool_calls" done="true" id="c1" name="ask" ' ++ 'arguments="{"q": "it's ok"}" ' ++ 'result="{"a": "it's done"}">\n' ++ "<summary>Tool executed</summary>\n</details>\nfinished",+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -767,22 +736,20 @@ test("hex and decimal character references in details attributes are decoded", (});test("a doubly escaped ampersand survives one decoding pass as literal text", () => {- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- timestamp: 1,- content:- '<details type="tool_calls" done="true" id="c" name="n" ' +- 'arguments="{"raw": "&#39;"}">\n</details>',- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ timestamp: 1,+ content:+ '<details type="tool_calls" done="true" id="c" name="n" ' ++ 'arguments="{"raw": "&#39;"}">\n</details>',+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -795,17 +762,15 @@ test("an out of range timestamp is discarded rather than freezing the clock", ()// Past 2^53 `previousTs + 1` stops advancing, so every later message would// land on one createdAt and the depth-first order would not survive a reload.for (const stamp of [1e16, 1.7e18, Number.MAX_VALUE]) {- const record = chatRecord({- history: historyOf(- [- { id: "u", parentId: null, role: "user", content: "q", timestamp: stamp },- { id: "a1", parentId: "u", role: "assistant", content: "one", timestamp: 0 },- { id: "a2", parentId: "a1", role: "user", content: "two", timestamp: 0 },- { id: "a3", parentId: "a2", role: "assistant", content: "three", timestamp: 0 },- ],- "a3",- ),- });+ const record = recordOf(+ [+ { id: "u", parentId: null, role: "user", content: "q", timestamp: stamp },+ { id: "a1", parentId: "u", role: "assistant", content: "one", timestamp: 0 },+ { id: "a2", parentId: "a1", role: "user", content: "two", timestamp: 0 },+ { id: "a3", parentId: "a2", role: "assistant", content: "three", timestamp: 0 },+ ],+ "a3",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -822,36 +787,32 @@ test("an out of range timestamp is discarded rather than freezing the clock", ()}// A stamp inside the range is still honoured.- const ok = chatRecord({- history: historyOf(- [{ id: "u", parentId: null, role: "user", content: "q", timestamp: 1_700_000_000 }],- "u",- ),- });+ const ok = recordOf(+ [{ id: "u", parentId: null, role: "user", content: "q", timestamp: 1_700_000_000 }],+ "u",+ );const inRange = openWebUIRecordToConversation(ok, "f");assert.ok(inRange);assert.equal(inRange.messages[0].createdAt, 1_700_000_000_000);});test("a generated image given as a url is not wrapped into a broken data url", () => {- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- content: "",- timestamp: 1,- output: [- { type: "image_generation_call", result: "https://example.com/a.png" },- { type: "message", content: [{ type: "output_text", text: "there" }] },- ],- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ content: "",+ timestamp: 1,+ output: [+ { type: "image_generation_call", result: "https://example.com/a.png" },+ { type: "message", content: [{ type: "output_text", text: "there" }] },+ ],+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -861,21 +822,19 @@ test("a generated image given as a url is not wrapped into a broken data url", (});test("malformed tool arguments stay readable instead of posing as an args object", () => {- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- timestamp: 1,- content:- '<details type="tool_calls" done="true" id="c" name="n" arguments="not json">\n</details>',- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ timestamp: 1,+ content:+ '<details type="tool_calls" done="true" id="c" name="n" arguments="not json">\n</details>',+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -886,29 +845,27 @@ test("malformed tool arguments stay readable instead of posing as an args object});test("a tool that returned only images carries no empty result body", () => {- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- content: "",- timestamp: 1,- output: [- { type: "function_call", call_id: "c1", name: "plot", arguments: "{}" },- {- type: "function_call_output",- call_id: "c1",- output: [{ type: "input_image", image_url: "data:image/png;base64,BBB" }],- },- { type: "message", content: [{ type: "output_text", text: "done" }] },- ],- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ content: "",+ timestamp: 1,+ output: [+ { type: "function_call", call_id: "c1", name: "plot", arguments: "{}" },+ {+ type: "function_call_output",+ call_id: "c1",+ output: [{ type: "input_image", image_url: "data:image/png;base64,BBB" }],+ },+ { type: "message", content: [{ type: "output_text", text: "done" }] },+ ],+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -919,33 +876,31 @@ test("a tool that returned only images carries no empty result body", () => {});test("a tool result keeps its text under any of the three part names, and portable image urls", () => {- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- timestamp: 1,- output: [- { type: "function_call", call_id: "c1", name: "lookup", arguments: "{}" },- {- type: "function_call_output",- call_id: "c1",- output: [- { type: "output_text", text: "first" },- { type: "text", text: " second" },- { type: "input_text", text: " third" },- { type: "input_image", image_url: "https://example.com/chart.png" },- { type: "input_image", image_url: "/api/v1/files/local-only" },- ],- },- ],- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ timestamp: 1,+ output: [+ { type: "function_call", call_id: "c1", name: "lookup", arguments: "{}" },+ {+ type: "function_call_output",+ call_id: "c1",+ output: [+ { type: "output_text", text: "first" },+ { type: "text", text: " second" },+ { type: "input_text", text: " third" },+ { type: "input_image", image_url: "https://example.com/chart.png" },+ { type: "input_image", image_url: "/api/v1/files/local-only" },+ ],+ },+ ],+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -963,12 +918,10 @@ test("details markup inside a fence that was never closed stays code", () => {const cut ='Like this:\n```markdown\n<details type="reasoning" done="true">\n<summary>Thought</summary>\n> not mine\n</details>\n';const conversation = openWebUIRecordToConversation(- chatRecord({- history: historyOf(- [{ id: "a", parentId: null, role: "assistant", content: cut, timestamp: 1 }],- "a",- ),- }),+ recordOf(+ [{ id: "a", parentId: null, role: "assistant", content: cut, timestamp: 1 }],+ "a",+ ),"fallback",);assert.ok(conversation);@@ -977,18 +930,16 @@ test("details markup inside a fence that was never closed stays code", () => {});test("a disconnected cycle does not displace the branch the user had open", () => {- const record = chatRecord({- history: historyOf(- [- { id: "u", parentId: null, role: "user", content: "question", timestamp: 1 },- { id: "a", parentId: "u", role: "assistant", content: "the answer", timestamp: 2 },- // A component reachable only through its own cycle.- { id: "c1", parentId: "c2", role: "user", content: "orphaned one", timestamp: 3 },- { id: "c2", parentId: "c1", role: "assistant", content: "orphaned two", timestamp: 4 },- ],- "a",- ),- });+ const record = recordOf(+ [+ { id: "u", parentId: null, role: "user", content: "question", timestamp: 1 },+ { id: "a", parentId: "u", role: "assistant", content: "the answer", timestamp: 2 },+ // A component reachable only through its own cycle.+ { id: "c1", parentId: "c2", role: "user", content: "orphaned one", timestamp: 3 },+ { id: "c2", parentId: "c1", role: "assistant", content: "orphaned two", timestamp: 4 },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -1001,24 +952,22 @@ test("a stray inline fence does not swallow the tool calls after it", () => {// Markdown opens a block fence only at the start of a line. Treating any// unclosed ``` as one made a single mid-sentence backtick run quote the rest// of the message, so every tool call after it was lost as literal markup.- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- timestamp: 1,- content:- "let me compute ```\n" +- '<details type="tool_calls" done="true" id="c1" name="calculator" ' +- 'arguments="{}" result="7">\n<summary>Tool Executed</summary>\n</details>\n' +- "the answer is 7",- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ timestamp: 1,+ content:+ "let me compute ```\n" ++ '<details type="tool_calls" done="true" id="c1" name="calculator" ' ++ 'arguments="{}" result="7">\n<summary>Tool Executed</summary>\n</details>\n' ++ "the answer is 7",+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -1029,25 +978,23 @@ test("a stray inline fence does not swallow the tool calls after it", () => {});test("a reasoning block quoting one backtick run keeps the next tool call", () => {- const record = chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- timestamp: 1,- content:- '<details type="reasoning" done="true">\n<summary>Thought</summary>\n' +- "> the user asked about ```\n</details>\n" +- '<details type="tool_calls" done="true" id="c9" name="real_tool" ' +- 'arguments="{}" result="42">\n<summary>Tool Executed</summary>\n</details>\n' +- "final answer",- },- ],- "a",- ),- });+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ timestamp: 1,+ content:+ '<details type="reasoning" done="true">\n<summary>Thought</summary>\n' ++ "> the user asked about ```\n</details>\n" ++ '<details type="tool_calls" done="true" id="c9" name="real_tool" ' ++ 'arguments="{}" result="42">\n<summary>Tool Executed</summary>\n</details>\n' ++ "final answer",+ },+ ],+ "a",+ );const conversation = openWebUIRecordToConversation(record, "fallback");assert.ok(conversation);@@ -1058,8 +1005,32 @@ test("a reasoning block quoting one backtick run keeps the next tool call", () =});test("reasoning survives an empty summary next to populated content", () => {- const record = chatRecord({- history: historyOf(+ const record = recordOf(+ [+ {+ id: "a",+ parentId: null,+ role: "assistant",+ timestamp: 1,+ output: [+ // Summaries off: the array is present but empty.+ { type: "reasoning", id: "rs_1", summary: [], content: [{ type: "reasoning_text", text: "weighed it up" }] },+ { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Done." }] },+ ],+ },+ ],+ "a",+ );++ const conversation = openWebUIRecordToConversation(record, "fallback");+ assert.ok(conversation);+ assert.deepEqual(+ parts(conversation, 0).filter((part) => part.type === "reasoning"),+ [{ type: "reasoning", text: "weighed it up" }],+ );+ // A populated summary still wins over content.+ const both = openWebUIRecordToConversation(+ recordOf([{id: "a",@@ -1067,40 +1038,12 @@ test("reasoning survives an empty summary next to populated content", () => {role: "assistant",timestamp: 1,output: [- // Summaries off: the array is present but empty.- { type: "reasoning", id: "rs_1", summary: [], content: [{ type: "reasoning_text", text: "weighed it up" }] },- { type: "message", id: "msg_1", role: "assistant", content: [{ type: "output_text", text: "Done." }] },+ { type: "reasoning", summary: [{ type: "summary_text", text: "the summary" }], content: [{ type: "reasoning_text", text: "the raw trace" }] },],},],"a",),- });-- const conversation = openWebUIRecordToConversation(record, "fallback");- assert.ok(conversation);- assert.deepEqual(- parts(conversation, 0).filter((part) => part.type === "reasoning"),- [{ type: "reasoning", text: "weighed it up" }],- );- // A populated summary still wins over content.- const both = openWebUIRecordToConversation(- chatRecord({- history: historyOf(- [- {- id: "a",- parentId: null,- role: "assistant",- timestamp: 1,- output: [- { type: "reasoning", summary: [{ type: "summary_text", text: "the summary" }], content: [{ type: "reasoning_text", text: "the raw trace" }] },- ],- },- ],- "a",- ),- }),"fallback",);assert.ok(both);diff --git a/studio/frontend/tests/overlay-scrollbar-gutter.test.ts b/studio/frontend/tests/overlay-scrollbar-gutter.test.tsindex 53b753092ed..54f74acd3b2 100644--- a/studio/frontend/tests/overlay-scrollbar-gutter.test.ts+++ b/studio/frontend/tests/overlay-scrollbar-gutter.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {@@ -12,6 +11,8 @@ import {watchOverlayScrollbarGutter,} from "../src/lib/overlay-scrollbar.ts";+import { readSrcAsync } from "./helpers/kit.ts";+const PROBE_WIDTH = 60;type Node = {@@ -248,10 +249,7 @@ test("regaining focus re-measures, so a changed scrollbar setting is picked up",});test("right-edge action lists reserve the gutter they publish", async () => {- const css = await readFile(- new URL("../src/index.css", import.meta.url),- "utf8",- );+ const css = await readSrcAsync("index.css");// The utility must read the variable written by the probe.assert.match(css,@@ -260,12 +258,8 @@ test("right-edge action lists reserve the gutter they publish", async () => {),);- const pickers = await readFile(- new URL(- "../src/features/model-picker/components/model-selector/pickers.tsx",- import.meta.url,- ),- "utf8",+ const pickers = await readSrcAsync(+ "features/model-picker/components/model-selector/pickers.tsx",);// Every model row must sit inside the gutter wrapper.assert.match(@@ -273,9 +267,8 @@ test("right-edge action lists reserve the gutter they publish", async () => {/"model-list-scroll[^"]*overflow-y-auto[^"]*"[\s\S]{0,800}"overlay-scrollbar-gutter",/,);- const apiKeysTab = await readFile(- new URL("../src/features/settings/tabs/api-keys-tab.tsx", import.meta.url),- "utf8",+ const apiKeysTab = await readSrcAsync(+ "features/settings/tabs/api-keys-tab.tsx",);// Preserve classic padding and move every API-key row into the gutter.assert.match(@@ -283,12 +276,8 @@ test("right-edge action lists reserve the gutter they publish", async () => {/"hover-scrollbar[^"]*overflow-y-auto[^"]*\bpr-1\b[^"]*"[\s\S]{0,200}<div className="overlay-scrollbar-gutter">[\s\S]{0,300}<ApiKeyRow/,);- const projectSourceDropzone = await readFile(- new URL(- "../src/features/rag/components/project-source-dropzone.tsx",- import.meta.url,- ),- "utf8",+ const projectSourceDropzone = await readSrcAsync(+ "features/rag/components/project-source-dropzone.tsx",);// Keep staged-source remove actions inside the gutter.assert.match(diff --git a/studio/frontend/tests/overlay-shadow-gutter.test.ts b/studio/frontend/tests/overlay-shadow-gutter.test.tsindex d08085ac805..67625b2248e 100644--- a/studio/frontend/tests/overlay-shadow-gutter.test.ts+++ b/studio/frontend/tests/overlay-shadow-gutter.test.ts@@ -11,13 +11,11 @@// placed, so this reads the source: the node suite has no DOM to compute in.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const PROVIDER = readFileSync(- new URL("../src/app/provider.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const PROVIDER = readSrc("app/provider.tsx");/** A `const NAME = <number>;` declaration in the provider. */function constant(name: string): number {diff --git a/studio/frontend/tests/padded-response.test.ts b/studio/frontend/tests/padded-response.test.tsindex b70d2755fea..140e3625029 100644--- a/studio/frontend/tests/padded-response.test.ts+++ b/studio/frontend/tests/padded-response.test.ts@@ -13,15 +13,13 @@*/import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { assertCompletedPaddedBody } from "../src/features/chat/api/padded-response.ts";-const chatApi = readFileSync(- new URL("../src/features/chat/api/chat-api.ts", import.meta.url),- "utf8",-);+import { readSrc, readText } from "./helpers/kit.ts";++const chatApi = readSrc("features/chat/api/chat-api.ts");test("a real payload passes through", () => {assertCompletedPaddedBody({ status: "loaded", model: "org/A" }, "Model load");@@ -63,10 +61,7 @@ test("only the two padded routes require a payload", () => {test("the Python client agrees", () => {// If only one client rejects a truncated reply, one reads success where the other fails.- const cli = readFileSync(- new URL("../../../unsloth_cli/_inference.py", import.meta.url),- "utf8",- );+ const cli = readText("../../../unsloth_cli/_inference.py");assert.ok(cli.includes("def require_completed_padded_body("));// unsloth_cli/tests/test_inference_chat.py asserts it actually raises.assert.ok(cli.includes("if isinstance(body, dict) and body:"));diff --git a/studio/frontend/tests/parallel-tool-call-arguments.test.ts b/studio/frontend/tests/parallel-tool-call-arguments.test.tsindex 2040538792a..32e50f86735 100644--- a/studio/frontend/tests/parallel-tool-call-arguments.test.ts+++ b/studio/frontend/tests/parallel-tool-call-arguments.test.ts@@ -7,9 +7,7 @@// not a change of name: the reported stream calls one tool three times.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import ts from "typescript";@@ -26,6 +24,8 @@ import {resolveToolCallPartId,} from "../src/features/chat/tool-call-id.ts";+import { readSrc } from "./helpers/kit.ts";+test("a slot holding one object is left as one object", () => {assert.deepEqual(splitTopLevelJsonObjects('{"url":"a"}'), {complete: ['{"url":"a"}'],@@ -141,12 +141,7 @@ test("arguments that are not one JSON object fall back rather than replay", () =// tests/pr9057-video-simulation.test.ts does: a re-implementation passes while// the adapter stays broken, which is how this defect survived// tool-call-delta-index.test.ts.-const adapterSource = readFileSync(- fileURLToPath(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- ),- "utf8",-);+const adapterSource = readSrc("features/chat/api/chat-adapter.ts");function liftBetween(what: string, from: string, to: string): string {const start = adapterSource.indexOf(from);diff --git a/studio/frontend/tests/pasted-text-attachment.test.ts b/studio/frontend/tests/pasted-text-attachment.test.tsindex b9327ed037c..7650c504ee6 100644--- a/studio/frontend/tests/pasted-text-attachment.test.ts+++ b/studio/frontend/tests/pasted-text-attachment.test.ts@@ -31,6 +31,8 @@ import {unwrapPastedTextContent,} from "../src/features/chat/utils/pasted-text.ts";+import { readSrcAsync } from "./helpers/kit.ts";+type ClipboardStub = {readonly files: readonly File[];readonly items: readonly { kind: string }[];@@ -715,10 +717,7 @@ test("a keyboard reporting no code falls back to the key", () => {test("the composer reads the chord from the keydown and clears it", async () => {const { readFile } = await import("node:fs/promises");- const thread = await readFile(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );+ const thread = await readSrcAsync("components/assistant-ui/thread.tsx");// A paste event carries no modifiers, so the chord has to come from the// keydown before it, on capture so inputProps keeps its own onKeyDown.assert.match(thread, /onKeyDownCapture=\{notePlainPasteChord\}/);@@ -820,10 +819,7 @@ test("the settings label names the chord the composer accepts", async () => {);}// The tab builds that same binding rather than spelling the chord out.- const tab = await readFile(- new URL("../src/features/settings/tabs/chat-tab.tsx", import.meta.url),- "utf8",- );+ const tab = await readSrcAsync("features/settings/tabs/chat-tab.tsx");assert.match(tab,/code: "KeyV", mod: true, ctrl: false, shift: true, alt: macPlatform/,diff --git a/studio/frontend/tests/per-model-params-hydration.test.ts b/studio/frontend/tests/per-model-params-hydration.test.tsindex 07588d35b31..7906969bcec 100644--- a/studio/frontend/tests/per-model-params-hydration.test.ts+++ b/studio/frontend/tests/per-model-params-hydration.test.ts@@ -11,7 +11,7 @@ import { readFileSync } from "node:fs";import { register } from "node:module";import test from "node:test";-import { installLocalStorageFake } from "./helpers/kit.ts";+import { installLocalStorageFake, readSrc } from "./helpers/kit.ts";const { store: localStorageFake } = installLocalStorageFake();// Skip the legacy import path: it would look for settings this test never wrote.@@ -563,13 +563,7 @@ test("an edit made before hydration is kept by the model's entry", async () => {// A safetensors reload at a smaller sequence length: the load sets the budget// to that context and the memory would replay a larger one over it.test("a remembered budget is capped by a non-GGUF load", () => {- const runtime = readFileSync(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- "utf8",- );+ const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts");// One cap for both sites: the load response and the Qwen3 thinking defaults.// The reported window leads, and the request stands in only for a backend that// sizes nothing -- a self-sizing one is sent the auto-size sentinel. Through the@@ -584,10 +578,7 @@ test("a remembered budget is capped by a non-GGUF load", () => {"the thinking-defaults replay is capped too",);- const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );+ const adapter = readSrc("features/chat/api/chat-adapter.ts");assert.match(adapter,/maxTokensCap: replayMaxTokensCap\(\s*candidate\.kind === "gguf"\s*\? loadedContextFields\(loadResp\)\.loadedContextLength\s*: loadedWindow,\s*\),/,@@ -595,22 +586,13 @@ test("a remembered budget is capped by a non-GGUF load", () => {// Compare loads the same way: a pane with no context pin sends the sentinel, and// capping its budget at 0 would leave the pane asking for no output at all.- const composer = readFileSync(- new URL("../src/features/chat/shared-composer.tsx", import.meta.url),- "utf8",- );+ const composer = readSrc("features/chat/shared-composer.tsx");assert.match(composer,/maxTokensCap: replayMaxTokensCap\(\s*loadedContextFields\(resp\)\.loadedContextLength \?\?\s*\(!resp\.is_gguf && effectiveMaxSeqLength > 0/,);- const status = readFileSync(- new URL(- "../src/features/chat/lib/apply-inference-status-to-store.ts",- import.meta.url,- ),- "utf8",- );+ const status = readSrc("features/chat/lib/apply-inference-status-to-store.ts");// Reported for a safetensors load too, so the cap is not narrowed to GGUF, and// through the same floor the load paths use: hydration must not clamp Max Tokens// below its own slider either.diff --git a/studio/frontend/tests/pinned-models-reorder.test.ts b/studio/frontend/tests/pinned-models-reorder.test.tsindex 1bb2f083c87..b6392d9f660 100644--- a/studio/frontend/tests/pinned-models-reorder.test.ts+++ b/studio/frontend/tests/pinned-models-reorder.test.ts@@ -2,10 +2,14 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-import { installLocalStorageFake, registerBundlerResolver } from "./helpers/kit.ts";+import {+ installLocalStorageFake,+ readSrc,+ readSrcAsync,+ registerBundlerResolver,+} from "./helpers/kit.ts";registerBundlerResolver();@@ -17,6 +21,8 @@ const { pinKey, usePinnedModelsStore } = await import("../src/features/model-picker/components/model-selector/pinned-models.ts");+const MODELS_CATALOG_ROWS = readSrc("features/hub/catalog/models-catalog-rows.tsx");+const STORAGE_KEY = "unsloth_pinned_models";function setPinned(pinned: string[]) {@@ -477,27 +483,14 @@ test("a storage event with no drag in flight just replaces the list", () => {// row menu offers datasets no pin action, so the drag must not offer one either,// or dragging dataset rows persistently reorders the user's model pins.test("the hub's pinned grid never makes a dataset row draggable", async () => {- const lists = await readFile(- new URL(- "../src/features/hub/catalog/models-catalog-lists.tsx",- import.meta.url,- ),- "utf8",- );+ const lists = await readSrcAsync("features/hub/catalog/models-catalog-lists.tsx");assert.match(lists,/const itemPinKey =\s*!isDataset &&\s*item\.row\.repoId &&\s*pinnedSet\.has\(pinKey\(item\.row\.repoId\)\)/,);// The invariant the gate keeps: the row menu withholds pin/unpin for datasets.- const rows = await readFile(- new URL(- "../src/features/hub/catalog/models-catalog-rows.tsx",- import.meta.url,- ),- "utf8",- );assert.match(- rows,+ MODELS_CATALOG_ROWS,/pin=\{\s*isDataset \|\| !deletableRepoId\s*\?\s*undefined/,);});@@ -552,13 +545,7 @@ test("unpinning a repo that was never pinned writes nothing", () => {test("both repo-level deletes clear pins through that one action", async () => {// The picker's partial repo row and the Hub's cache row do the same delete, so they must not// drift into two answers about what a pin outlives.- const pickers = await readFile(- new URL(- "../src/features/model-picker/components/model-selector/pickers.tsx",- import.meta.url,- ),- "utf8",- );+ const pickers = await readSrcAsync("features/model-picker/components/model-selector/pickers.tsx");assert.equal(pickers.split("unpinRepo(c.repo_id);").length - 1,2,@@ -568,15 +555,8 @@ test("both repo-level deletes clear pins through that one action", async () => {!pickers.includes("if (pinnedSet.has(pinKey(c.repo_id))) {"),"and neither clears by toggling the bare repo key",);- const rows = await readFile(- new URL(- "../src/features/hub/catalog/models-catalog-rows.tsx",- import.meta.url,- ),- "utf8",- );assert.ok(- rows.includes(+ MODELS_CATALOG_ROWS.includes("usePinnedModelsStore.getState().unpinRepo(deletableRepoId);",),);diff --git a/studio/frontend/tests/pr9057-video-simulation.test.ts b/studio/frontend/tests/pr9057-video-simulation.test.tsindex 3f9730ccd29..fcc97d0859b 100644--- a/studio/frontend/tests/pr9057-video-simulation.test.ts+++ b/studio/frontend/tests/pr9057-video-simulation.test.ts@@ -10,9 +10,7 @@// own ceiling, and the extractor that turns a stored part back into base64.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import ts from "typescript";@@ -24,14 +22,13 @@ import {} from "../src/lib/video-utils.ts";import { AUDIO_ACCEPT, MAX_AUDIO_SIZE } from "../src/lib/audio-utils.ts";+import { readSrc } from "./helpers/kit.ts";+// chat-adapter.ts drags in the stores, the toast layer and the whole runtime for// one pure extractor, so lift the shipped source instead of importing it -- the// same trick tests/auto-load-target-key.test.ts uses. This still asserts against// the real code: a rename or a rewrite fails the slice below.-const adapterSource = readFileSync(- fileURLToPath(new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url)),- "utf8",-);+const adapterSource = readSrc("features/chat/api/chat-adapter.ts");function lift(name: string, opener: string): string {const start = adapterSource.indexOf(opener);@@ -336,12 +333,7 @@ test("a thread with no video and no user turn returns nothing rather than throwi// E. the context-usage recount must decline a turn carrying a clip// ----------------------------------------------------------------------------const recountSource = readFileSync(- fileURLToPath(- new URL("../src/features/chat/utils/refresh-context-usage.ts", import.meta.url),- ),- "utf8",-);+const recountSource = readSrc("features/chat/utils/refresh-context-usage.ts");test("the recount declines a video turn, as it already declines image and audio", () => {// toOpenAIMessages has no video branch, so a turn carrying a clip would bediff --git a/studio/frontend/tests/progressive-mount-glue.test.ts b/studio/frontend/tests/progressive-mount-glue.test.tsindex c346499ada9..e7b40219d43 100644--- a/studio/frontend/tests/progressive-mount-glue.test.ts+++ b/studio/frontend/tests/progressive-mount-glue.test.ts@@ -6,11 +6,9 @@// chat-autoscroll-frame-budget.test.ts). Each is a real invariant with a real failure behind it.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const read = (path: string): string =>- readFileSync(new URL(path, import.meta.url), "utf8");+import { readText } from "./helpers/kit.ts";/*** Source with comments removed. The "must not appear" assertions run against this: these files@@ -21,12 +19,12 @@ const code = (source: string): string =>source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^[ \t]*\/\/.*$/gm, "");const GLUE = code(- read("../src/components/assistant-ui/progressive-messages.tsx"),+ readText("../src/components/assistant-ui/progressive-messages.tsx"),);const HOOK = code(- read("../src/components/assistant-ui/use-intent-aware-autoscroll.tsx"),+ readText("../src/components/assistant-ui/use-intent-aware-autoscroll.tsx"),);-const THREAD = code(read("../src/components/assistant-ui/thread.tsx"));+const THREAD = code(readText("../src/components/assistant-ui/thread.tsx"));/*** The region of `source` between two markers, with BOTH required. A barediff --git a/studio/frontend/tests/project-attachment-target-adoption.test.ts b/studio/frontend/tests/project-attachment-target-adoption.test.tsindex b0c1e3f4f70..d66d93396d1 100644--- a/studio/frontend/tests/project-attachment-target-adoption.test.ts+++ b/studio/frontend/tests/project-attachment-target-adoption.test.ts@@ -6,11 +6,19 @@// attach path went through ensureThreadId: the choice was dropped and inherited.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { CHAT_PROJECT_ATTACHMENT_TARGET_KEY } from "../src/features/chat/utils/project-attachment-target.ts";+import { readSrc } from "./helpers/kit.ts";++const CHAT_RUNTIME_STORE = readSrc(+ "features/chat/stores/chat-runtime-store.ts",+);+const THREAD_DOCUMENTS_BAR = readSrc(+ "features/rag/components/thread-documents-bar.tsx",+);+const PENDING = "__pending__";type Target = "project" | "chat";@@ -75,58 +83,37 @@ test("clearing with nothing pending changes nothing", () => {// Adoption has to run on both paths that turn a fresh composer into a chat.test("both chat-creating paths adopt the pending choice", () => {- const source = readFileSync(- new URL(- "../src/features/rag/components/thread-documents-bar.tsx",- import.meta.url,- ),- "utf8",- );// Attaching a file first: ensureThreadId materializes the thread.assert.match(- source,+ THREAD_DOCUMENTS_BAR,/initialize\(\)[\s\S]{0,300}?adoptPendingProjectAttachmentTarget\(remoteId, claim\)/,);// Sending a message first: the id arrives as a prop.assert.match(- source,+ THREAD_DOCUMENTS_BAR,/if \(!hadThreadId\) \{[\s\S]{0,200}?adoptPendingProjectAttachmentTarget\(threadId\)/,);});test("the composer clears its pending choice when it goes away", () => {- const source = readFileSync(- new URL(- "../src/features/rag/components/thread-documents-bar.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(source, /clearPendingProjectAttachmentTarget\(\)/);+ assert.match(THREAD_DOCUMENTS_BAR, /clearPendingProjectAttachmentTarget\(\)/);});// Membership is read from the chat's own row, so there is a window where it is// unknown. Attaching in it would file the file by guess.test("attaching is held until the chat's project is known", () => {- const source = readFileSync(- new URL(- "../src/features/rag/components/thread-documents-bar.tsx",- import.meta.url,- ),- "utf8",- );assert.match(- source,+ THREAD_DOCUMENTS_BAR,/const projectUnresolved = threadProjectId === undefined;/,"unresolved has to be distinguishable from no project",);assert.match(- source,+ THREAD_DOCUMENTS_BAR,/uploading \|\| projectUploading \|\| projectUnresolved/,"the attach controls hold",);assert.match(- source,+ THREAD_DOCUMENTS_BAR,/if \(projectUnresolved\) \{\s*return;\s*\}/,"and a desktop drop stays in the store rather than draining",);@@ -135,10 +122,7 @@ test("attaching is held until the chat's project is known", () => {// A send outlives navigation, and hydration and a model load both run before the// project is first resolved.test("the run keeps the project it started in", () => {- const source = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );+ const source = readSrc("features/chat/api/chat-adapter.ts");assert.match(source,// Whichever await comes first: the property is that the read is the run's@@ -205,36 +189,25 @@ test("an abandoned composer cannot consume the next composer's choice", () => {// The counter has to move on both ways the entry changes hands, or a claim// taken before one of them still looks current afterwards.test("both writers of the pending entry move the claim", () => {- const store = readFileSync(- new URL(- "../src/features/chat/stores/chat-runtime-store.ts",- import.meta.url,- ),- "utf8",- );assert.equal(- store.match(/pendingAttachmentTargetClaim \+= 1;/g)?.length,+ CHAT_RUNTIME_STORE.match(/pendingAttachmentTargetClaim \+= 1;/g)?.length,2,"set-pending and clear-pending both bump it",);assert.match(- store,+ CHAT_RUNTIME_STORE,/if \(claim !== undefined && claim !== pendingAttachmentTargetClaim\) \{\s*return state;/,);- const bar = readFileSync(- new URL(- "../src/features/rag/components/thread-documents-bar.tsx",- import.meta.url,- ),- "utf8",- );// Read before initialize(), not after it resolves.assert.match(- bar,+ THREAD_DOCUMENTS_BAR,/const claim = readPendingAttachmentTargetClaim\(\);[\s\S]{0,200}?\.initialize\(\)/,);- assert.match(bar, /adoptPendingProjectAttachmentTarget\(remoteId, claim\)/);+ assert.match(+ THREAD_DOCUMENTS_BAR,+ /adoptPendingProjectAttachmentTarget\(remoteId, claim\)/,+ );});// Sending a normal message in a project composer creates the chat, and the page@@ -242,10 +215,7 @@ test("both writers of the pending entry move the claim", () => {// the choice unmounts without ever seeing the new id, and the Thread's own bar// mounts with the id already set, so neither of the bar's adopt paths runs.test("the project composer's choice survives the swap to a thread", () => {- const page = readFileSync(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );+ const page = readSrc("features/chat/chat-page.tsx");// The swap: this is what unmounts the composer.assert.match(page, /\{pendingNewThreadId \? \(/);// Adopted before it, in the path that learns the id, and only for the choice@@ -264,37 +234,23 @@ test("the project composer's choice survives the swap to a thread", () => {);// The claim the store hands out changes on every pending write, value or not.- const store = readFileSync(- new URL(- "../src/features/chat/stores/chat-runtime-store.ts",- import.meta.url,- ),- "utf8",- );assert.match(- store,+ CHAT_RUNTIME_STORE,/if \(threadId === null\) \{\s*pendingAttachmentTargetClaim \+= 1;/,);// Why the bar cannot cover it: the Thread's bar starts with an id, so the// first-id branch never fires for it.- const bar = readFileSync(- new URL(- "../src/features/rag/components/thread-documents-bar.tsx",- import.meta.url,- ),- "utf8",+ assert.match(+ THREAD_DOCUMENTS_BAR,+ /const hadThreadIdRef = useRef\(threadId !== null\);/,);- assert.match(bar, /const hadThreadIdRef = useRef\(threadId !== null\);/);});// A browser-local preference that a reset leaves behind outlives the reset: new// attachments keep going to the scope the user just asked to forget.test("the attach-target preference is cleared by the preferences reset", () => {- const tab = readFileSync(- new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),- "utf8",- );+ const tab = readSrc("features/settings/tabs/general-tab.tsx");const start = tab.indexOf("const PREFS_KEYS");const keys = tab.slice(start, tab.indexOf("];", start));assert.ok(start >= 0, "PREFS_KEYS moved");diff --git a/studio/frontend/tests/project-chat-run-keepalive.test.ts b/studio/frontend/tests/project-chat-run-keepalive.test.tsindex ee6c182574b..aae81808204 100644--- a/studio/frontend/tests/project-chat-run-keepalive.test.ts+++ b/studio/frontend/tests/project-chat-run-keepalive.test.ts@@ -9,17 +9,12 @@// rather than a replacement.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const page = readFileSync(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",-);-const provider = readFileSync(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const page = readSrc("features/chat/chat-page.tsx");+const provider = readSrc("features/chat/runtime-provider.tsx");/** The source of one component, from its declaration to the next one. */function componentSource(source: string, declaration: string): string {@@ -357,10 +352,7 @@ test("a delayed first send keeps the creation inputs it was sent under", () => {// attachment before handleSend and Unsloth's PDF/DOCX/text adapters extract there, so with// the provider surviving a project switch a document send materializes in whichever project// is on screen by then.- const thread = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );+ const thread = readSrc("components/assistant-ui/thread.tsx");assert.match(thread,/claimThreadCreation\([\s\S]*?\);\s*aui\.composer\(\)\.send\(\);/,@@ -392,10 +384,7 @@ test("a delayed first send keeps the creation inputs it was sent under", () => {// The RUN resolves its project separately from the record write, and takes the run's// instructions, RAG sources and sandbox from it. It reads the same stamp.- const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );+ const adapter = readSrc("features/chat/api/chat-adapter.ts");assert.match(adapter,/const creationClaim = unstable_threadId\s*\? readThreadCreationClaim\(unstable_threadId\)\s*: undefined;\s*const composerProjectIdAtSend = creationClaim\s*\? creationClaim\.projectId/,@@ -403,10 +392,7 @@ test("a delayed first send keeps the creation inputs it was sent under", () => {// ...and the claim has to outlive initialize(), because there is no ordering guarantee// between the two readers. Consuming it on the first read starves the second.assert.doesNotMatch(provider, /releaseThreadCreationClaim/);- const claimModule = readFileSync(- new URL("../src/features/chat/utils/chat-thread-creation-claim.ts", import.meta.url),- "utf8",- );+ const claimModule = readSrc("features/chat/utils/chat-thread-creation-claim.ts");assert.doesNotMatch(claimModule, /export function releaseThreadCreationClaim/);});diff --git a/studio/frontend/tests/project-source-reply-destination.test.ts b/studio/frontend/tests/project-source-reply-destination.test.tsindex c9057370e79..fe0727b467f 100644--- a/studio/frontend/tests/project-source-reply-destination.test.ts+++ b/studio/frontend/tests/project-source-reply-destination.test.ts@@ -12,13 +12,11 @@// the way rag-availability-marker.test.ts does for the same file.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-const src = await readFile(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",-);+import { readSrcAsync } from "./helpers/kit.ts";++const src = await readSrcAsync("components/assistant-ui/thread.tsx");/** The onSelect body of the "Save to project sources" action bar item. */function saveHandler(): string {diff --git a/studio/frontend/tests/project-source-reply-markdown.test.ts b/studio/frontend/tests/project-source-reply-markdown.test.tsindex 4a3e59bc24d..b59fb06590e 100644--- a/studio/frontend/tests/project-source-reply-markdown.test.ts+++ b/studio/frontend/tests/project-source-reply-markdown.test.ts@@ -7,10 +7,11 @@// is only a tool call has no text part at all, so it saved nothing.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import { register } from "node:module";import test from "node:test";+import { readSrcAsync } from "./helpers/kit.ts";+// The module under test imports a sibling without its extension, the way vite// resolves it.register("./bundler-resolver.mjs", import.meta.url);@@ -87,10 +88,7 @@ test("a tool result is normalised the way the whole-chat save normalises it", ()test("the reply action saves through this conversion", async () => {// thread.tsx is 6k lines of TSX that node cannot load, so this reads the// source, the way project-source-reply-destination.test.ts does.- const src = await readFile(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );+ const src = await readSrcAsync("components/assistant-ui/thread.tsx");const marker = src.indexOf("Save to project sources");assert.ok(marker > 0, "the reply action is gone or was renamed");const handler = src.slice(diff --git a/studio/frontend/tests/project-source-save.test.ts b/studio/frontend/tests/project-source-save.test.tsindex fe71790407b..fe34a930839 100644--- a/studio/frontend/tests/project-source-save.test.ts+++ b/studio/frontend/tests/project-source-save.test.ts@@ -2,10 +2,10 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {installLocalStorageFake,+ readSrcAsync,registerStoreStubResolver,} from "./helpers/kit.ts";import { setAuthFetchHandler } from "./helpers/store-stubs/auth.ts";@@ -248,13 +248,7 @@ test("unsubscribing stops the refetch, so an unmounted panel cannot set state",});test("the panel subscribes, and does not resurrect a row it just deleted", async () => {- const src = await readFile(- new URL(- "../src/features/rag/components/project-sources-panel.tsx",- import.meta.url,- ),- "utf8",- );+ const src = await readSrcAsync("features/rag/components/project-sources-panel.tsx");assert.match(src,/subscribeProjectSourcesUpdated\(projectId, \(\) => \{\n\s*void refresh\(\{ quiet: true \}\);\n\s*\}\),/,diff --git a/studio/frontend/tests/prompt-list-reorder.test.ts b/studio/frontend/tests/prompt-list-reorder.test.tsindex 58799a2904b..234c3a4dd91 100644--- a/studio/frontend/tests/prompt-list-reorder.test.ts+++ b/studio/frontend/tests/prompt-list-reorder.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {type RowBox,@@ -11,6 +10,8 @@ import {ownsDrag,} from "../src/features/chat/prompt-storage/reorder.ts";+import { readSrcAsync } from "./helpers/kit.ts";+const GAP = 2;// Lay rows out the way the flex column does, so a reorder can be replayed@@ -184,13 +185,7 @@ test("sub-pixel settling is not worth a transform", () => {// flipShifts is only correct if the component hands it a baseline read at the// reorder, so keep the capture where it belongs.test("the baseline is captured when the reorder is requested", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/sortable-prompt-items.tsx",- import.meta.url,- ),- "utf8",- );+ const source = await readSrcAsync("features/chat/prompt-storage/sortable-prompt-items.tsx");const captures = source.split("prevOffsets.current = measureOffsets();").length - 1;assert.equal(captures, 1, "the FLIP baseline is captured somewhere else too");const [beforeApply] = source.split("const applyOrder");diff --git a/studio/frontend/tests/prompt-storage-mutation-lock.test.ts b/studio/frontend/tests/prompt-storage-mutation-lock.test.tsindex 9461d160a47..63c673f0ff4 100644--- a/studio/frontend/tests/prompt-storage-mutation-lock.test.ts+++ b/studio/frontend/tests/prompt-storage-mutation-lock.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {type LockSet,@@ -13,6 +12,10 @@ import {samePromptDraft,} from "../src/features/chat/prompt-storage/mutation-lock.ts";+import { readSrc } from "./helpers/kit.ts";++const PROMPT_STORAGE_DIALOG = readSrc("features/chat/prompt-storage/prompt-storage-dialog.tsx");+const empty: LockSet = new Set<string>();test("a second caller cannot take a lock that is already held", () => {@@ -53,23 +56,16 @@ test("releasing an id nobody holds is a no-op on the same set", () => {});test("the detail panes do not own a mutation lock", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );// Both panes are mounted with key={entry.id}, so a useState lock inside one// resets on every row switch. That is the defect; keep it from coming back.assert.doesNotMatch(- source,+ PROMPT_STORAGE_DIALOG,/const \[pending, setPending\] = useState/,"a detail pane owns its lock again, which a row switch resets",);for (const prop of ["pending={mutatingIds.has(", "runMutation={runMutation}"]) {assert.equal(- source.split(prop).length - 1,+ PROMPT_STORAGE_DIALOG.split(prop).length - 1,2,`${prop} should reach both PromptDetail and PromptListDetail`,);@@ -82,21 +78,14 @@ test("the detail panes do not own a mutation lock", async () => {// later during render, with no finally left to release it, and the row's Save and// Delete stay disabled for good. The ref is the authority for that reason.test("the lock decides from the ref, not from a scheduled updater", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(source, /const mutatingRef = useRef<ReadonlySet<string>>/);+ assert.match(PROMPT_STORAGE_DIALOG, /const mutatingRef = useRef<ReadonlySet<string>>/);assert.match(- source,+ PROMPT_STORAGE_DIALOG,/const \[held, started\] = acquire\(mutatingRef\.current, id\);/,"the lock is decided from state again, which can be stale",);assert.doesNotMatch(- source,+ PROMPT_STORAGE_DIALOG,/let started = false;/,"the deferred-updater pattern is back",);@@ -135,59 +124,45 @@ test("list drafts compare by items, not by identity", () => {// minted a second id and stored a duplicate, and a rejection was unhandled, so a// failed create looked exactly like a successful one.test("both create paths are guarded and report failure", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );// Above the forms, like the row locks: the forms are conditionally mounted, so// selecting a rail row while a create is out would otherwise hand a reopened// form a fresh false guard and let it mint a second id for the same draft.assert.equal(- source.split("= useCreateGuard();").length - 1,+ PROMPT_STORAGE_DIALOG.split("= useCreateGuard();").length - 1,2,"the create guard is not owned once per kind above the New forms",);- const [beforeForms] = source.split("function NewPromptForm");+ const [beforeForms] = PROMPT_STORAGE_DIALOG.split("function NewPromptForm");assert.doesNotMatch(beforeForms,/const \{ creating, create \} = useCreateGuard\(\);/,"a New form owns its guard again, which a row switch resets",);for (const prop of ["creating={promptCreate.creating}", "creating={listCreate.creating}"]) {- assert.ok(source.includes(prop), `${prop} should reach its New form`);+ assert.ok(PROMPT_STORAGE_DIALOG.includes(prop), `${prop} should reach its New form`);}assert.equal(- source.split("disabled={creating ").length - 1,+ PROMPT_STORAGE_DIALOG.split("disabled={creating ").length - 1,2,"a Save button stays live while its create is in flight",);for (const message of ["Could not create prompt", "Could not create list"]) {- assert.ok(source.includes(message), `a failed create is silent: ${message}`);+ assert.ok(PROMPT_STORAGE_DIALOG.includes(message), `a failed create is silent: ${message}`);}// The ref decides, for the reason the mutation lock's does.- assert.match(source, /if \(creatingRef\.current\) return;/);+ assert.match(PROMPT_STORAGE_DIALOG, /if \(creatingRef\.current\) return;/);});// The draft is what covers the entry the pane still holds, which is the pre-save// copy until the list is refetched. Clearing it first flashes the old text back.test("a save clears its draft only after the refreshed entry is in", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );assert.equal(- source.split("await onRefresh();\n onSaved(submitted);").length - 1,+ PROMPT_STORAGE_DIALOG.split("await onRefresh();\n onSaved(submitted);").length - 1,2,"a save pane drops the draft before the refresh lands",);assert.doesNotMatch(- source,+ PROMPT_STORAGE_DIALOG,/onSaved\(submitted\);\n\s+onRefresh\(\);/,"the unawaited refresh is back",);@@ -197,14 +172,7 @@ test("a save clears its draft only after the refreshed entry is in", async () =>// the deleted row is still in promptEntries reselects it. The pane then renders// an entry the backend no longer has until the refetch lands.test("a delete clears its selection only after the row is gone", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );- const leadIns = source.split("onDeleted(entry.id);").slice(0, -1);+ const leadIns = PROMPT_STORAGE_DIALOG.split("onDeleted(entry.id);").slice(0, -1);assert.equal(leadIns.length, 2, "both detail panes should clear a deleted row");for (const before of leadIns) {assert.ok(@@ -214,7 +182,7 @@ test("a delete clears its selection only after the row is gone", async () => {);}assert.doesNotMatch(- source,+ PROMPT_STORAGE_DIALOG,/onDeleted\(entry\.id\);\n\s+onRefresh\(\);/,"the unawaited refresh is back",);@@ -226,25 +194,18 @@ test("a delete clears its selection only after the row is gone", async () => {// when its text wraps on a narrow dialog. At 320x320 the guess left the body// 57px too tall and Use, Save and Run fell outside the clip.test("the dialog body claims no height it has to guess", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );assert.doesNotMatch(- source,+ PROMPT_STORAGE_DIALOG,/min-h-\[[^\]]*dvh/,"the body floor is measured against the viewport again",);assert.match(- source,+ PROMPT_STORAGE_DIALOG,/flex-1 min-h-0 overflow-y-auto px-4 sm:px-6/,"the body no longer shrinks to whatever the chrome leaves it",);// The row minimums are what actually keeps each pane usable.- assert.match(source, /grid-rows-\[minmax\(132px,30%\)_minmax\(272px,1fr\)\]/);+ assert.match(PROMPT_STORAGE_DIALOG, /grid-rows-\[minmax\(132px,30%\)_minmax\(272px,1fr\)\]/);});// The New form's fields stay editable while its create is out, and Cancel can@@ -252,23 +213,16 @@ test("the dialog body claims no height it has to guess", async () => {// lands discarded text that never reached the server, which is the defect// samePromptDraft already guards on the edit panes.test("a create resets its draft only if it still holds what was sent", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(source, /samePromptDraft\(prev, submitted\) \? emptyPromptDraft\(\) : prev/);- assert.match(source, /sameListDraft\(prev, submitted\) \? emptyListDraft\(\) : prev/);+ assert.match(PROMPT_STORAGE_DIALOG, /samePromptDraft\(prev, submitted\) \? emptyPromptDraft\(\) : prev/);+ assert.match(PROMPT_STORAGE_DIALOG, /sameListDraft\(prev, submitted\) \? emptyListDraft\(\) : prev/);// The created path must not run the Cancel callback, which discards outright.assert.doesNotMatch(- source,+ PROMPT_STORAGE_DIALOG,/onCreated\([^)]*\);\n\s+onClose\(\);/,"the created path closes through Cancel again, which resets unconditionally",);assert.equal(- source.split("onCreated(id, submitted, mounted.current);").length - 1,+ PROMPT_STORAGE_DIALOG.split("onCreated(id, submitted, mounted.current);").length - 1,2,"both create paths should hand the submitted snapshot up",);@@ -286,24 +240,17 @@ test("an empty draft does not match a submitted one", () => {// grow faster than the item count. The backend takes 10000 items in one list, so// the editor has to be able to wait.test("an oversized list waits to be asked before mounting its editor", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(source, /const EDITOR_ROW_LIMIT = \d+;/);- const limit = Number(/const EDITOR_ROW_LIMIT = (\d+);/.exec(source)?.[1]);+ assert.match(PROMPT_STORAGE_DIALOG, /const EDITOR_ROW_LIMIT = \d+;/);+ const limit = Number(/const EDITOR_ROW_LIMIT = (\d+);/.exec(PROMPT_STORAGE_DIALOG)?.[1]);assert.ok(limit > 0 && limit < 500, `${limit} is not a limit that avoids the freeze`);// Latched, not recomputed: Add prompt on a list at the limit would otherwise// take it past and unmount the editor the user is typing in.assert.match(- source,+ PROMPT_STORAGE_DIALOG,/const \[editorMounted, setEditorMounted\] = useState\(\n\s+\(\) => items\.length <= EDITOR_ROW_LIMIT,\n\s+\);/,);assert.doesNotMatch(- source,+ PROMPT_STORAGE_DIALOG,/const editorMounted = \w+ \|\| items\.length <= EDITOR_ROW_LIMIT;/,"the mount decision is recomputed from the live length again",);@@ -312,32 +259,25 @@ test("an oversized list waits to be asked before mounting its editor", async ()"const filtered = items.filter((t) => t.trim());","const runnableItems = items.filter((t) => t.trim());",]) {- assert.ok(source.includes(readsFullItems), `truncated: ${readsFullItems}`);+ assert.ok(PROMPT_STORAGE_DIALOG.includes(readsFullItems), `truncated: ${readsFullItems}`);}});// A create outlives the form that started it, and completion used to clear the// search, move the selection and close whatever New form was open by then.test("a finished create only moves the view its own form still owns", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );assert.equal(- source.split("onCreated(id, submitted, mounted.current);").length - 1,+ PROMPT_STORAGE_DIALOG.split("onCreated(id, submitted, mounted.current);").length - 1,2,"a create path does not say whether its form is still on screen",);assert.equal(- source.split("if (!fromOpenForm) return;").length - 1,+ PROMPT_STORAGE_DIALOG.split("if (!fromOpenForm) return;").length - 1,2,"a completion still navigates after the user left the form",);// The draft still resets on a match, wherever the user went.- const [, afterGuard] = source.split("const selectCreatedPrompt");+ const [, afterGuard] = PROMPT_STORAGE_DIALOG.split("const selectCreatedPrompt");assert.ok(afterGuard.indexOf("setNewPromptDraft(") < afterGuard.indexOf("if (!fromOpenForm) return;"),"the guard skips the draft reset, leaving a saved prompt marked unsaved",@@ -348,21 +288,14 @@ test("a finished create only moves the view its own form still owns", async () =// hidden one too. Correcting the hidden tab's selection against that dropped the// row it had, and clearing the query in an effect left one render to do it in.test("only the visible tab's selection is corrected", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(source, /if \(activeTab === "prompts"\) \{\n\s+if \(filteredPrompts\.length === 0\)/);- assert.match(source, /const selectTab = useCallback\(\(tab: Tab\) => \{/);+ assert.match(PROMPT_STORAGE_DIALOG, /if \(activeTab === "prompts"\) \{\n\s+if \(filteredPrompts\.length === 0\)/);+ assert.match(PROMPT_STORAGE_DIALOG, /const selectTab = useCallback\(\(tab: Tab\) => \{/);assert.doesNotMatch(- source,+ PROMPT_STORAGE_DIALOG,/\}, \[activeTab\]\);/,"the per-tab reset is an effect again, which renders once with the old query",);- assert.doesNotMatch(source, /onClick=\{\(\) => setActiveTab\(tab\)\}/);+ assert.doesNotMatch(PROMPT_STORAGE_DIALOG, /onClick=\{\(\) => setActiveTab\(tab\)\}/);});// main.tsx wraps the app in StrictMode, which replays an effect as setup,@@ -370,20 +303,13 @@ test("only the visible tab's selection is corrected", async () => {// that first cleanup, so every create reported an unmounted form and the New// form never closed on success.test("the New form's mounted flag is set in effect setup", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );assert.equal(- source.split("mounted.current = true;").length - 1,+ PROMPT_STORAGE_DIALOG.split("mounted.current = true;").length - 1,2,"a New form only sets its mounted flag at the ref, which StrictMode clears",);assert.doesNotMatch(- source,+ PROMPT_STORAGE_DIALOG,/useEffect\(\(\) => \(\) => \{ mounted\.current = false; \}, \[\]\);/,"the cleanup-only effect is back",);@@ -409,22 +335,15 @@ test("no id can be crafted to collide across the two kinds", () => {});test("both panes take their lock through lockKey", async () => {- const source = await readFile(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- "utf8",- );- assert.equal(source.split('runMutation(lockKey("prompt", entry.id)').length - 1, 2);- assert.equal(source.split('runMutation(lockKey("list", entry.id)').length - 1, 2);+ assert.equal(PROMPT_STORAGE_DIALOG.split('runMutation(lockKey("prompt", entry.id)').length - 1, 2);+ assert.equal(PROMPT_STORAGE_DIALOG.split('runMutation(lockKey("list", entry.id)').length - 1, 2);assert.doesNotMatch(- source,+ PROMPT_STORAGE_DIALOG,/runMutation\(entry\.id,/,"a raw id reaches the shared lock set again",);assert.doesNotMatch(- source,+ PROMPT_STORAGE_DIALOG,/mutatingIds\.has\(selected(Prompt|List)\.id\)/,"a pane's pending state is read off a raw id again",);diff --git a/studio/frontend/tests/provider-max-output-tokens-guards.test.ts b/studio/frontend/tests/provider-max-output-tokens-guards.test.tsindex c074cde8eda..ca492ecdfc2 100644--- a/studio/frontend/tests/provider-max-output-tokens-guards.test.ts+++ b/studio/frontend/tests/provider-max-output-tokens-guards.test.ts@@ -2,11 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {installLocalStorageFake,+ readSrc,registerBundlerResolver,} from "./helpers/kit.ts";@@ -245,19 +245,13 @@ test("an entry saved by an older install loads without gaining a cap", () => {// applied while the provider is unresolved would lower the value permanently. Source-level// assertions, since neither call site is reachable without a DOM.test("every clamp site waits for a resolved provider", () => {- const settings = readFileSync(- new URL("../src/features/chat/chat-settings-sheet.tsx", import.meta.url),- "utf8",- );+ const settings = readSrc("features/chat/chat-settings-sheet.tsx");assert.match(settings,/function applyPresetParamsWithinCurrentLimits\([\s\S]*?if \(!isExternalModel \|\| activeExternalProvider == null\) return nextParams;/,);- const store = readFileSync(- new URL("../src/features/chat/stores/chat-runtime-store.ts", import.meta.url),- "utf8",- );+ const store = readSrc("features/chat/stores/chat-runtime-store.ts");assert.match(store,/if \(provider\) \{\s*const cap = getExternalMaxOutputTokens\(\s*provider\.providerType/,diff --git a/studio/frontend/tests/provisional-hardware-verdict.test.ts b/studio/frontend/tests/provisional-hardware-verdict.test.tsindex e363f8823e0..0fb0477ebfb 100644--- a/studio/frontend/tests/provisional-hardware-verdict.test.ts+++ b/studio/frontend/tests/provisional-hardware-verdict.test.ts@@ -9,7 +9,11 @@import assert from "node:assert/strict";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import {+ readSrc,+ readSrcAsync,+ registerBundlerResolver,+} from "./helpers/kit.ts";registerBundlerResolver();@@ -17,6 +21,10 @@ const { isDetectionDeferred, isProvisionalVerdict, resolveVerdict, videoNavHint"../src/config/hardware-verdict.ts");+const APP_SIDEBAR = readSrc("components/app-sidebar.tsx");+const ENV = readSrc("config/env.ts");+const USE_HARDWARE_INFO = readSrc("hooks/use-hardware-info.ts");+const GPU_HOST = { chatOnly: false, chatOnlyReason: null, chatOnlyDetail: null };const MAC_DEFAULT = { chatOnly: true, chatOnlyReason: null, chatOnlyDetail: null };@@ -144,17 +152,13 @@ test("an actively detecting reply is not deferred", () => {// wait on every navigation. Asserted on source: env.ts is not importable outside vite.test("the bounded hardware wait is spent at most once per page load", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/config/env.ts", import.meta.url),- "utf8",- );assert.match(- src,+ ENV,/let hardwareWaitSpent = false/,"no once-per-load latch: every navigation can repeat the full wait",);assert.match(- src,+ ENV,/const deadline = spendWait \? Date\.now\(\) \+ HARDWARE_DETECT_WAIT_MS : 0/,"the guard does not zero the deadline, so the wait is not actually skipped",);@@ -165,12 +169,8 @@ test("the bounded hardware wait is spent at most once per page load", async () =// provisional into measured, so it only holds the login form behind the torch import.test("an unauthenticated read never spends the detection window", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/config/env.ts", import.meta.url),- "utf8",- );assert.match(- src,+ ENV,/const spendWait = Boolean\(token\) && !hardwareWaitSpent/,"the wait is not gated on having a token, so /login blocks on hardware detection",);@@ -181,26 +181,22 @@ test("an unauthenticated read never spends the detection window", async () => {// leaving the awaited caller on the local default and redirecting a GPU host to /chat.test("the latch is claimed after the wait, not during it", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/config/env.ts", import.meta.url),- "utf8",- );- const loopStart = src.indexOf("while (res.ok && Date.now() < deadline)");+ const loopStart = ENV.indexOf("while (res.ok && Date.now() < deadline)");// Anchor on the loop's own closing brace, NOT on the latch. Searching for the latch// made this assertion unfalsifiable: String.prototype.search returns the FIRST match,// so moving the latch inside the loop moved loopEnd with it and the slice ended just// short of the claim either way. The test then passed against the exact regression its// header describes.- const loopEnd = src.indexOf("\n }\n", loopStart);+ const loopEnd = ENV.indexOf("\n }\n", loopStart);assert.ok(loopStart > 0 && loopEnd > loopStart, "the wait loop moved");assert.ok(- !src.slice(loopStart, loopEnd).includes("hardwareWaitSpent = true"),+ !ENV.slice(loopStart, loopEnd).includes("hardwareWaitSpent = true"),"the latch is claimed inside the loop, so a concurrent caller skips an unfinished window",);// And it must still be claimed somewhere after the loop, or deleting it outright// would satisfy the check above.assert.match(- src.slice(loopEnd),+ ENV.slice(loopEnd),/if \(spendWait[^)]*\) hardwareWaitSpent = true;/,"the latch is never claimed after the wait, so the window is never spent",);@@ -211,22 +207,18 @@ test("the latch is claimed after the wait, not during it", async () => {// as local, changing model filtering, paths and install commands.test("a provisional forced refresh keeps the server-reported platform", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/config/env.ts", import.meta.url),- "utf8",- );assert.match(- src,+ ENV,/const keepPlatform =\s*\n?\s*data\.device_type === undefined && previous\.fetched/,"no guard: a provisional forced refresh overwrites the authoritative platform",);assert.match(- src,+ ENV,/keepPlatform \? previous\.deviceType : detectLocalPlatform\(\)/,"the guard does not actually keep the stored platform",);assert.match(- src,+ ENV,/fetched: data\.device_type !== undefined \|\| keepPlatform/,"fetched drops to false, so the authoritative platform is not treated as held",);@@ -237,18 +229,13 @@ test("a provisional forced refresh keeps the server-reported platform", async ()// kept the conservative deferred verdict and stayed chat-only until a hard refresh.test("a deferred verdict is recorded so the sidebar can poll out of it", async () => {const { readFile } = await import("node:fs/promises");- const env = await readFile(new URL("../src/config/env.ts", import.meta.url), "utf8");- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );assert.match(- env,+ ENV,/detectionDeferred: isDetectionDeferred\(data\)/,"the store never records that the verdict came from a deferred reply",);assert.match(- sidebar,+ APP_SIDEBAR,/chatOnlyReason !== "mlx_unavailable" && !detectionDeferred/,"the recovery poll still ignores a deferred verdict, so it never recovers",);@@ -259,16 +246,12 @@ test("a deferred verdict is recorded so the sidebar can poll out of it", async (// a stale token spends the whole window and holds /login on a cold boot.test("a rejected token stops the wait instead of polling it out", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/config/env.ts", import.meta.url),- "utf8",- );- const loopStart = src.indexOf("while (res.ok && Date.now() < deadline)");+ const loopStart = ENV.indexOf("while (res.ok && Date.now() < deadline)");// Same brace anchor as above rather than the latch pattern, so the slice cannot move// with the code it is meant to be measuring.- const loopEnd = src.indexOf("\n }\n", loopStart);+ const loopEnd = ENV.indexOf("\n }\n", loopStart);assert.ok(loopStart > 0 && loopEnd > loopStart, "the wait loop moved");- const loop = src.slice(loopStart, loopEnd);+ const loop = ENV.slice(loopStart, loopEnd);assert.ok(/if \(peek\.version === undefined\)\s*\{?[^}]*break;/.test(loop),"the loop keeps polling a reply with no authed-only field, so an expired token " +@@ -286,18 +269,14 @@ test("a rejected token stops the wait instead of polling it out", async () => {// the latch on a refused token leaves the route guard on local defaults until a refresh.test("a rejected token does not consume the once-per-load window", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/config/env.ts", import.meta.url),- "utf8",- );assert.match(- src,+ ENV,/if \(spendWait && !tokenRejected\) hardwareWaitSpent = true;/,"the latch is claimed even when the break came from a rejected token, so the " +"first accepted token in this page load skips its window",);assert.match(- src,+ ENV,/tokenRejected = true;/,"nothing records that the break was caused by a rejected token",);@@ -309,17 +288,13 @@ test("a rejected token does not consume the once-per-load window", async () => {// answered -- which PR #7607's lazy detection can stretch to minutes.test("the store exposes an unknown state, not just chat-only", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/config/env.ts", import.meta.url),- "utf8",- );assert.match(- src,+ ENV,/capabilitiesUnknown: \(\) => boolean;/,"PlatformState has no unknown state, so a caller can only read the guess",);assert.match(- src,+ ENV,/return !state\.fetched && !state\.detectionDeferred;/,"the selector is not derived from `fetched`, the flag that already means " +"'a server-reported verdict is stored'",@@ -331,11 +306,7 @@ test("the store exposes an unknown state, not just chat-only", async () => {// never flips. Calling that unknown would spin Train and Video for the whole session.test("a deferred verdict counts as settled, not as still checking", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/config/env.ts", import.meta.url),- "utf8",- );- const selector = /capabilitiesUnknown: \(\) => \{([\s\S]*?)\n \},/.exec(src);+ const selector = /capabilitiesUnknown: \(\) => \{([\s\S]*?)\n \},/.exec(ENV);assert.ok(selector, "capabilitiesUnknown is no longer a block the deferred case can live in");assert.match(selector[1],@@ -346,12 +317,8 @@ test("a deferred verdict counts as settled, not as still checking", async () =>test("the sidebar gates Train and Video on a measured verdict", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );assert.match(- src,+ APP_SIDEBAR,/const chatOnlyMeasured = chatOnly && !capabilitiesUnknown;/,"the rows still read chatOnly directly, so the UA guess disables them",);@@ -362,13 +329,13 @@ test("the sidebar gates Train and Video on a measured verdict", async () => {// class keeps `disabled: chatOnlyMeasured,` from matching, since "M" is not in it.for (const pattern of [/disabled: chatOnly[,;\s]/, /if \(chatOnly\) return;/]) {assert.ok(- !pattern.test(src),+ !pattern.test(APP_SIDEBAR),`${pattern} still reads the unmeasured verdict`,);}// Both rows opt into the pending state rather than rendering a guessed gray-out.assert.equal(- src.match(/pending: capabilitiesUnknown,/g)?.length,+ APP_SIDEBAR.match(/pending: capabilitiesUnknown,/g)?.length,2,"Train and Video do not both mark themselves pending while the verdict is out",);@@ -378,10 +345,7 @@ test("the sidebar gates Train and Video on a measured verdict", async () => {// pre-measurement guess strands a healthy host there for the rest of the session.test("the route guard waits out an unknown verdict on Train and Video", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/app/routes/__root.tsx", import.meta.url),- "utf8",- );+ const src = await readSrcAsync("app/routes/__root.tsx");const guard = /const SELF_GATED_WHILE_UNKNOWN = \[([^\]]*)\]/.exec(src);assert.ok(guard, "no list of paths that wait the verdict out");for (const path of ["/studio", "/video"]) {@@ -404,10 +368,7 @@ test("the route guard waits out an unknown verdict on Train and Video", async ()// so the page has to say which, rather than fail at load.test("the Video page gates on the backend's own capability answer", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/features/video/video-page.tsx", import.meta.url),- "utf8",- );+ const src = await readSrcAsync("features/video/video-page.tsx");assert.match(src,/hardware\.videoSupported === false/,@@ -478,22 +439,18 @@ test("a chat-only Apple Silicon host keeps Video navigable", () => {// tests above only describe.test("the Video row is disabled exactly when the hint has something to say", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );assert.match(- src,+ APP_SIDEBAR,/const videoDisabledHint = videoNavHint\(chatOnlyMeasured, chatOnlyReason\)/,"the Video hint no longer comes from the shared derivation",);assert.match(- src,+ APP_SIDEBAR,/const videoDisabled = videoDisabledHint !== undefined/,"the Video row's disabled state is no longer derived from its hint",);// The train row keeps `disabled: chatOnlyMeasured`, so match inside the video row only.- const videoRow = src.slice(src.indexOf(" video: {"));+ const videoRow = APP_SIDEBAR.slice(APP_SIDEBAR.indexOf(" video: {"));const videoBody = videoRow.slice(0, videoRow.indexOf("},"));assert.match(videoBody,@@ -506,7 +463,7 @@ test("the Video row is disabled exactly when the hint has something to say", asy/tooltip: videoDisabledHint,/,"the Video row is disabled with no reason shown",);- assert.ok(!/coming soon/.test(src), "the Video row still promises macOS support that has shipped");+ assert.ok(!/coming soon/.test(APP_SIDEBAR), "the Video row still promises macOS support that has shipped");});// The Video gate waits on useHardwareInfo's `loaded`, and a failed probe used to resolve to@@ -514,17 +471,13 @@ test("the Video row is disabled exactly when the hint has something to say", asy// the rest of the session.test("a failed hardware probe is retried, not left unloaded", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/hooks/use-hardware-info.ts", import.meta.url),- "utf8",- );assert.match(- src,+ USE_HARDWARE_INFO,/if \(!cancelled && !hw\.loaded\) retry = setTimeout\(load, RETRY_MS\);/,"nothing re-probes after a failed read",);assert.match(- src,+ USE_HARDWARE_INFO,/if \(retry !== undefined\) clearTimeout\(retry\);/,"the retry outlives the component that scheduled it",);@@ -537,19 +490,15 @@ test("a failed hardware probe is retried, not left unloaded", async () => {// is a permanent "Checking this machine..." rather than a stale value.test("a cache filled between render and subscribe still reaches the component", async () => {const { readFile } = await import("node:fs/promises");- const src = await readFile(- new URL("../src/hooks/use-hardware-info.ts", import.meta.url),- "utf8",- );assert.match(- src,+ USE_HARDWARE_INFO,/if \(cached\) listener\(cached\);\s*\n\s*else load\(\);/,"a component that missed the notify has no path to the cache it skipped loading for",);// A 200 superseded by a later invalidate must not be reported as a failed probe: load()// reads !loaded as failure and drops the page back to its loading state.assert.ok(- !/return cached \?\? DEFAULT;/.test(src),+ !/return cached \?\? DEFAULT;/.test(USE_HARDWARE_INFO),"a superseded but successful read still resolves as an unloaded DEFAULT",);});diff --git a/studio/frontend/tests/qwen-defaults-migration-hydration.test.ts b/studio/frontend/tests/qwen-defaults-migration-hydration.test.tsindex 508e131188a..207461ab5bf 100644--- a/studio/frontend/tests/qwen-defaults-migration-hydration.test.ts+++ b/studio/frontend/tests/qwen-defaults-migration-hydration.test.ts@@ -33,21 +33,61 @@ const LEGACY_SNAPSHOT = {systemVariables: "",fastMode: false,};+/** The global row the legacy snapshot was written beside. */+const LEGACY_GLOBAL = {+ temperature: 0.6,+ topP: 0.95,+ minP: 0.01,+ presencePenalty: 0.0,+ maxTokens: 8192,+};+const BUILTIN_DEFAULT = {+ activePreset: "Default",+ activePresetSource: "builtin-default",+} as const;++const sleep = (ms: number): Promise<void> =>+ new Promise((resolve) => setTimeout(resolve, ms));++/**+ * Stage what the server holds and drop the writes recorded so far. Staged GETs are+ * cleared too unless `keepReads`: a leftover response answers the next hydration.+ */+function seedSettings(+ settings: Record<string, unknown>,+ options: { keepReads?: boolean } = {},+): void {+ if (options.keepReads !== true) settingsHttp.getResponses.length = 0;+ settingsHttp.settings = settings;+ settingsHttp.puts.length = 0;+}++const modelPut = (): Record<string, unknown> | undefined =>+ settingsHttp.puts.find(+ (put) =>+ (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[+ QWEN38+ ] !== undefined,+ );+const hasModelPut = (): boolean => modelPut() !== undefined;++const persistedRow = (): Record<string, unknown> =>+ (+ settingsHttp.settings.inferenceParamsByModel as Record<+ string,+ Record<string, unknown>+ >+ )[QWEN38];test("hydration replaces and persists the stale Qwen3.8 default snapshot", async () => {- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0.0,- maxTokens: 8192,+ seedSettings(+ {+ ...BUILTIN_DEFAULT,+ inferenceParams: LEGACY_GLOBAL,+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },},- inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- };- settingsHttp.puts.length = 0;+ { keepReads: true },+ );useChatRuntimeStore.setState((state) => ({params: {...state.params,@@ -56,8 +96,7 @@ test("hydration replaces and persists the stale Qwen3.8 default snapshot", asyncpresencePenalty: 1.5,},paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,settingsHydrated: false,}));@@ -70,14 +109,8 @@ test("hydration replaces and persists the stale Qwen3.8 default snapshot", asyncassert.equal(hydrated.paramsByModel[QWEN38]?.minP, 0);assert.equal(hydrated.paramsByModel[QWEN38]?.presencePenalty, 1.5);- await new Promise((resolve) => setTimeout(resolve, 600));- const migrationPut = settingsHttp.puts.find(- (put) =>- (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[- QWEN38- ] !== undefined,- );- assert.deepEqual(migrationPut, {+ await sleep(600);+ assert.deepEqual(modelPut(), {inferenceParamsByModel: {[QWEN38]: { minP: 0, presencePenalty: 1.5 },},@@ -85,25 +118,15 @@ test("hydration replaces and persists the stale Qwen3.8 default snapshot", async});test("active-model adoption retries a migration deferred during hydration", async () => {- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0,- maxTokens: 8192,- },+ seedSettings({+ ...BUILTIN_DEFAULT,+ inferenceParams: LEGACY_GLOBAL,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- };- settingsHttp.puts.length = 0;+ });useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: "" },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,reasoningAlwaysOn: false,reasoningEnabled: true,settingsHydrated: false,@@ -126,7 +149,7 @@ test("active-model adoption retries a migration deferred during hydration", asyn},{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);const migrated = useChatRuntimeStore.getState();assert.equal(migrated.paramsByModel[QWEN38]?.minP, 0);@@ -135,37 +158,19 @@ test("active-model adoption retries a migration deferred during hydration", asynsettingsHttp.puts.some((put) => put.inferenceParams !== undefined),false,);- assert.equal(- settingsHttp.puts.some(- (put) =>- (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[- QWEN38- ] !== undefined,- ),- true,- );+ assert.equal(hasModelPut(), true);});test("hydration upgrades a global-only non-thinking installation", async () => {- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ seedSettings({+ ...BUILTIN_DEFAULT,reasoningEnabled: false,- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0.0,- maxTokens: 8192,- },- };- settingsHttp.puts.length = 0;+ inferenceParams: LEGACY_GLOBAL,+ });useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: QWEN38 },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningEnabled: true,settingsHydrated: false,@@ -197,15 +202,8 @@ test("a confirming read preserves a newer edit from another tab", async () => {presencePenalty: 0.4,};const legacySettings = {- activePreset: "Default",- activePresetSource: "builtin-default",- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0.0,- maxTokens: 8192,- },+ ...BUILTIN_DEFAULT,+ inferenceParams: LEGACY_GLOBAL,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },};const newerSettings = {@@ -218,8 +216,7 @@ test("a confirming read preserves a newer edit from another tab", async () => {useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: QWEN38 },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,settingsHydrated: false,}));@@ -230,21 +227,12 @@ test("a confirming read preserves a newer edit from another tab", async () => {useChatRuntimeStore.getState().paramsByModel[QWEN38]?.presencePenalty,0.4,);- assert.equal(- settingsHttp.puts.some(- (put) =>- (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[- QWEN38- ] !== undefined,- ),- false,- );+ assert.equal(hasModelPut(), false);});test("atomic migration persistence rejects an edit after confirmation", async () => {const legacySettings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },};const newerSettings = {@@ -262,8 +250,7 @@ test("atomic migration persistence rejects an edit after confirmation", async ()useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: QWEN38 },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,settingsHydrated: false,}));@@ -279,8 +266,7 @@ test("atomic migration persistence rejects an edit after confirmation", async ()test("a confirming read uses the latest reasoning mode", async () => {const thinkingSettings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,reasoningEnabled: true,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },};@@ -294,8 +280,7 @@ test("a confirming read uses the latest reasoning mode", async () => {useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: QWEN38 },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,reasoningAlwaysOn: false,reasoningEnabled: true,settingsHydrated: false,@@ -308,12 +293,7 @@ test("a confirming read uses the latest reasoning mode", async () => {assert.equal(hydrated.params.temperature, 0.7);assert.equal(hydrated.params.topP, 0.8);assert.deepEqual(- settingsHttp.puts.find(- (put) =>- (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[- QWEN38- ] !== undefined,- ),+ modelPut(),{inferenceParamsByModel: {[QWEN38]: {@@ -328,20 +308,11 @@ test("a confirming read uses the latest reasoning mode", async () => {});test("returning from a custom preset retries the guarded migration", async () => {- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0.0,- maxTokens: 8192,- },+ seedSettings({+ ...BUILTIN_DEFAULT,+ inferenceParams: LEGACY_GLOBAL,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- };- settingsHttp.puts.length = 0;+ });useChatRuntimeStore.setState((state) => ({params: {...state.params,@@ -360,21 +331,13 @@ test("returning from a custom preset retries the guarded migration", async () =>useChatRuntimeStore.getState().setActivePreset("Default");useChatRuntimeStore.getState().setActivePresetSource("builtin-default");- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);const state = useChatRuntimeStore.getState();assert.equal(state.params.minP, 0);assert.equal(state.params.presencePenalty, 1.5);assert.equal(state.paramsByModel[QWEN38]?.presencePenalty, 1.5);- assert.equal(- settingsHttp.puts.some(- (put) =>- (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[- QWEN38- ] !== undefined,- ),- true,- );+ assert.equal(hasModelPut(), true);});test("restoring the final modified field retries after the parameter edit", async () => {@@ -382,13 +345,10 @@ test("restoring the final modified field retries after the parameter edit", asyn...LEGACY_SNAPSHOT,presencePenalty: 0.4,};- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ seedSettings({+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- };- settingsHttp.puts.length = 0;+ });useChatRuntimeStore.setState((state) => ({params: {...state.params,@@ -408,27 +368,18 @@ test("restoring the final modified field retries after the parameter edit", asyn...useChatRuntimeStore.getState().params,presencePenalty: 0,});- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);const state = useChatRuntimeStore.getState();assert.equal(state.params.minP, 0);assert.equal(state.params.presencePenalty, 1.5);assert.equal(state.paramsByModel[QWEN38]?.presencePenalty, 1.5);- assert.equal(- settingsHttp.puts.some(- (put) =>- (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[- QWEN38- ] !== undefined,- ),- true,- );+ assert.equal(hasModelPut(), true);});test("a model switch during the confirming read leaves the former row untouched", async () => {const legacySettings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },};let releaseConfirmation!: (value: Record<string, unknown>) => void;@@ -442,8 +393,7 @@ test("a model switch during the confirming read leaves the former row untouched"useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: QWEN38 },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -452,7 +402,7 @@ test("a model switch during the confirming read leaves the former row untouched"const hydration = useChatRuntimeStore.getState().hydratePersistedSettings();while (settingsHttp.gets < 2) {- await new Promise((resolve) => setTimeout(resolve, 0));+ await sleep(0);}useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: "unsloth/Qwen3.6-9B-GGUF" },@@ -465,36 +415,18 @@ test("a model switch during the confirming read leaves the former row untouched"useChatRuntimeStore.getState().paramsByModel[QWEN38]?.presencePenalty,0,);- assert.equal(- settingsHttp.puts.some(- (put) =>- (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[- QWEN38- ] !== undefined,- ),- false,- );+ assert.equal(hasModelPut(), false);});test("resident-model adoption migrates a deferred global-only snapshot", async () => {- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0,- maxTokens: 8192,- },- };- settingsHttp.puts.length = 0;+ seedSettings({+ ...BUILTIN_DEFAULT,+ inferenceParams: LEGACY_GLOBAL,+ });useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -509,7 +441,7 @@ test("resident-model adoption migrates a deferred global-only snapshot", async (migrateOwnedGlobalQwenDefaults: true,},);- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);const globalPut = settingsHttp.puts.find((put) => put.inferenceParams !== undefined,@@ -521,25 +453,15 @@ test("resident-model adoption migrates a deferred global-only snapshot", async (});test("resident-model adoption does not claim a global beside model memory", async () => {- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0,- maxTokens: 8192,- },+ seedSettings({+ ...BUILTIN_DEFAULT,+ inferenceParams: LEGACY_GLOBAL,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- };- settingsHttp.puts.length = 0;+ });useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -554,7 +476,7 @@ test("resident-model adoption does not claim a global beside model memory", asynmigrateOwnedGlobalQwenDefaults: true,},);- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);const persisted = settingsHttp.settings as {inferenceParams?: { minP?: number; presencePenalty?: number };@@ -573,13 +495,10 @@ test("resident-model adoption does not claim a global beside model memory", asyntest("a retry cannot overwrite an edit made after its confirming read", async () => {const legacySettings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },};- settingsHttp.getResponses.length = 0;- settingsHttp.settings = legacySettings;- settingsHttp.puts.length = 0;+ seedSettings(legacySettings);settingsHttp.beforeConditionalApply = () => {settingsHttp.settings = {...legacySettings,@@ -591,8 +510,7 @@ test("a retry cannot overwrite an edit made after its confirming read", async ()useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -604,24 +522,15 @@ test("a retry cannot overwrite an edit made after its confirming read", async (){ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);assert.equal(settingsHttp.puts.length, 0);- assert.equal(- (- settingsHttp.settings.inferenceParamsByModel as Record<- string,- Record<string, unknown>- >- )[QWEN38].presencePenalty,- 0.4,- );+ assert.equal(persistedRow().presencePenalty, 0.4);});test("a retry revalidates the checkpoint after its confirming read", async () => {const legacySettings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },};let releaseConfirmation!: (value: Record<string, unknown>) => void;@@ -635,8 +544,7 @@ test("a retry revalidates the checkpoint after its confirming read", async () =>useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -649,7 +557,7 @@ test("a retry revalidates the checkpoint after its confirming read", async () =>{ fromModelDefaults: true },);while (settingsHttp.gets < 1) {- await new Promise((resolve) => setTimeout(resolve, 0));+ await sleep(0);}useChatRuntimeStore.setState((state) => ({params: {@@ -659,37 +567,25 @@ test("a retry revalidates the checkpoint after its confirming read", async () =>reasoningEnabled: false,}));releaseConfirmation(legacySettings);- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);assert.equal(settingsHttp.puts.length, 0);- assert.equal(- (- settingsHttp.settings.inferenceParamsByModel as Record<- string,- Record<string, unknown>- >- )[QWEN38].presencePenalty,- 0,- );+ assert.equal(persistedRow().presencePenalty, 0);});test("a retry fences reasoning added after a confirming read", async () => {const legacySettings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },};- settingsHttp.getResponses.length = 0;- settingsHttp.settings = legacySettings;- settingsHttp.puts.length = 0;+ seedSettings(legacySettings);settingsHttp.beforeConditionalApply = () => {settingsHttp.settings = { ...legacySettings, reasoningEnabled: false };};useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -701,40 +597,22 @@ test("a retry fences reasoning added after a confirming read", async () => {{ ...state.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);assert.equal(settingsHttp.puts.length, 0);assert.equal(settingsHttp.settings.reasoningEnabled, false);- assert.equal(- (- settingsHttp.settings.inferenceParamsByModel as Record<- string,- Record<string, unknown>- >- )[QWEN38].presencePenalty,- 0,- );+ assert.equal(persistedRow().presencePenalty, 0);});test("deferred global ownership cannot follow a later checkpoint", async () => {- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0,- maxTokens: 8192,- },- };- settingsHttp.puts.length = 0;+ seedSettings({+ ...BUILTIN_DEFAULT,+ inferenceParams: LEGACY_GLOBAL,+ });useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -756,7 +634,7 @@ test("deferred global ownership cannot follow a later checkpoint", async () => {},reasoningEnabled: false,}));- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);const persisted = settingsHttp.settings as {inferenceParams?: { presencePenalty?: number; minP?: number };@@ -766,18 +644,14 @@ test("deferred global ownership cannot follow a later checkpoint", async () => {});test("local migration preserves an active thread's sampling override", async () => {- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ seedSettings({+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- };- settingsHttp.puts.length = 0;+ });useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -795,7 +669,7 @@ test("local migration preserves an active thread's sampling override", async (){ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);const migrated = useChatRuntimeStore.getState();assert.equal(migrated.params.presencePenalty, 0);@@ -809,26 +683,16 @@ test("local migration preserves an active thread's sampling override", async ()});test("hydration migrates the authoritative global when model memory is off", async () => {- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ seedSettings({+ ...BUILTIN_DEFAULT,rememberParamsPerModel: false,- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0,- maxTokens: 8192,- },+ inferenceParams: LEGACY_GLOBAL,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- };- settingsHttp.puts.length = 0;+ });useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: QWEN38 },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -857,26 +721,16 @@ test("hydration migrates the authoritative global when model memory is off", asy});test("a first user model load during hydration does not claim prior globals", async () => {- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ seedSettings({+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0,- maxTokens: 8192,- },- };- settingsHttp.puts.length = 0;+ inferenceParams: LEGACY_GLOBAL,+ });settingsHttp.hold();useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: "" },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -884,7 +738,7 @@ test("a first user model load during hydration does not claim prior globals", as}));const hydration = useChatRuntimeStore.getState().hydratePersistedSettings();- await new Promise((resolve) => setTimeout(resolve, 0));+ await sleep(0);const loading = useChatRuntimeStore.getState();loading.setParams({@@ -911,13 +765,10 @@ test("a first user model load during hydration does not claim prior globals", astest("a normalized migration patch stays within the loaded context", async () => {const lowerCaseKey = QWEN38.toLowerCase();- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ seedSettings({+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [lowerCaseKey]: LEGACY_SNAPSHOT },- };- settingsHttp.puts.length = 0;+ });useChatRuntimeStore.setState((state) => ({params: {...state.params,@@ -927,8 +778,7 @@ test("a normalized migration patch stays within the loaded context", async () =>},paramsByModel: { [lowerCaseKey]: LEGACY_SNAPSHOT },loadedContextLength: 4096,- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -940,7 +790,7 @@ test("a normalized migration patch stays within the loaded context", async () =>{ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);const migrated = useChatRuntimeStore.getState();assert.equal(migrated.params.maxTokens, 4096);@@ -948,26 +798,16 @@ test("a normalized migration patch stays within the loaded context", async () =>});test("deferred adoption migrates the authoritative global when memory is off", async () => {- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ seedSettings({+ ...BUILTIN_DEFAULT,rememberParamsPerModel: false,- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0,- maxTokens: 8192,- },+ inferenceParams: LEGACY_GLOBAL,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- };- settingsHttp.puts.length = 0;+ });useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: "" },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -988,7 +828,7 @@ test("deferred adoption migrates the authoritative global when memory is off", amigrateOwnedGlobalQwenDefaults: true,},);- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);const globalPatch = settingsHttp.puts.find((put) => put.inferenceParams !== undefined,@@ -1002,19 +842,10 @@ test("deferred adoption migrates the authoritative global when memory is off", atest("a retry fences optional global fields added after confirmation", async () => {await flushPendingChatSettings();const legacySettings = {- activePreset: "Default",- activePresetSource: "builtin-default",- inferenceParams: {- temperature: 0.6,- topP: 0.95,- minP: 0.01,- presencePenalty: 0,- maxTokens: 8192,- },+ ...BUILTIN_DEFAULT,+ inferenceParams: LEGACY_GLOBAL,};- settingsHttp.getResponses.length = 0;- settingsHttp.settings = legacySettings;- settingsHttp.puts.length = 0;+ seedSettings(legacySettings);settingsHttp.beforeConditionalApply = () => {settingsHttp.settings = {...legacySettings,@@ -1030,8 +861,7 @@ test("a retry fences optional global fields added after confirmation", async ()presencePenalty: 1.5,},paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -1046,7 +876,7 @@ test("a retry fences optional global fields added after confirmation", async ()migrateOwnedGlobalQwenDefaults: true,},);- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);assert.equal(settingsHttp.puts.length, 0);assert.equal(@@ -1064,19 +894,15 @@ test("a retry fences optional global fields added after confirmation", async ()});test("migration follows the reasoning mode established by the loaded model", async () => {- settingsHttp.getResponses.length = 0;- settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ seedSettings({+ ...BUILTIN_DEFAULT,reasoningEnabled: true,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- };- settingsHttp.puts.length = 0;+ });useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,supportsReasoning: true,reasoningAlwaysOn: false,reasoningEnabled: false,@@ -1097,7 +923,7 @@ test("migration follows the reasoning mode established by the loaded model", asy},{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);assert.deepEqual(settingsHttp.puts.find(@@ -1120,8 +946,7 @@ test("routine model-default refreshes skip migration reads without a candidate",settingsHttp.gets = 0;settingsHttp.puts.length = 0;settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,};useChatRuntimeStore.setState((state) => ({params: {@@ -1135,14 +960,13 @@ test("routine model-default refreshes skip migration reads without a candidate",presencePenalty: 1.5,},paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,settingsHydrated: true,}));const qwen = useChatRuntimeStore.getState();qwen.setParams({ ...qwen.params }, { fromModelDefaults: true });- await new Promise((resolve) => setTimeout(resolve, 0));+ await sleep(0);assert.equal(settingsHttp.gets, 0);const llamaCheckpoint = "unsloth/Llama-3.2-3B-Instruct-GGUF";@@ -1151,7 +975,7 @@ test("routine model-default refreshes skip migration reads without a candidate",{ ...current.params, checkpoint: llamaCheckpoint },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 0));+ await sleep(0);assert.equal(settingsHttp.gets, 0);});@@ -1167,8 +991,7 @@ test("a failed settings write does not strand the migration", async () => {settingsHttp.puts.length = 0;settingsHttp.putFailures = [{ status: 503 }];settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },};useChatRuntimeStore.setState((state) => ({@@ -1182,15 +1005,7 @@ test("a failed settings write does not strand the migration", async () => {}));useChatRuntimeStore.getState().setActivePresetSource("builtin-default");- await new Promise((resolve) => setTimeout(resolve, 50));-- const migrationReached = (): boolean =>- settingsHttp.puts.some(- (put) =>- (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[- QWEN38- ] !== undefined,- );+ await sleep(50);// The 503 leaves the older patch requeued. Reaching the backend merge after// the CAS would restore the legacy row, so the migration has to be the last@@ -1211,7 +1026,7 @@ test("a failed settings write does not strand the migration", async () => {await flushPendingChatSettings();const qwen = useChatRuntimeStore.getState();qwen.setParams({ ...qwen.params }, { fromModelDefaults: true });- await new Promise((resolve) => setTimeout(resolve, 50));+ await sleep(50);- assert.equal(migrationReached(), true, "the retry never landed");+ assert.equal(hasModelPut(), true, "the retry never landed");});diff --git a/studio/frontend/tests/qwen-defaults-migration-safety.test.ts b/studio/frontend/tests/qwen-defaults-migration-safety.test.tsindex 7974320add6..7a11a06915d 100644--- a/studio/frontend/tests/qwen-defaults-migration-safety.test.ts+++ b/studio/frontend/tests/qwen-defaults-migration-safety.test.ts@@ -48,7 +48,8 @@ function resetHttp(settings: Record<string, unknown>): void {settingsHttp.putGate = null;}-function seedActiveQwen(): void {+/** The store as it stands with the legacy Qwen3.8 snapshot loaded and active. */+function seedActiveQwen(overrides: Record<string, unknown> = {}): void {useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },@@ -58,9 +59,23 @@ function seedActiveQwen(): void {reasoningAlwaysOn: false,reasoningEnabled: true,settingsHydrated: true,+ ...overrides,}));}+const sleep = (ms: number): Promise<void> =>+ new Promise((resolve) => setTimeout(resolve, ms));++/** The adoption a model load performs, and the drain that follows it. */+async function adoptQwenDefaults(): Promise<void> {+ const active = useChatRuntimeStore.getState();+ active.setParams(+ { ...active.params, minP: 0, presencePenalty: 1.5 },+ { fromModelDefaults: true },+ );+ await sleep(50);+}+function serverRow(key = QWEN38): Record<string, unknown> {return (settingsHttp.settings.inferenceParamsByModel as Record<@@ -70,9 +85,13 @@ function serverRow(key = QWEN38): Record<string, unknown> {)[key];}-const LEGACY_SETTINGS = {+const BUILTIN_DEFAULT = {activePreset: "Default",activePresetSource: "builtin-default",+} as const;++const LEGACY_SETTINGS = {+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },};@@ -90,12 +109,7 @@ test("a rejected retry leaves local sampling on the value the server kept", asyn};seedActiveQwen();- const active = useChatRuntimeStore.getState();- active.setParams(- { ...active.params, minP: 0, presencePenalty: 1.5 },- { fromModelDefaults: true },- );- await new Promise((resolve) => setTimeout(resolve, 50));+ await adoptQwenDefaults();assert.equal(settingsHttp.puts.length, 0);assert.equal(serverRow().presencePenalty, 0.4);@@ -112,12 +126,7 @@ test("an accepted retry still applies the migration locally", async () => {resetHttp({ ...LEGACY_SETTINGS });seedActiveQwen();- const active = useChatRuntimeStore.getState();- active.setParams(- { ...active.params, minP: 0, presencePenalty: 1.5 },- { fromModelDefaults: true },- );- await new Promise((resolve) => setTimeout(resolve, 50));+ await adoptQwenDefaults();assert.equal(settingsHttp.puts.length, 1);assert.equal(serverRow().presencePenalty, 1.5);@@ -134,12 +143,7 @@ test("a backend without the conditional route persists nothing and shows nothingsettingsHttp.conditionalStatus = 404;seedActiveQwen();- const active = useChatRuntimeStore.getState();- active.setParams(- { ...active.params, minP: 0, presencePenalty: 1.5 },- { fromModelDefaults: true },- );- await new Promise((resolve) => setTimeout(resolve, 50));+ await adoptQwenDefaults();assert.equal(settingsHttp.puts.length, 0);assert.equal(serverRow().presencePenalty, 0);@@ -153,12 +157,7 @@ test("the browser build's 405 is treated the same as an absent route", async ()settingsHttp.conditionalStatus = 405;seedActiveQwen();- const active = useChatRuntimeStore.getState();- active.setParams(- { ...active.params, minP: 0, presencePenalty: 1.5 },- { fromModelDefaults: true },- );- await new Promise((resolve) => setTimeout(resolve, 50));+ await adoptQwenDefaults();assert.equal(settingsHttp.puts.length, 0);assert.equal(serverRow().presencePenalty, 0);@@ -167,16 +166,9 @@ test("the browser build's 405 is treated the same as an absent route", async ()test("a preset modified during hydration is not migrated on a stale read", async () => {resetHttp({ ...LEGACY_SETTINGS });- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },- paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",- rememberParamsPerModel: true,- reasoningAlwaysOn: false,- reasoningEnabled: true,+ seedActiveQwen({settingsHydrated: false,- }));+ });settingsHttp.hold();const hydration = useChatRuntimeStore.getState().hydratePersistedSettings();// A slider moves while the settings GET is in flight. Its provenance write@@ -197,38 +189,24 @@ test("a preset modified during hydration is not migrated on a stale read", asynctest("a normalized exact key cannot overwrite a row added after the read", async () => {const lower = QWEN38.toLowerCase();resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [lower]: LEGACY_SNAPSHOT },});const newerRow = { temperature: 0.31, presencePenalty: 0.4, maxTokens: 2048 };settingsHttp.beforeConditionalApply = () => {settingsHttp.settings = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: {[lower]: LEGACY_SNAPSHOT,[QWEN38]: newerRow,},};};- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },+ seedActiveQwen({paramsByModel: { [lower]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",- rememberParamsPerModel: true,- reasoningAlwaysOn: false,- reasoningEnabled: true,- settingsHydrated: true,- }));+ });- const active = useChatRuntimeStore.getState();- active.setParams(- { ...active.params, minP: 0, presencePenalty: 1.5 },- { fromModelDefaults: true },- );- await new Promise((resolve) => setTimeout(resolve, 50));+ await adoptQwenDefaults();// The exact-key row the other tab wrote must survive intact, and no// per-model patch may be sent for it at all.@@ -243,27 +221,14 @@ test("a normalized exact key cannot overwrite a row added after the read", asynctest("a model id containing slashes stays one absence-fence path segment", async () => {const lower = QWEN38.toLowerCase();resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [lower]: LEGACY_SNAPSHOT },});- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },+ seedActiveQwen({paramsByModel: { [lower]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",- rememberParamsPerModel: true,- reasoningAlwaysOn: false,- reasoningEnabled: true,- settingsHydrated: true,- }));+ });- const active = useChatRuntimeStore.getState();- active.setParams(- { ...active.params, minP: 0, presencePenalty: 1.5 },- { fromModelDefaults: true },- );- await new Promise((resolve) => setTimeout(resolve, 50));+ await adoptQwenDefaults();// Nothing raced it, so the normalization applies under the exact spelling.assert.equal(serverRow(QWEN38).presencePenalty, 1.5);@@ -272,21 +237,14 @@ test("a model id containing slashes stays one absence-fence path segment", asynctest("the loaded model's reasoning mode survives hydration", async () => {// A small Qwen defaults to non-thinking while storage still says thinking.resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,reasoningEnabled: true,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },});- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },- paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",- rememberParamsPerModel: true,- reasoningAlwaysOn: false,+ seedActiveQwen({reasoningEnabled: false,settingsHydrated: false,- }));+ });noteLoadedModelReasoningMode(QWEN38, false, true);await useChatRuntimeStore.getState().hydratePersistedSettings();@@ -305,21 +263,13 @@ test("a status refresh cannot outrank the installation's persisted reasoning", a// which before hydration is a local default, not the installation setting.// Only a load this browser performed may win.resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,reasoningEnabled: false,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },});- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },- paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",- rememberParamsPerModel: true,- reasoningAlwaysOn: false,- reasoningEnabled: true,+ seedActiveQwen({settingsHydrated: false,- }));+ });// This browser never loaded QWEN38: clear any load marker left by an earlier// case, then let a status merely report the model (fromLoad defaults false).noteLoadedModelReasoningMode("unsloth/Llama-3.2-3B-Instruct-GGUF", false);@@ -336,21 +286,14 @@ test("the post-load refresh does not drop the load's claim on the mode", async (// noteLoadedModelReasoningMode again with the default false. Downgrading there// would let hydration replay the previous model's persisted toggle.resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,reasoningEnabled: true,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },});- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },- paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",- rememberParamsPerModel: true,- reasoningAlwaysOn: false,+ seedActiveQwen({reasoningEnabled: false,settingsHydrated: false,- }));+ });noteLoadedModelReasoningMode(QWEN38, false, true);// The refresh that performLoad awaits, reporting the same model.noteLoadedModelReasoningMode(QWEN38, false);@@ -367,21 +310,13 @@ test("a model without reasoning support is migrated as non-thinking", async () =// The load-time overlay is gated on supportsReasoning, so a toggle left over// from the previous model must not pick the thinking table for the row.resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },});- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },- paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",- rememberParamsPerModel: true,- reasoningAlwaysOn: false,- reasoningEnabled: true,+ seedActiveQwen({supportsReasoning: false,settingsHydrated: false,- }));+ });// A status reported this checkpoint, and it cannot reason.noteLoadedModelReasoningMode("unsloth/Llama-3.2-3B-Instruct-GGUF", false);useChatRuntimeStore.setState({ reasoningEnabled: true });@@ -400,8 +335,7 @@ test("an empty stored model map is declined, since it cannot be fenced", async (// adding the first row would slip through, so this declines rather than// write unfenced. An absent key is different and stays fenced.resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParams: {temperature: 0.6,topP: 0.95,@@ -410,16 +344,11 @@ test("an empty stored model map is declined, since it cannot be fenced", async (},inferenceParamsByModel: {},});- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },+ seedActiveQwen({paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",rememberParamsPerModel: false,- reasoningAlwaysOn: false,- reasoningEnabled: true,settingsHydrated: false,- }));+ });await useChatRuntimeStore.getState().hydratePersistedSettings();@@ -434,16 +363,14 @@ test("case-distinct POSIX paths keep separate reasoning-mode records", async ()const upper = "/home/u/Models/qwen3.8-27b";const lower = "/home/u/models/qwen3.8-27b";resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,reasoningEnabled: true,inferenceParamsByModel: { [lower]: LEGACY_SNAPSHOT },});useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: lower },paramsByModel: { [lower]: LEGACY_SNAPSHOT },- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: false,@@ -481,7 +408,7 @@ test("a checkpoint switch during the conditional write is not migrated", async ({ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 60));+ await sleep(60);// The row the user switched to keeps its legacy values locally.const after = useChatRuntimeStore.getState();@@ -497,8 +424,7 @@ test("case-distinct POSIX ownership claims still conflict", async () => {const upper = "/home/u/Models/qwen3.8-27b";const lower = "/home/u/models/qwen3.8-27b";resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParams: {temperature: 0.6,topP: 0.95,@@ -509,8 +435,7 @@ test("case-distinct POSIX ownership claims still conflict", async () => {useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: lower },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: false,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -528,7 +453,7 @@ test("case-distinct POSIX ownership claims still conflict", async () => {{ ...second.params, checkpoint: lower },{ fromModelDefaults: true, migrateOwnedGlobalQwenDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 60));+ await sleep(60);const global = settingsHttp.settings.inferenceParams as Record<string,@@ -545,15 +470,13 @@ test("selecting an external Qwen migrates its dormant row", async () => {"Qwen/Qwen3.8-27B",)}`;resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [external]: LEGACY_SNAPSHOT },});useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: "unsloth/Llama-3.2-3B-Instruct-GGUF" },paramsByModel: { [external]: { ...LEGACY_SNAPSHOT } },- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -562,7 +485,7 @@ test("selecting an external Qwen migrates its dormant row", async () => {}));useChatRuntimeStore.getState().setCheckpoint(external, null);- await new Promise((resolve) => setTimeout(resolve, 60));+ await sleep(60);const row = serverRow(external);assert.equal(row.presencePenalty, 1.5);@@ -575,15 +498,13 @@ test("the send barrier waits for a migration a model pick just scheduled", async"Qwen/Qwen3.6-9B",)}`;resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: { [external]: LEGACY_SNAPSHOT },});useChatRuntimeStore.setState((state) => ({params: { ...state.params, checkpoint: "unsloth/Llama-3.2-3B-Instruct-GGUF" },paramsByModel: { [external]: { ...LEGACY_SNAPSHOT } },- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -618,7 +539,7 @@ test("an edit racing the conditional write does not strand local on legacy", asy{ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 60));+ await sleep(60);// The server took the migration, so the tab must not keep generating from the// values it no longer holds.@@ -640,7 +561,7 @@ test("a decision field that sanitizes away blocks the write", async () => {{ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 60));+ await sleep(60);// The row itself, not the queue: an earlier case's debounced PUT can land in// this window and says nothing about whether the migration wrote.@@ -654,8 +575,7 @@ test("a case-distinct external switch during the write is not migrated", async (const upper = `external::vendor::${encodeURIComponent("Vendor/Qwen3.8-27B")}`;const lower = `external::vendor::${encodeURIComponent("vendor/qwen3.8-27b")}`;resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: {[upper]: LEGACY_SNAPSHOT,[lower]: LEGACY_SNAPSHOT,@@ -672,8 +592,7 @@ test("a case-distinct external switch during the write is not migrated", async ([upper]: { ...LEGACY_SNAPSHOT },[lower]: { ...LEGACY_SNAPSHOT },},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -686,7 +605,7 @@ test("a case-distinct external switch during the write is not migrated", async ({ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 60));+ await sleep(60);// Only the row the write was for; the other model keeps its own values.const lowerRow = useChatRuntimeStore.getState().paramsByModel[lower] as Record<@@ -700,8 +619,7 @@ test("a case-distinct external switch during the write is not migrated", async (test("an earlier retry settling does not clear a later retry's barrier", async () => {const QWEN36 = "unsloth/Qwen3.6-14B-GGUF";const base = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: {[QWEN38]: { ...LEGACY_SNAPSHOT },[QWEN36]: { ...LEGACY_SNAPSHOT },@@ -720,26 +638,19 @@ test("an earlier retry settling does not clear a later retry's barrier", async (const [firstGet, releaseFirst] = holdGet();const [secondGet, releaseSecond] = holdGet();settingsHttp.getResponses.push(firstGet, secondGet);- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },+ seedActiveQwen({paramsByModel: {[QWEN38]: { ...LEGACY_SNAPSHOT },[QWEN36]: { ...LEGACY_SNAPSHOT },},- activePreset: "Default",- activePresetSource: "builtin-default",- rememberParamsPerModel: true,- reasoningAlwaysOn: false,- reasoningEnabled: true,- settingsHydrated: true,- }));+ });const first = useChatRuntimeStore.getState();first.setParams({ ...first.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 0));+ await sleep(0);useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN36 },}));@@ -748,9 +659,9 @@ test("an earlier retry settling does not clear a later retry's barrier", async ({ ...second.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 10));+ await sleep(10);releaseFirst();- await new Promise((resolve) => setTimeout(resolve, 30));+ await sleep(30);setTimeout(releaseSecond, 40);// A barrier cleared by the wrong retry resolves here with the second row@@ -765,8 +676,7 @@ test("an earlier retry settling does not clear a later retry's barrier", async (test("the send barrier follows a retry that replaces the one it captured", async () => {const QWEN36 = "unsloth/Qwen3.6-14B-GGUF";const base = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: {[QWEN38]: { ...LEGACY_SNAPSHOT },[QWEN36]: { ...LEGACY_SNAPSHOT },@@ -783,26 +693,19 @@ test("the send barrier follows a retry that replaces the one it captured", asyncconst [firstGet, releaseFirst] = holdGet();const [secondGet, releaseSecond] = holdGet();settingsHttp.getResponses.push(firstGet, secondGet);- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },+ seedActiveQwen({paramsByModel: {[QWEN38]: { ...LEGACY_SNAPSHOT },[QWEN36]: { ...LEGACY_SNAPSHOT },},- activePreset: "Default",- activePresetSource: "builtin-default",- rememberParamsPerModel: true,- reasoningAlwaysOn: false,- reasoningEnabled: true,- settingsHydrated: true,- }));+ });const first = useChatRuntimeStore.getState();first.setParams({ ...first.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 0));+ await sleep(0);// The send joins here, so it captures the first retry.const barrier = awaitPendingQwenDefaultsMigration();useChatRuntimeStore.setState((state) => ({@@ -813,7 +716,7 @@ test("the send barrier follows a retry that replaces the one it captured", async{ ...second.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 10));+ await sleep(10);releaseFirst();setTimeout(releaseSecond, 60);@@ -836,7 +739,7 @@ test("a write outlasting the flush timeout rearms the migration", async () => {// the wire when the migration tries to land.const before = useChatRuntimeStore.getState();before.setAutoTitle(!before.autoTitle);- await new Promise((resolve) => setTimeout(resolve, 600));+ await sleep(600);const active = useChatRuntimeStore.getState();active.setParams(@@ -844,12 +747,12 @@ test("a write outlasting the flush timeout rearms the migration", async () => {{ fromModelDefaults: true },);// Past the 2000 ms flush timeout with the ordinary write still outstanding.- await new Promise((resolve) => setTimeout(resolve, 2600));+ await sleep(2600);assert.equal(serverRow().presencePenalty, 0);releasePut();settingsHttp.putGate = null;- await new Promise((resolve) => setTimeout(resolve, 200));+ await sleep(200);await Promise.race([awaitPendingQwenDefaultsMigration(),new Promise((resolve) => setTimeout(resolve, 5000)),@@ -861,22 +764,14 @@ test("a status-only reasoning marker does not pick the migration table", async (// Status for a resident model lands before the settings GET, so the marker// carries this browser's local default rather than an answer about the model.resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,reasoningEnabled: false,inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },});- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },+ seedActiveQwen({paramsByModel: { [QWEN38]: { ...LEGACY_SNAPSHOT } },- activePreset: "Default",- activePresetSource: "builtin-default",- rememberParamsPerModel: true,supportsReasoning: true,- reasoningAlwaysOn: false,- reasoningEnabled: true,- settingsHydrated: true,- }));+ });noteLoadedModelReasoningMode(QWEN38, true);const active = useChatRuntimeStore.getState();@@ -884,7 +779,7 @@ test("a status-only reasoning marker does not pick the migration table", async ({ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 60));+ await sleep(60);// The persisted toggle is off, so the non-thinking row is what the pill will// hydrate against.@@ -897,25 +792,19 @@ test("a null model map is fenced rather than treated as empty", async () => {// row holds, so another tab can replace it with rows this write never saw,// and the compare-and-set asserts neither its value nor its absence.resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParams: { ...LEGACY_SNAPSHOT },inferenceParamsByModel: null,});- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },+ seedActiveQwen({paramsByModel: {},- activePreset: "Default",activePresetSource: "custom",rememberParamsPerModel: false,- reasoningAlwaysOn: false,- reasoningEnabled: true,supportsReasoning: true,- settingsHydrated: true,- }));+ });useChatRuntimeStore.getState().setActivePresetSource("builtin-default");- await new Promise((resolve) => setTimeout(resolve, 80));+ await sleep(80);const globals = settingsHttp.settings.inferenceParams as Record<string,@@ -930,26 +819,20 @@ test("per-model memory enabled during the read cancels the global migration", as// Scheduled while the global snapshot was the active model's to rewrite; the// confirming read shows per-model memory on, so it no longer is.resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: true,inferenceParams: { ...LEGACY_SNAPSHOT },inferenceParamsByModel: { [OTHER]: { ...LEGACY_SNAPSHOT } },});- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },+ seedActiveQwen({paramsByModel: {},- activePreset: "Default",activePresetSource: "custom",rememberParamsPerModel: false,- reasoningAlwaysOn: false,- reasoningEnabled: true,supportsReasoning: true,- settingsHydrated: true,- }));+ });useChatRuntimeStore.getState().setActivePresetSource("builtin-default");- await new Promise((resolve) => setTimeout(resolve, 80));+ await sleep(80);const globals = settingsHttp.settings.inferenceParams as Record<string,@@ -970,7 +853,7 @@ test("a wedged backend does not hold a send open forever", async () => {{ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 20));+ await sleep(20);const started = Date.now();let timedOut = false;@@ -994,15 +877,13 @@ test("adopting the startup model clears the unowned pre-hydration mark", async (// any pre-hydration switch as an interactive pick, and adoption is the signal// that says otherwise, so the global snapshot is still this model's.resetHttp({- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParams: { ...LEGACY_SNAPSHOT },});useChatRuntimeStore.setState((state) => ({params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: "" },paramsByModel: {},- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,rememberParamsPerModel: false,reasoningAlwaysOn: false,reasoningEnabled: true,@@ -1021,7 +902,7 @@ test("adopting the startup model clears the unowned pre-hydration mark", async (settingsHttp.release?.();await hydrating;- await new Promise((resolve) => setTimeout(resolve, 60));+ await sleep(60);const global = settingsHttp.settings.inferenceParams as Record<string,@@ -1050,7 +931,7 @@ test("a thread pin survives the race recovery path", async () => {{ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 80));+ await sleep(80);assert.equal(useChatRuntimeStore.getState().params.presencePenalty,@@ -1075,7 +956,7 @@ test("an unreachable backend does not spin the migration rearm", async () => {{ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 1500));+ await sleep(1500);assert.ok(settingsHttp.puts.length < 40,@@ -1087,8 +968,7 @@ test("an unreachable backend does not spin the migration rearm", async () => {test("a model switch during hydration still gets its own row migrated", async () => {const QWEN36 = "unsloth/Qwen3.6-14B-GGUF";const stored = {- activePreset: "Default",- activePresetSource: "builtin-default",+ ...BUILTIN_DEFAULT,inferenceParamsByModel: {[QWEN38]: { ...LEGACY_SNAPSHOT },[QWEN36]: { ...LEGACY_SNAPSHOT },@@ -1102,22 +982,16 @@ test("a model switch during hydration still gets its own row migrated", async ()releaseConfirm = () => resolve(settingsHttp.settings);});settingsHttp.getResponses.push(stored, confirming);- useChatRuntimeStore.setState((state) => ({- params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },+ seedActiveQwen({paramsByModel: {[QWEN38]: { ...LEGACY_SNAPSHOT },[QWEN36]: { ...LEGACY_SNAPSHOT },},- activePreset: "Default",- activePresetSource: "builtin-default",- rememberParamsPerModel: true,- reasoningAlwaysOn: false,- reasoningEnabled: true,supportsReasoning: true,settingsHydrated: false,- }));+ });const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();- await new Promise((resolve) => setTimeout(resolve, 20));+ await sleep(20);// The model moves while the confirming read is out. Neither switch path can// schedule a retry from here, since hydration has not finished.useChatRuntimeStore.setState((state) => ({@@ -1125,7 +999,7 @@ test("a model switch during hydration still gets its own row migrated", async ()}));releaseConfirm();await hydrating;- await new Promise((resolve) => setTimeout(resolve, 80));+ await sleep(80);const row = (settingsHttp.settings.inferenceParamsByModel as Record<@@ -1154,7 +1028,7 @@ test("a custom preset chosen mid-write keeps its own legacy-valued fields", asyn{ ...active.params, minP: 0, presencePenalty: 1.5 },{ fromModelDefaults: true },);- await new Promise((resolve) => setTimeout(resolve, 80));+ await sleep(80);const after = useChatRuntimeStore.getState().params;assert.equal(after.presencePenalty, 0);diff --git a/studio/frontend/tests/qwen38-sampling-defaults.test.ts b/studio/frontend/tests/qwen38-sampling-defaults.test.tsindex 8e59a0a888c..0d559474d67 100644--- a/studio/frontend/tests/qwen38-sampling-defaults.test.ts+++ b/studio/frontend/tests/qwen38-sampling-defaults.test.ts@@ -2,11 +2,10 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import { register } from "node:module";import test from "node:test";-import { installLocalStorageFake } from "./helpers/kit.ts";+import { installLocalStorageFake, readSrc } from "./helpers/kit.ts";installLocalStorageFake();register("./store-settings-resolver.mjs", import.meta.url);@@ -56,12 +55,8 @@ test("the Qwen3.8 Think toggle puts 1.5 in the live chat settings", () => {});test("every status merge is wired to the active Qwen thinking table", () => {- const source = readFileSync(- new URL(- "../src/features/chat/lib/apply-inference-status-to-store.ts",- import.meta.url,- ),- "utf8",+ const source = readSrc(+ "features/chat/lib/apply-inference-status-to-store.ts",);assert.match(source,diff --git a/studio/frontend/tests/rag-availability-marker.test.ts b/studio/frontend/tests/rag-availability-marker.test.tsindex 6d8172be8a0..41c53e1e468 100644--- a/studio/frontend/tests/rag-availability-marker.test.ts+++ b/studio/frontend/tests/rag-availability-marker.test.ts@@ -8,10 +8,11 @@// apparently-working empty Knowledge bases page whose Create button could only 503.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";++const RAG_API = readSrc("features/rag/api/rag-api.ts");registerBundlerResolver();@@ -33,10 +34,6 @@ function resetAvailability() {});}-function readSrc(path: string) {- return readFile(new URL(`../src/${path}`, import.meta.url), "utf8");-}-/** The body of a top-level function, so an assertion cannot pass on a neighbour's code. */function functionBody(src: string, name: string): string {const start = src.search(new RegExp(`(async )?function\\*?\\s+${name}\\b`));@@ -206,13 +203,12 @@ test("the KB list's own 200 does not overrule its marker", () => {// four call sites, because three of them bypass ragRequesttest("every RAG response path reports availability", async () => {- const src = await readSrc("features/rag/api/rag-api.ts");assert.match(- src,+ RAG_API,/import \{ noteRagAvailability, noteRagResponse \} from "\.\/rag-availability";/,"rag-api does not read the availability contract at all",);- const request = functionBody(src, "ragRequest");+ const request = functionBody(RAG_API, "ragRequest");assert.match(request,/noteRagResponse\(204, null\)/,@@ -223,26 +219,26 @@ test("every RAG response path reports availability", async () => {/noteRagResponse\(response\.status, json\);\n\s*if \(!response\.ok\)/,"the 503 is turned straight into a thrown Error, so nothing records it",);- const upload = functionBody(src, "ragUpload");+ const upload = functionBody(RAG_API, "ragUpload");assert.match(upload,/noteRagResponse\(response\.status, json\)/,"ragUpload bypasses ragRequest, so its 503 is still dropped",);- const stream = functionBody(src, "openEventStream");+ const stream = functionBody(RAG_API, "openEventStream");assert.match(stream,/noteRagResponse\(response\.status, body\)/,"the SSE endpoints bypass ragRequest too",);assert.match(- functionBody(src, "boundedEventStream"),+ functionBody(RAG_API, "boundedEventStream"),/openEventStream\(/,"the budgeted stream opens without the availability check",);for (const generator of ["streamJobEvents", "streamFolderSyncJobEvents"]) {assert.match(- functionBody(src, generator),+ functionBody(RAG_API, generator),/boundedEventStream</,`${generator} opens its stream outside the budgeted opener`,);@@ -250,8 +246,7 @@ test("every RAG response path reports availability", async () => {});test("listKnowledgeBases reads the marker before returning the array", async () => {- const src = await readSrc("features/rag/api/rag-api.ts");- const list = functionBody(src, "listKnowledgeBases");+ const list = functionBody(RAG_API, "listKnowledgeBases");assert.match(list,/ragAvailable\?: boolean;/,diff --git a/studio/frontend/tests/rag-refresh-sequencing.test.ts b/studio/frontend/tests/rag-refresh-sequencing.test.tsindex 31332f805a4..fd23ce1e399 100644--- a/studio/frontend/tests/rag-refresh-sequencing.test.ts+++ b/studio/frontend/tests/rag-refresh-sequencing.test.ts@@ -8,9 +8,17 @@// latest-request rule useRagDocuments.refresh applies.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";+import { readSrc } from "./helpers/kit.ts";++const THREAD = readSrc("components/assistant-ui/thread.tsx");+const CHAT_ADAPTER = readSrc("features/chat/api/chat-adapter.ts");+const RAG_API = readSrc("features/rag/api/rag-api.ts");+const THREAD_DOCUMENTS_BAR = readSrc("features/rag/components/thread-documents-bar.tsx");+const USE_LINKED_FOLDERS = readSrc("features/rag/components/use-linked-folders.ts");+const USE_RAG_DOCUMENTS = readSrc("features/rag/components/use-rag-documents.ts");+type Row = { id: string; status: string };/** The publish gate as refresh applies it: take a ticket, drop the result if a@@ -106,15 +114,8 @@ test("a response for a scope that has been cleared does not publish", async () =});test("the scope-change effect takes a ticket on the way out", () => {- const source = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );assert.match(- source,+ USE_RAG_DOCUMENTS,/prev !== null && prev !== scopeKey\)[\s\S]{0,400}?refreshSeq\.current \+= 1;/,"clearing the scope must outrank a refresh already in flight",);@@ -123,15 +124,8 @@ test("the scope-change effect takes a ticket on the way out", () => {// A superseded failure describes a scope no longer shown, and a host without the// vector extension 503s every one of these: no toast per composer opened.test("a failure is only reported for the request still being awaited", () => {- const source = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );assert.match(- source,+ USE_RAG_DOCUMENTS,/if \(refreshSeq\.current !== requestId\) return true;\s*if \(\s*!opts\?\.silentErrors &&\s*!useRagAvailabilityStore\.getState\(\)\.isUnavailable\(\)/,);});@@ -140,18 +134,11 @@ test("a failure is only reported for the request still being awaited", () => {// would fail one request per chat opened. Checked on projectId itself, so the// attach controls and target menu go with it rather than offering a certain 503.test("no project scope is opened where RAG cannot run", () => {- const source = readFileSync(- new URL(- "../src/features/rag/components/thread-documents-bar.tsx",- import.meta.url,- ),- "utf8",- );assert.match(- source,+ THREAD_DOCUMENTS_BAR,/const projectId =\s*\(ragEnabled && ragSource\.type === "kb"\) \|\| ragUnavailable\s*\? null\s*: \(threadProjectId \?\? null\);/,);- assert.match(source, /projectId \? \{ type: "project", projectId \} : null/);+ assert.match(THREAD_DOCUMENTS_BAR, /projectId \? \{ type: "project", projectId \} : null/);});// A project's sources also change from the Sources panel: an upload invalidated@@ -189,43 +176,18 @@ test("work in the other instance counts as indexing", () => {});test("the composer reads indexing from the hooks, not the listed rows", () => {- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );- assert.match(hook, /noteProjectWork\(uploadingProjectId, 1\)/);- assert.match(hook, /noteProjectWork\(uploadingProjectId, -1\)/);- assert.match(hook, /workElsewhere > 0 \|\|/);+ assert.match(USE_RAG_DOCUMENTS, /noteProjectWork\(uploadingProjectId, 1\)/);+ assert.match(USE_RAG_DOCUMENTS, /noteProjectWork\(uploadingProjectId, -1\)/);+ assert.match(USE_RAG_DOCUMENTS, /workElsewhere > 0 \|\|/);// A folder sync reports at start and completion only, so the rows it// creates land with nothing gating the composer in between.- const folders = readFileSync(- new URL(- "../src/features/rag/components/use-linked-folders.ts",- import.meta.url,- ),- "utf8",- );// Tied to the job, not to the component that started it: leaving the Sources// tab aborts its event stream, the sync carries on.- assert.match(folders, /watchProjectFolderJob\(scopeId, initial\.id\)/);- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );- assert.match(api, /noteProjectWork\(projectId, 1\)/);- assert.match(api, /noteProjectWork\(projectId, -1\)/);- const bar = readFileSync(- new URL(- "../src/features/rag/components/thread-documents-bar.tsx",- import.meta.url,- ),- "utf8",- );+ assert.match(USE_LINKED_FOLDERS, /watchProjectFolderJob\(scopeId, initial\.id\)/);+ assert.match(RAG_API, /noteProjectWork\(projectId, 1\)/);+ assert.match(RAG_API, /noteProjectWork\(projectId, -1\)/);assert.match(- bar,+ THREAD_DOCUMENTS_BAR,/const hasIndexing =\s*threadIndexing \|\| threadListLoading \|\| projectIndexing \|\| projectListLoading;/,);});@@ -253,28 +215,14 @@ test("a poll tick is skipped while one is still out", () => {});test("the poll and the initial list are wired that way", () => {- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );assert.match(- hook,+ USE_RAG_DOCUMENTS,/if \(!refreshInFlight\.current\) \{\s*void refresh\(\{ quiet: true \}\);/,);// Reopening a project whose job is already running: nothing is listed yet and// no upload of ours is counted, so the gate has to hold for the first list.- const bar = readFileSync(- new URL(- "../src/features/rag/components/thread-documents-bar.tsx",- import.meta.url,- ),- "utf8",- );assert.match(- bar,+ THREAD_DOCUMENTS_BAR,/threadIndexing \|\| threadListLoading \|\| projectIndexing \|\| projectListLoading/,);});@@ -282,46 +230,31 @@ test("the poll and the initial list are wired that way", () => {// Two tabs on the same project share its sources, and a CustomEvent reaches// only the tab that fired it.test("an invalidation crosses tabs", () => {- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );assert.match(- api,+ RAG_API,/getProjectChannel\(\)\?\.postMessage\(\{ kind: "sources", projectId \}\)/,);// Work in flight crosses too, or the other tab stays sendable through it.assert.match(- api,+ RAG_API,/getProjectChannel\(\)\?\.postMessage\(\{\s*kind: "work",\s*projectId,\s*delta,\s*from: TAB_ID,/,);- assert.match(api, /new BroadcastChannel\(PROJECT_SOURCES_CHANGED_EVENT\)/);- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );- assert.match(hook, /subscribeProjectSourcesBroadcast\(\);/);+ assert.match(RAG_API, /new BroadcastChannel\(PROJECT_SOURCES_CHANGED_EVENT\)/);+ assert.match(USE_RAG_DOCUMENTS, /subscribeProjectSourcesBroadcast\(\);/);});// Only the tab that started the work can report it finished, and it may be// closed first, so what it reports lapses rather than gating for the session.test("work reported by another tab lapses", () => {- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );- assert.match(api, /const REMOTE_WORK_TTL_MS = 120_000;/);- assert.match(api, /until: Date\.now\(\) \+ REMOTE_WORK_TTL_MS/);+ assert.match(RAG_API, /const REMOTE_WORK_TTL_MS = 120_000;/);+ assert.match(RAG_API, /until: Date\.now\(\) \+ REMOTE_WORK_TTL_MS/);// Local and remote add up; a remote count past its deadline is dropped.assert.match(- api,+ RAG_API,/if \(entry\.until > now\) remoteCount \+= entry\.count;\s*\}\s*return \(projectWorkInFlight\.get\(projectId\) \?\? 0\) \+ remoteCount;/,);// One pending wake-up per project, however chatty the other tab is.- assert.match(api, /clearTimeout\(timer\)/);+ assert.match(RAG_API, /clearTimeout\(timer\)/);const TTL = 120_000;const remote = new Map<string, { count: number; until: number }>();@@ -356,12 +289,8 @@ test("work reported by another tab lapses", () => {// Two uploads overlapping in the other tab: the first to finish must not// release the gate the second is still holding.test("overlapping remote work is counted, not flagged", () => {- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );assert.match(- api,+ RAG_API,/setRemoteProjectWork\(projectId, from, Math\.max\(0, current \+ delta\)\);/,);@@ -387,29 +316,15 @@ test("overlapping remote work is counted, not flagged", () => {// The composer says the source is gone on click, but it is there until the// DELETE returns, and the probe is invalidated only after that.test("a project delete is work on the project", () => {- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );- assert.match(hook, /noteProjectWork\(removingProjectId, 1\)/);- assert.match(hook, /noteProjectWork\(removingProjectId, -1\)/);+ assert.match(USE_RAG_DOCUMENTS, /noteProjectWork\(removingProjectId, 1\)/);+ assert.match(USE_RAG_DOCUMENTS, /noteProjectWork\(removingProjectId, -1\)/);});// A superseded request clearing the flag would report the list as known while// the request that will publish is still out.test("the newest request owns the loading flag", () => {- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );assert.match(- hook,+ USE_RAG_DOCUMENTS,/if \(refreshSeq\.current === requestId\) \{\s*refreshInFlight\.current = false;\s*setLoading\(false\);/,);});@@ -418,21 +333,14 @@ test("the newest request owns the loading flag", () => {// fires afterwards triggers a quiet refresh, which takes no loading gate: between// the two the composer would report nothing indexing.test("the refresh an invalidation triggers is counted as work", () => {- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );// The listener hands off to the shared loader, which takes the lease for as// long as the list (and its retries) run.assert.match(- hook,+ USE_RAG_DOCUMENTS,/void loadProjectSources\(projectScopeId, \{ quiet: true \}\);/,);assert.match(- hook,+ USE_RAG_DOCUMENTS,/noteProjectWork\(projectId, 1\);\s*try \{[\s\S]{0,900}?\} finally \{\s*noteProjectWork\(projectId, -1\);/,);});@@ -440,17 +348,13 @@ test("the refresh an invalidation triggers is counted as work", () => {// One failed read is not a finished job: a backend restart misses a tick or two// while the durable sync runs on.test("a folder job watcher rides out a failed read", () => {- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );// The catch is inside the loop, so a failure does not reach the finally.assert.match(- api,+ RAG_API,/if \(isRagClientError\(error\)\) break;\s*consecutiveFailures \+= 1;\s*if \(consecutiveFailures >= MAX_FOLDER_JOB_READ_FAILURES\) \{\s*break;/,);// A read that comes back clears the streak, so only a run of them gives up.- assert.match(api, /consecutiveFailures = 0;/);+ assert.match(RAG_API, /consecutiveFailures = 0;/);// The same loop, run against reads that fail and then recover.const reads = ["fail", "fail", "fail", "running", "fail", "completed"];@@ -481,17 +385,13 @@ test("a folder job watcher rides out a failed read", () => {// An upload larger than the deadline sends no delta in between, so without a// renewal the other tab stops counting it and becomes sendable mid-upload.test("work in flight renews the deadline other tabs put on it", () => {- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );- assert.match(api, /const WORK_HEARTBEAT_MS = 45_000;/);+ assert.match(RAG_API, /const WORK_HEARTBEAT_MS = 45_000;/);// The absolute count, not a zero delta: a delta cannot revive an entry the// receiver has already let lapse, which a suspended timer produces.- assert.match(api, /setInterval\(answerWorkQuery, WORK_HEARTBEAT_MS\)/);+ assert.match(RAG_API, /setInterval\(answerWorkQuery, WORK_HEARTBEAT_MS\)/);// Started and stopped by the count itself, so an idle tab posts nothing.assert.match(- api,+ RAG_API,/if \(projectWorkInFlight\.size === 0\) \{\s*if \(workHeartbeat !== null\) \{\s*clearInterval\(workHeartbeat\)/,);@@ -528,15 +428,8 @@ test("work in flight renews the deadline other tabs put on it", () => {// replacement, so nothing reaches the sequence guard that would clear the// flags. The composer reads the list as still unknown and holds every send.test("dropping the scope clears the flags no request will", () => {- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );assert.match(- hook,+ USE_RAG_DOCUMENTS,/if \(scope\) \{[\s\S]{0,300}?: refresh\(\)\);\s*\} else \{[\s\S]{0,300}?refreshInFlight\.current = false;[\s\S]{0,200}?setLoading\(false\);/,);@@ -564,12 +457,8 @@ test("dropping the scope clears the flags no request will", () => {// answer for 30s. The watcher is the only observer once the panel unmounts, so// a send released by it would still read the cached "no sources".test("a folder job drops the cached answer before the gate", () => {- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );assert.match(- api,+ RAG_API,/announceProjectSourcesUpdated\(projectId\);\s*noteProjectWork\(projectId, -1\);/,);});@@ -577,15 +466,11 @@ test("a folder job drops the cached answer before the gate", () => {// BroadcastChannel does not replay, so a tab opened mid-upload hears nothing// until the next delta, which for an upload is its completion.test("a tab that opens mid-upload asks what is already running", () => {- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );// Asked once, on the way in.- assert.match(api, /askForWorkInFlight\(\);\s*return projectChannel;/);- assert.match(api, /postMessage\(\{ kind: "work-query" \}\)/);+ assert.match(RAG_API, /askForWorkInFlight\(\);\s*return projectChannel;/);+ assert.match(RAG_API, /postMessage\(\{ kind: "work-query" \}\)/);assert.match(- api,+ RAG_API,/channel\.postMessage\(\{ kind: "work-state", projectId, count, from: TAB_ID \}\)/,);@@ -616,21 +501,17 @@ test("a tab that opens mid-upload asks what is already running", () => {// project-wide count, the first to finish clears the gate the second is still// holding, and a send goes out mid-upload.test("work is counted per reporting tab, not per project", () => {- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );assert.match(- api,+ RAG_API,/const remoteProjectWork = new Map<\s*string,\s*Map<string, \{ count: number; until: number \}>\s*>\(\);/,);// Every message says who sent it, or the counts cannot be kept apart.- assert.match(api, /kind: "work",\s*projectId,\s*delta,\s*from: TAB_ID,/);+ assert.match(RAG_API, /kind: "work",\s*projectId,\s*delta,\s*from: TAB_ID,/);assert.match(- api,+ RAG_API,/postMessage\(\{ kind: "work-state", projectId, count, from: TAB_ID \}\)/,);- assert.match(api, /if \(entry\.until > now\) remoteCount \+= entry\.count;/);+ assert.match(RAG_API, /if \(entry\.until > now\) remoteCount \+= entry\.count;/);// The reported sequence, per sender.const TTL = 120_000;@@ -668,64 +549,50 @@ test("work is counted per reporting tab, not per project", () => {// The gate is released by the mutation's reconciling refresh, so a refresh that// fails releases it with the composer holding no rows at all.test("a failed reconciling refresh is retried before the gate drops", () => {- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );- assert.match(hook, /const REFRESH_RETRIES = 3;/);+ assert.match(USE_RAG_DOCUMENTS, /const REFRESH_RETRIES = 3;/);assert.match(- hook,+ USE_RAG_DOCUMENTS,/if \(await refresh\(\{ quiet: opts\?\.quiet, silentErrors: !last \}\)\) return;/,);// The release is still guaranteed, retries or not.assert.match(- hook,+ USE_RAG_DOCUMENTS,/\} finally \{\s*noteProjectWork\(projectId, -1\);/,);// And the first list of a project takes the same path, so a transient failure// there does not leave an empty list reporting nothing to wait for.assert.match(- hook,+ USE_RAG_DOCUMENTS,/scope\.type === "project"\s*\? loadProjectSources\(scope\.projectId\)\s*: refresh\(\)/,);// A superseded request reports the list as known: the newer one owns it.- assert.match(hook, /if \(refreshSeq\.current !== requestId\) return true;/);+ assert.match(USE_RAG_DOCUMENTS, /if \(refreshSeq\.current !== requestId\) return true;/);});// The backend creates and starts the job before it answers, so the request// itself is time the project is changing with nothing gating on it.test("a folder mutation takes the gate before its request", () => {- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-linked-folders.ts",- import.meta.url,- ),- "utf8",- );assert.match(- hook,+ USE_LINKED_FOLDERS,/noteProjectWork\(projectWorkScopeId, 1\);\s*try \{\s*return await run\(\);\s*\} finally \{\s*noteProjectWork\(projectWorkScopeId, -1\);/,);// Linking, syncing, rebuilding and unlinking all go through it.assert.match(- hook,+ USE_LINKED_FOLDERS,/withProjectWork\(async \(\) => \{\s*const created = await createLinkedFolder\(/,);assert.match(- hook,+ USE_LINKED_FOLDERS,/withProjectWork\(async \(\) => \{\s*const started =\s*mode === "rebuild"/,);assert.match(- hook,+ USE_LINKED_FOLDERS,/withProjectWork\(\(\) => deleteLinkedFolder\(folderId, removeIndex\)\)/,);// The job's own lease is taken inside the request's, so a scope change// between the response and trackJob cannot leave the project uncounted.- assert.match(hook, /watchStartedJob\(created\.job\.id\);\s*return created;/);- assert.match(hook, /watchStartedJob\(started\.job\.id\);\s*return started;/);+ assert.match(USE_LINKED_FOLDERS, /watchStartedJob\(created\.job\.id\);\s*return created;/);+ assert.match(USE_LINKED_FOLDERS, /watchStartedJob\(started\.job\.id\);\s*return started;/);});// A folder sync outlives the tab that started it. After a reload the watcher is@@ -733,59 +600,44 @@ test("a folder mutation takes the gate before its request", () => {// composer's own list is legitimately empty. Only the Sources panel lists// linked folders, and a project opens on Chats, so the composer has to ask.test("a project composer picks up a folder sync already running", () => {- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );assert.match(- api,+ RAG_API,/export async function reconcileProjectFolderJobs\(\s*projectId: string,\s*\): Promise<void>/,);assert.match(- api,+ RAG_API,/if \(folder\.activeJobId\) \{\s*watchProjectFolderJob\(projectId, folder\.activeJobId\);/,);// Two bars on one project share a look, and a failed look does not count as// an answer, but the project is never closed to a later one.assert.match(- api,+ RAG_API,/if \(\(folderReconcileNotBefore\.get\(projectId\) \?\? 0\) > now\) return;[\s\S]{0,400}?folderReconcileNotBefore\.set\(projectId, now \+ FOLDER_RECONCILE_MIN_GAP_MS\);/,);- assert.match(api, /folderReconcileNotBefore\.delete\(projectId\);/);-- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );- assert.match(hook, /void reconcileProjectFolderJobs\(workScopeId\);/);+ assert.match(RAG_API, /folderReconcileNotBefore\.delete\(projectId\);/);++ assert.match(USE_RAG_DOCUMENTS, /void reconcileProjectFolderJobs\(workScopeId\);/);// The backend enqueues a job per auto-syncing folder on its own timer, so one// look at mount time misses every scan that starts after it.assert.match(- hook,+ USE_RAG_DOCUMENTS,/const reconcile = setInterval\(\(\) => \{\s*void reconcileProjectFolderJobs\(workScopeId\);\s*\}, FOLDER_RECONCILE_INTERVAL_MS\);/,);// The lookup takes a lease before its first await, so the listener that reads// the count has to be registered ahead of it.assert.match(- hook,+ USE_RAG_DOCUMENTS,/window\.addEventListener\(PROJECT_WORK_CHANGED_EVENT, read\);[\s\S]{0,400}?void reconcileProjectFolderJobs\(workScopeId\);/,);- assert.match(hook, /clearInterval\(reconcile\);/);+ assert.match(USE_RAG_DOCUMENTS, /clearInterval\(reconcile\);/);});// Unlinking a folder deletes its job rows, and so does the history prune, so a// detached watcher can poll a job id that will never answer again.test("a folder job watcher stops on an answered 4xx", () => {- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );// Read the two constants the loop is bounded by rather than restating them.const retryBudget = Number(- /const MAX_FOLDER_JOB_READ_FAILURES = (\d+);/.exec(api)?.[1],+ /const MAX_FOLDER_JOB_READ_FAILURES = (\d+);/.exec(RAG_API)?.[1],);assert.ok(retryBudget > 0);@@ -806,24 +658,20 @@ test("a folder job watcher stops on an answered 4xx", () => {// A queued prompt outlives the bar that watched it, and isIndexing() answers only// while that bar is mounted, so the queue has to ask for the project itself.test("a background prompt queue checks the project it will send to", () => {- const thread = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );// The thread-scope check no longer returns early past the project one.assert.doesNotMatch(- thread,+ THREAD,/if \(!item\.target\.usesThreadDocuments\) \{\s*return false;/,);- assert.match(thread, /\? await resolveProjectId\(threadId, undefined, \{/);- assert.match(thread, /composerProjectId: queueProjectId,/);+ assert.match(THREAD, /\? await resolveProjectId\(threadId, undefined, \{/);+ assert.match(THREAD, /composerProjectId: queueProjectId,/);// Work in flight counts as well as rows: an upload has no row until it lands.assert.match(- thread,+ THREAD,/if \(projectWorkCount\(projectId\) > 0\) \{\s*return true;/,);assert.match(- thread,+ THREAD,/const projectDocuments = await listProjectDocuments\(projectId\);\s*return projectDocuments\.some\(indexingDocument\);/,);});@@ -831,41 +679,30 @@ test("a background prompt queue checks the project it will send to", () => {// A queue in a chat with no row yet cannot look its project up: the row is not// there, and the store holds whichever project is on screen when the poll lands.test("a queue in a chat with no row still waits on its project", () => {- const src = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );// Captured at queue start, beside the other snapshots, and never for incognito// (which has no project and no row to reconcile against).assert.match(- src,+ THREAD,/const projectIdAtQueueStart = incognitoAtQueueStart\s*\?\s*null\s*:\s*\(chatStateAtQueueStart\.activeProjectId \?\? null\);/,);- assert.match(src, /getQueueProjectId: \(\) => projectIdAtQueueStart,/);+ assert.match(THREAD, /getQueueProjectId: \(\) => projectIdAtQueueStart,/);// The thread lookup stays the source of truth wherever there is a thread.assert.match(- src,+ THREAD,/const queueProjectId = item\.target\.getQueueProjectId\(\);\s*const projectId = threadId\s*\?\s*await resolveProjectId\(threadId, undefined, \{\s*rethrowReadFailure: true,\s*composerProjectId: queueProjectId,\s*\}\)\s*:\s*queueProjectId;/,);// And the thread-document read is still only made when there is a thread.- assert.match(src, /if \(threadId && item\.target\.usesThreadDocuments\) \{/);+ assert.match(THREAD, /if \(threadId && item\.target\.usesThreadDocuments\) \{/);});// Unlinking deletes the rows whatever this hook shows by the time the DELETE// returns, so an announcement gated on the current scope leaves every other// composer, and every other tab, listing files that are gone.test("unlinking a folder announces for the project it was for", () => {- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-linked-folders.ts",- import.meta.url,- ),- "utf8",- );- assert.match(hook, /const unlinkedProjectId = projectWorkScopeId;/);+ assert.match(USE_LINKED_FOLDERS, /const unlinkedProjectId = projectWorkScopeId;/);// Announced before the scope guard, so navigating mid-DELETE cannot skip it.assert.match(- hook,+ USE_LINKED_FOLDERS,/if \(unlinkedProjectId\) announceProjectSourcesUpdated\(unlinkedProjectId\);\s*if \(currentScopeKey\.current !== operationScopeKey\) return;/,);});@@ -874,52 +711,37 @@ test("unlinking a folder announces for the project it was for", () => {// one files the next attachment into the chat, and nothing re-runs the lookup// until the chat or the open project changes.test("a failed project lookup leaves the scope unresolved", () => {- const bar = readFileSync(- new URL(- "../src/features/rag/components/thread-documents-bar.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(bar, /const PROJECT_LOOKUP_RETRIES = 3;/);+ assert.match(THREAD_DOCUMENTS_BAR, /const PROJECT_LOOKUP_RETRIES = 3;/);assert.match(- bar,+ THREAD_DOCUMENTS_BAR,/for \(let attempt = 0; attempt < PROJECT_LOOKUP_RETRIES; attempt \+= 1\)/,);// Nothing records a null project on the failure path any more.assert.doesNotMatch(- bar,+ THREAD_DOCUMENTS_BAR,/setResolved\(\{ threadId, trigger: activeProjectId, projectId: null \}\);/,);// And unresolved still disables the attach controls.- assert.match(bar, /const projectUnresolved = threadProjectId === undefined;/);- assert.match(bar, /uploading \|\| projectUploading \|\| projectUnresolved/);+ assert.match(THREAD_DOCUMENTS_BAR, /const projectUnresolved = threadProjectId === undefined;/);+ assert.match(THREAD_DOCUMENTS_BAR, /uploading \|\| projectUploading \|\| projectUnresolved/);});// A row the probe could not read is not a chat with no project: answering null// dispatches the queued prompt and bypasses the retry the catch exists for.test("a failed row read holds a queued prompt instead of releasing it", () => {- const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );- assert.match(adapter, /opts\?: \{ rethrowReadFailure\?: boolean;/);+ assert.match(CHAT_ADAPTER, /opts\?: \{ rethrowReadFailure\?: boolean;/);assert.match(- adapter,+ CHAT_ADAPTER,/\} catch \(error\) \{[\s\S]{0,200}?if \(opts\?\.rethrowReadFailure\) throw error;\s*return null;/,);- const thread = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );assert.match(- thread,+ THREAD,/await resolveProjectId\(threadId, undefined, \{\s*rethrowReadFailure: true,/,);// Every other caller keeps failing soft: they run on the send path, where a// read failure must not adopt whichever project is on screen.assert.equal(- (thread.match(/rethrowReadFailure/g) ?? []).length,+ (THREAD.match(/rethrowReadFailure/g) ?? []).length,1,"only the queue probe rethrows",);@@ -928,28 +750,20 @@ test("a failed row read holds a queued prompt instead of releasing it", () => {// A knowledge base replaces every other scope in rag_scope, so a queue scoped to// one cannot be affected by a project upload or a folder sync.test("a knowledge-base queue does not wait on project sources", () => {- const thread = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );assert.match(- thread,+ THREAD,/const usesKnowledgeBaseAtQueueStart =\s*chatStateAtQueueStart\.ragEnabled &&\s*chatStateAtQueueStart\.ragSource\.type === "kb";/,);- assert.match(thread, /usesKnowledgeBase: usesKnowledgeBaseAtQueueStart,/);+ assert.match(THREAD, /usesKnowledgeBase: usesKnowledgeBaseAtQueueStart,/);// Ahead of the project lookup, and after the thread one, which a KB queue// never takes anyway.assert.match(- thread,+ THREAD,/if \(item\.target\.usesKnowledgeBase\) \{\s*return false;\s*\}[\s\S]{0,900}?const projectId = threadId/,);// The exclusivity this relies on, in the adapter that builds the scope.- const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );assert.match(- adapter,+ CHAT_ADAPTER,/ragEnabled && ragSource\.type === "kb"\s*\? \{ kb_id: ragSource\.kbId \}/,);});@@ -958,22 +772,15 @@ test("a knowledge-base queue does not wait on project sources", () => {// lister of the project it started for, so after the user moves on it publishes// that project's documents into the composer showing another one.test("a retry stops when the scope it started for is gone", () => {- const hook = readFileSync(- new URL(- "../src/features/rag/components/use-rag-documents.ts",- import.meta.url,- ),- "utf8",- );- assert.match(hook, /const startedFor = `project:\$\{projectId\}`;/);+ assert.match(USE_RAG_DOCUMENTS, /const startedFor = `project:\$\{projectId\}`;/);assert.match(- hook,+ USE_RAG_DOCUMENTS,/liveScopeKeyRef\.current = scopeKey;\s*\}, \[scopeKey\]\);/,);// Checked after the delay, not before the first attempt: the scope effect that// starts this load runs before the one that records the live scope.assert.match(- hook,+ USE_RAG_DOCUMENTS,/await new Promise\(\(resolve\) =>\s*setTimeout\(resolve, 1000 \* \(attempt \+ 1\)\),\s*\);[\s\S]{0,400}?if \(liveScopeKeyRef\.current !== startedFor\) return;/,);});@@ -982,22 +789,18 @@ test("a retry stops when the scope it started for is gone", () => {// store names whichever project is on screen when the queue polls. Falling back// to it there probes the project the user moved to, not the one being waited on.test("a queue with no row yet falls back to its own project, not the store", () => {- const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );assert.match(- adapter,+ CHAT_ADAPTER,/opts\?: \{ rethrowReadFailure\?: boolean; composerProjectId\?: string \| null \}/,);// The caller's fallback wins over the store, and null from a caller is an// answer rather than a reason to read the store.assert.match(- adapter,+ CHAT_ADAPTER,/const composerProjectId =\s*opts\?\.composerProjectId !== undefined\s*\?\s*opts\.composerProjectId\s*:\s*useChatRuntimeStore\.getState\(\)\.activeProjectId;/,);// The row and the pending map still outrank it.- assert.match(adapter, /if \(thread\) \{\s*composerProjectByPendingThread\.delete\(threadId\);/);+ assert.match(CHAT_ADAPTER, /if \(thread\) \{\s*composerProjectByPendingThread\.delete\(threadId\);/);});// One timer covers the project, so arming it for a full TTL on every update@@ -1005,20 +808,16 @@ test("a queue with no row yet falls back to its own project, not the store", ()// mid-upload, and its stale count then gates a mounted composer until some later// event happens to publish.test("the work timer is armed for the earliest sender deadline", () => {- const api = readFileSync(- new URL("../src/features/rag/api/rag-api.ts", import.meta.url),- "utf8",- );assert.match(- api,+ RAG_API,/let earliest = Number\.POSITIVE_INFINITY;\s*for \(const entry of bySender\.values\(\)\) \{\s*earliest = Math\.min\(earliest, entry\.until\);/,);- assert.match(api, /Math\.max\(0, earliest - Date\.now\(\)\)/);+ assert.match(RAG_API, /Math\.max\(0, earliest - Date\.now\(\)\)/);// Fired, it drops what lapsed and arms for the next deadline rather than// leaving the remaining senders with no wake-up at all.- assert.match(api, /if \(entry\.until <= now\) live\.delete\(sender\);/);+ assert.match(RAG_API, /if \(entry\.until <= now\) live\.delete\(sender\);/);assert.match(- api,+ RAG_API,/publishProjectWorkChanged\(projectId\);\s*armRemoteWorkExpiry\(projectId\);/,);diff --git a/studio/frontend/tests/rag-scope-context-length.test.ts b/studio/frontend/tests/rag-scope-context-length.test.tsindex 93b86bc0c57..4c59a9a7fe9 100644--- a/studio/frontend/tests/rag-scope-context-length.test.ts+++ b/studio/frontend/tests/rag-scope-context-length.test.ts@@ -4,17 +4,13 @@import assert from "node:assert/strict";import test from "node:test";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";-import { ragScopeContextLength } from "../src/features/chat/api/rag-context-length.ts";+import { readText } from "./helpers/kit.ts";+const UNGUARDED_WINDOW = /context_length:\s*\n?\s*runtime\./;const GUARDED_WINDOW = /context_length: ragScopeContextLength\(\{/g;-const read = (path: string) =>- readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");-test("a resident GGUF's window is not reported on a hosted turn", () => {assert.equal(ragScopeContextLength({@@ -57,7 +53,7 @@ test("a local load with no GGUF window falls back to maxSeqLength", () => {});test("every rag_scope window goes through the guard", () => {- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");assert.doesNotMatch(adapter, UNGUARDED_WINDOW);assert.equal((adapter.match(GUARDED_WINDOW) ?? []).length, 2);});@@ -66,12 +62,12 @@ test("every rag_scope window goes through the guard", () => {// the reduced window is what `loadedContextLength` carries. A budget sized off the pin// would inject a document the served window cannot hold.test("the served window is budgeted, never the n_ctx the load asked for", () => {- const helper = read("../src/features/chat/api/rag-context-length.ts");+ const helper = readText("../src/features/chat/api/rag-context-length.ts");assert.doesNotMatch(helper.slice(helper.indexOf("export function")),/loadedCustomContextLength/,);- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");for (const call of adapter.match(/ragScopeContextLength\(\{[^}]*\}\)/g) ?? []) {assert.doesNotMatch(call, /loadedCustomContextLength/);}@@ -83,12 +79,12 @@ test("the served window is budgeted, never the n_ctx the load asked for", () =>test("every runtime field the budget reads survives a queued run", () => {const queuedKeys = new Set((- read("../src/features/chat/utils/queued-chat-run-settings.ts")+ readText("../src/features/chat/utils/queued-chat-run-settings.ts").match(/const QUEUED_SETTING_KEYS = \[([\s\S]*?)\] as const;/)?.[1] ?? "").match(/"([^"]+)"/g)?.map((quoted) => quoted.slice(1, -1)) ?? [],);assert.ok(queuedKeys.size > 0);- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");const calls = adapter.match(/ragScopeContextLength\(\{[^}]*\}\)/g) ?? [];assert.equal(calls.length, 2);for (const call of calls) {diff --git a/studio/frontend/tests/read-aloud-tts-model-row.test.ts b/studio/frontend/tests/read-aloud-tts-model-row.test.tsindex e8ad0df6cef..431ac67d285 100644--- a/studio/frontend/tests/read-aloud-tts-model-row.test.ts+++ b/studio/frontend/tests/read-aloud-tts-model-row.test.ts@@ -2,21 +2,13 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const source = readFileSync(- new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url),- "utf8",-);-const en = readFileSync(- new URL("../src/i18n/locales/en.ts", import.meta.url),- "utf8",-);-const audioSource = readFileSync(- new URL("../src/features/audio/audio-page.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/settings/tabs/voice-tab.tsx");+const en = readSrc("i18n/locales/en.ts");+const audioSource = readSrc("features/audio/audio-page.tsx");test("the studio TTS row offers the Audio page it tells the user to use", () => {// Settings is a modal, so it must close or Audio opens behind it.diff --git a/studio/frontend/tests/reasoning-grid-collapse.test.ts b/studio/frontend/tests/reasoning-grid-collapse.test.tsindex 281dfbf0ae5..dc935c89ac7 100644--- a/studio/frontend/tests/reasoning-grid-collapse.test.ts+++ b/studio/frontend/tests/reasoning-grid-collapse.test.ts@@ -17,19 +17,17 @@// silently stale.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const read = (path: string) =>- readFileSync(new URL(path, import.meta.url), "utf8");+import { readText } from "./helpers/kit.ts";-const UNMEASURED = read("../src/components/ui/unmeasured-collapsible.tsx");-const REASONING = read("../src/components/assistant-ui/reasoning.tsx");-const FLAGS = read("../src/components/assistant-ui/thread-feature-flags.ts");-const SHARED_COLLAPSIBLE = read("../src/components/ui/collapsible.tsx");-const APP_SIDEBAR = read("../src/components/app-sidebar.tsx");-const TOOL_GROUP = read("../src/components/assistant-ui/tool-group.tsx");-const TOOL_FALLBACK = read("../src/components/assistant-ui/tool-fallback.tsx");+const UNMEASURED = readText("../src/components/ui/unmeasured-collapsible.tsx");+const REASONING = readText("../src/components/assistant-ui/reasoning.tsx");+const FLAGS = readText("../src/components/assistant-ui/thread-feature-flags.ts");+const SHARED_COLLAPSIBLE = readText("../src/components/ui/collapsible.tsx");+const APP_SIDEBAR = readText("../src/components/app-sidebar.tsx");+const TOOL_GROUP = readText("../src/components/assistant-ui/tool-group.tsx");+const TOOL_FALLBACK = readText("../src/components/assistant-ui/tool-fallback.tsx");// Comments in these files discuss measurement at length, so an assertion on the raw text would// pass or fail on prose. Only code lines are considered.@@ -206,7 +204,7 @@ test("the height keyframes stay in use everywhere else, because the sidebar list});test("reduced motion is reached by the transition, not bypassed by it", () => {- const indexCss = read("../src/index.css");+ const indexCss = readText("../src/index.css");// Two blankets, the OS media query and the in-app override class. Both force// transition-duration as well as animation-duration, which is what makes a transition-based// collapse honour reduced motion without any new rule.diff --git a/studio/frontend/tests/reload-snapshot.test.ts b/studio/frontend/tests/reload-snapshot.test.tsindex e4cfb945f35..29a5d7427b2 100644--- a/studio/frontend/tests/reload-snapshot.test.ts+++ b/studio/frontend/tests/reload-snapshot.test.ts@@ -2,133 +2,41 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import vm from "node:vm";-const script = readFileSync(- new URL("../public/reload-snapshot.js", import.meta.url),- "utf8",-);-const indexHtml = readFileSync(- new URL("../index.html", import.meta.url),- "utf8",-);-const indexCss = readFileSync(- new URL("../src/index.css", import.meta.url),- "utf8",-);-const rootRouteSource = readFileSync(- new URL("../src/app/routes/__root.tsx", import.meta.url),- "utf8",-);-const runtimeProviderSource = readFileSync(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",-);-const chatPageSource = readFileSync(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",-);-const sharedComposerSource = readFileSync(- new URL("../src/features/chat/shared-composer.tsx", import.meta.url),- "utf8",-);-const imageDropzoneSource = readFileSync(- new URL("../src/components/image-dropzone.tsx", import.meta.url),- "utf8",-);-const attachmentPreviewSource = readFileSync(- new URL(- "../src/components/assistant-ui/attachment-preview.tsx",- import.meta.url,- ),- "utf8",-);--const attachmentSource = readFileSync(- new URL("../src/components/assistant-ui/attachment.tsx", import.meta.url),- "utf8",-);-const imagesPageSource = readFileSync(- new URL("../src/features/images/images-page.tsx", import.meta.url),- "utf8",-);-const videoPageSource = readFileSync(- new URL("../src/features/video/video-page.tsx", import.meta.url),- "utf8",-);-const audioPageSource = readFileSync(- new URL("../src/features/audio/audio-page.tsx", import.meta.url),- "utf8",-);-const hubPageSource = readFileSync(- new URL("../src/features/hub/hub-page.tsx", import.meta.url),- "utf8",-);-const referencePickerSource = readFileSync(- new URL("../src/features/video/reference-picker.tsx", import.meta.url),- "utf8",-);--const unstructuredDropZoneSource = readFileSync(- new URL(- "../src/features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsx",- import.meta.url,- ),- "utf8",-);--const projectsPageSource = readFileSync(- new URL("../src/features/chat/projects-page.tsx", import.meta.url),- "utf8",-);--const seedDialogSource = readFileSync(- new URL(- "../src/features/recipe-studio/dialogs/seed/seed-dialog.tsx",- import.meta.url,- ),- "utf8",-);--const projectSourceDropzoneSource = readFileSync(- new URL(- "../src/features/rag/components/project-source-dropzone.tsx",- import.meta.url,- ),- "utf8",-);-const dataRecipesPageSource = readFileSync(- new URL(- "../src/features/data-recipes/pages/data-recipes-page.tsx",- import.meta.url,- ),- "utf8",-);-const editRecipePageSource = readFileSync(- new URL(- "../src/features/data-recipes/pages/edit-recipe-page.tsx",- import.meta.url,- ),- "utf8",-);-const exportPageSource = readFileSync(- new URL("../src/features/export/export-page.tsx", import.meta.url),- "utf8",-);-const studioPageSource = readFileSync(- new URL("../src/features/studio/studio-page.tsx", import.meta.url),- "utf8",-);-const apiMonitorPageSource = readFileSync(- new URL("../src/features/api-monitor/api-monitor-page.tsx", import.meta.url),- "utf8",-);-const authFormSource = readFileSync(- new URL("../src/features/auth/components/auth-form.tsx", import.meta.url),- "utf8",-);+import { readSrc, readText } from "./helpers/kit.ts";++const script = readText("../public/reload-snapshot.js");+const indexHtml = readText("../index.html");+const indexCss = readSrc("index.css");+const rootRouteSource = readSrc("app/routes/__root.tsx");+const runtimeProviderSource = readSrc("features/chat/runtime-provider.tsx");+const chatPageSource = readSrc("features/chat/chat-page.tsx");+const sharedComposerSource = readSrc("features/chat/shared-composer.tsx");+const imageDropzoneSource = readSrc("components/image-dropzone.tsx");+const attachmentPreviewSource = readSrc("components/assistant-ui/attachment-preview.tsx");++const attachmentSource = readSrc("components/assistant-ui/attachment.tsx");+const imagesPageSource = readSrc("features/images/images-page.tsx");+const videoPageSource = readSrc("features/video/video-page.tsx");+const audioPageSource = readSrc("features/audio/audio-page.tsx");+const hubPageSource = readSrc("features/hub/hub-page.tsx");+const referencePickerSource = readSrc("features/video/reference-picker.tsx");++const unstructuredDropZoneSource = readSrc("features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsx");++const projectsPageSource = readSrc("features/chat/projects-page.tsx");++const seedDialogSource = readSrc("features/recipe-studio/dialogs/seed/seed-dialog.tsx");++const projectSourceDropzoneSource = readSrc("features/rag/components/project-source-dropzone.tsx");+const dataRecipesPageSource = readSrc("features/data-recipes/pages/data-recipes-page.tsx");+const editRecipePageSource = readSrc("features/data-recipes/pages/edit-recipe-page.tsx");+const exportPageSource = readSrc("features/export/export-page.tsx");+const studioPageSource = readSrc("features/studio/studio-page.tsx");+const apiMonitorPageSource = readSrc("features/api-monitor/api-monitor-page.tsx");+const authFormSource = readSrc("features/auth/components/auth-form.tsx");type Listener = (event: Record<string, unknown>) => void;diff --git a/studio/frontend/tests/research-activity-follow-loop.test.ts b/studio/frontend/tests/research-activity-follow-loop.test.tsindex a8634eca485..a2d8d8413a1 100644--- a/studio/frontend/tests/research-activity-follow-loop.test.ts+++ b/studio/frontend/tests/research-activity-follow-loop.test.ts@@ -7,17 +7,14 @@// shape the measurements were taken against, as drag-costs-no-render.test.ts does for panels.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";+import { readSrc } from "./helpers/kit.ts";++const RESEARCH_ACTIVITY_PANEL = readSrc("features/chat/components/research-activity-panel.tsx");+function followLoopSource(): string {- const text = readFileSync(- new URL(- "../src/features/chat/components/research-activity-panel.tsx",- import.meta.url,- ),- "utf8",- );+ const text = readSrc("features/chat/components/research-activity-panel.tsx");const start = text.indexOf("function useResearchActivityScroll");assert.ok(start >= 0, "useResearchActivityScroll is gone");const end = text.indexOf("\n}", text.indexOf("}, [runId];".replace(";", ");")));@@ -60,14 +57,7 @@ test("detach cancels every pending follow step", () => {});test("the pinned threshold stays at 2px, not 1", () => {- const text = readFileSync(- new URL(- "../src/features/chat/components/research-activity-panel.tsx",- import.meta.url,- ),- "utf8",- );// HiDPI subpixel rounding leaves a fractional gap; at 1px the loop never reads as pinned and// never exits, the configuration the freeze was reported on.- assert.match(text, /const ACTIVITY_PINNED_THRESHOLD_PX = 2;/);+ assert.match(RESEARCH_ACTIVITY_PANEL, /const ACTIVITY_PINNED_THRESHOLD_PX = 2;/);});diff --git a/studio/frontend/tests/research-activity-visuals.test.ts b/studio/frontend/tests/research-activity-visuals.test.tsindex 58d7ab4c31c..ccc933bc75a 100644--- a/studio/frontend/tests/research-activity-visuals.test.ts+++ b/studio/frontend/tests/research-activity-visuals.test.ts@@ -2,16 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const source = readFileSync(- new URL(- "../src/features/chat/components/research-activity-panel.tsx",- import.meta.url,- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/chat/components/research-activity-panel.tsx");function between(start: string, end: string): string {const startIndex = source.indexOf(start);diff --git a/studio/frontend/tests/research-render-budget.test.ts b/studio/frontend/tests/research-render-budget.test.tsindex 6319dd2603b..f2dd3ceca46 100644--- a/studio/frontend/tests/research-render-budget.test.ts+++ b/studio/frontend/tests/research-render-budget.test.ts@@ -7,14 +7,11 @@// the cheap path, assert the expensive one is gone.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { markdownPluginNeeds, MAX_HIGHLIGHT_CHARS } from "../src/lib/markdown-plugins.ts";-function source(path: string): string {- return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");-}+import { readSrc } from "./helpers/kit.ts";test("no research subscriber selects the whole run object", () => {// Each re-rendered its subtree on every streamed delta; thread.tsx's useThreadResearchActive@@ -23,7 +20,7 @@ test("no research subscriber selects the whole run object", () => {"features/chat/chat-page.tsx","components/assistant-ui/thread.tsx",]) {- const text = source(path);+ const text = readSrc(path);assert.doesNotMatch(text,/state\.sessions\[[^\]]+\]\?\.run;/,@@ -38,24 +35,24 @@ test("no research subscriber selects the whole run object", () => {});test("chat-page derives the research pane from strings", () => {- const page = source("features/chat/chat-page.tsx");+ const page = readSrc("features/chat/chat-page.tsx");assert.match(page, /state\.sessions\[openResearchRunId\]\?\.run\.threadId/);assert.match(page, /state\.sessions\[latestResearchRunId\]\?\.run\.status/);});test("Thread is memoized", () => {- const thread = source("components/assistant-ui/thread.tsx");+ const thread = readSrc("components/assistant-ui/thread.tsx");assert.match(thread, /export const Thread: FC<\{[^}]*\}> = memo\(/s);assert.match(thread, /Thread\.displayName = "Thread";/);});test("the report renderer is deferred and its plugins are conditional", () => {- const preview = source("components/markdown/markdown-preview.tsx");+ const preview = readSrc("components/markdown/markdown-preview.tsx");assert.match(preview, /markdownPluginNeeds\(markdown\)/);assert.match(preview, /scheduleIdleTask\(\(\) => setReadyMarkdown\(markdown\), 200\)/);// The old path: all three plugins, always, in one synchronous commit.assert.doesNotMatch(preview, /const MARKDOWN_PLUGINS = \{ code, math, mermaid \}/);- const message = source("features/chat/components/research-message.tsx");+ const message = readSrc("features/chat/components/research-message.tsx");assert.match(message, /markdown=\{run\.report\}[\s\S]*?defer=\{true\}/);});@@ -63,7 +60,7 @@ test("deferred readiness belongs to a markdown value, not to the component", ()// Blanking readiness from a passive effect lands one commit late, so the parse is paid twice.// Measured on a 202KB report: a wasted 576ms parse, then a second one, ~1.11s blocked against// ~0.66s once readiness is derived during render.- const preview = source("components/markdown/markdown-preview.tsx");+ const preview = readSrc("components/markdown/markdown-preview.tsx");assert.match(preview, /const ready = !defer \|\| readyMarkdown === markdown;/);assert.match(preview, /scheduleIdleTask\(\(\) => setReadyMarkdown\(markdown\), 200\)/);assert.doesNotMatch(preview, /useState\(!defer\)/);@@ -88,7 +85,7 @@ test("plugin needs follow the document", () => {// must change with it - and "costs $5 and $10" is why a balanced-pair regex is not the answer.assert.equal(markdownPluginNeeds("the area is $x^2$ per unit").math, false);assert.match(- source("components/markdown/markdown-preview.tsx"),+ readSrc("components/markdown/markdown-preview.tsx"),/import \{ math \} from "@streamdown\/math";/,);assert.equal(markdownPluginNeeds("```mermaid\ngraph TD;\n```").mermaid, true);@@ -116,7 +113,7 @@ test("highlighting is capped, and the cap is one constant", () => {"components/assistant-ui/tool-code-cell.tsx","components/assistant-ui/attachment-preview.tsx",]) {- const cell = source(path);+ const cell = readSrc(path);assert.match(cell, imports, path);assert.doesNotMatch(cell, /const MAX_HIGHLIGHT_CHARS = /, path);}diff --git a/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts b/studio/frontend/tests/resident-config-match-accelerator-matrix.test.tsindex a72843b0a3c..70c688c7e06 100644--- a/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts+++ b/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts@@ -20,12 +20,10 @@*/import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import type { PerModelConfig } from "../src/features/model-picker/model-config/per-model-config.ts";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();const { residentRuntimeMatchesConfig: matchesWithStanding } = await import(@@ -436,15 +434,7 @@ test("an empty pinned pool is Automatic, not a demand for no GPUs", () => {test("every PerModelConfig field is either compared or deliberately excluded", () => {// A new setting not classified here is one an adopted pick would drop silently.- const source = readFileSync(- fileURLToPath(- new URL(- "../src/features/model-picker/model-config/per-model-config.ts",- import.meta.url,- ),- ),- "utf8",- );+ const source = readSrc("features/model-picker/model-config/per-model-config.ts");const body = source.slice(source.indexOf("export interface PerModelConfig {"),source.indexOf("export const DEFAULT_PER_MODEL_CONFIG"),diff --git a/studio/frontend/tests/resident-config-match.test.ts b/studio/frontend/tests/resident-config-match.test.tsindex 725247c990b..2d5f9c381a4 100644--- a/studio/frontend/tests/resident-config-match.test.ts+++ b/studio/frontend/tests/resident-config-match.test.ts@@ -11,11 +11,11 @@*/import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";++const USE_CHAT_MODEL_RUNTIME = readSrc("features/chat/hooks/use-chat-model-runtime.ts");registerBundlerResolver();const { residentRuntimeMatchesConfig, residentSpeculativeNeedsRepair } =@@ -367,19 +367,10 @@ test("one differing field among many agreeing ones is still a reload", () => {* carries forceReload, and a native pick carries a lease this path cannot adopt.*/test("selectModel weighs the config and the lease before confirming a reload", () => {- const source = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- ),- "utf8",- );// Newline-tolerant: the call wraps once its argument list grows.- const configCheck = source.search(/residentRuntimeMatchesConfig\(\s*status/);- const identityCheck = source.indexOf("residentModelMatchesPick(status");- const confirmPrompt = source.indexOf(+ const configCheck = USE_CHAT_MODEL_RUNTIME.search(/residentRuntimeMatchesConfig\(\s*status/);+ const identityCheck = USE_CHAT_MODEL_RUNTIME.indexOf("residentModelMatchesPick(status");+ const confirmPrompt = USE_CHAT_MODEL_RUNTIME.indexOf("await confirmStopRunningChatsIfNeeded(",);assert.ok(identityCheck > 0, "selectModel no longer checks residency");@@ -394,7 +385,7 @@ test("selectModel weighs the config and the lease before confirming a reload", (// written only by a completed load, so this path must not adopt one.// Widened as the gate's preamble grows: what matters is that the guard opens the block// the identity check sits in, not how many reads it makes first.- const guard = source.lastIndexOf(+ const guard = USE_CHAT_MODEL_RUNTIME.lastIndexOf("if (!forceReload && !nativePathToken) {",identityCheck,);@@ -1546,18 +1537,9 @@ test("a healthy runtime and a pick wanting no drafter both stay on the shortcut"* against the live store rather than in this leaf.*/test("the resident shortcut keeps the picked model's own sequence cap", () => {- const source = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- ),- "utf8",- );- const configCheck = source.search(/residentRuntimeMatchesConfig\(\s*status/);- const rollback = source.indexOf("restorePreviousConfig();", configCheck);- const reapply = source.indexOf("pickedMaxSeqLength", configCheck);+ const configCheck = USE_CHAT_MODEL_RUNTIME.search(/residentRuntimeMatchesConfig\(\s*status/);+ const rollback = USE_CHAT_MODEL_RUNTIME.indexOf("restorePreviousConfig();", configCheck);+ const reapply = USE_CHAT_MODEL_RUNTIME.indexOf("pickedMaxSeqLength", configCheck);assert.ok(rollback > 0,"the shortcut no longer rolls the staged config back",@@ -1566,14 +1548,14 @@ test("the resident shortcut keeps the picked model's own sequence cap", () => {reapply > rollback,"the shortcut leaves the outgoing model's maxSeqLength in place",);- const confirmPrompt = source.indexOf(+ const confirmPrompt = USE_CHAT_MODEL_RUNTIME.indexOf("await confirmStopRunningChatsIfNeeded(",);assert.ok(reapply < confirmPrompt, "the re-apply escaped the shortcut");// An absent cap is not "leave it alone": applyPerModelConfigToRuntime resolves it to the// default, so a pick without one must land on the default rather than the outgoing cap.assert.match(- source.slice(reapply, reapply + 260),+ USE_CHAT_MODEL_RUNTIME.slice(reapply, reapply + 260),/\?\?\s*defaultInferenceParams\.maxSeqLength/,"an absent cap no longer resolves to the default",);@@ -1588,21 +1570,12 @@ test("the resident shortcut keeps the picked model's own sequence cap", () => {* is a silent loss rather than one extra reload.*/test("an outstanding audio probe keeps the shortcut from skipping the load", () => {- const source = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- ),- "utf8",- );- const identity = source.search(/residentModelMatchesPick\(\s*status/);- const probe = source.indexOf("status.audio_probe_pending !== true", identity);+ const identity = USE_CHAT_MODEL_RUNTIME.search(/residentModelMatchesPick\(\s*status/);+ const probe = USE_CHAT_MODEL_RUNTIME.indexOf("status.audio_probe_pending !== true", identity);// The caller tells the repair check whether the load carries a gguf_path, since the// route derives that from the identifier and the drafter retry is guarded on it.assert.match(- source,+ USE_CHAT_MODEL_RUNTIME,/\(loadPath \?\? modelId\)\.toLowerCase\(\)\.endsWith\("\.gguf"\)/,"the repair check no longer knows whether the pick sends a path",);@@ -1611,10 +1584,10 @@ test("an outstanding audio probe keeps the shortcut from skipping the load", ()"the shortcut adopts a model whose audio probe never finished",);// Inside the verdict, so the re-read before adopting judges it again.- const decision = source.indexOf("const confirmedStatus", identity);+ const decision = USE_CHAT_MODEL_RUNTIME.indexOf("const confirmedStatus", identity);assert.ok(probe < decision, "the probe check escaped the residency verdict");// Only an explicit true declines: a backend too old to report it behaves as before.- assert.match(source.slice(probe - 40, probe + 40), /!== true/);+ assert.match(USE_CHAT_MODEL_RUNTIME.slice(probe - 40, probe + 40), /!== true/);});/**@@ -1627,22 +1600,13 @@ test("an outstanding audio probe keeps the shortcut from skipping the load", ()* would leave the picker naming this model while prompts went to the one now loaded.*/test("the shortcut re-reads and re-judges the status before adopting", () => {- const source = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- ),- "utf8",- );// The verdict is a named predicate, so it can be applied to more than one status.assert.match(- source,+ USE_CHAT_MODEL_RUNTIME,/const adoptable = \(status: InferenceStatusResponse\) =>\s*\(status\.loading\?\.length \?\? 0\) === 0 &&/,"the residency verdict is no longer callable against a second status",);- const decision = source.search(+ const decision = USE_CHAT_MODEL_RUNTIME.search(/const confirmedStatus = await getInferenceStatus\(\)/,);assert.ok(@@ -1650,28 +1614,28 @@ test("the shortcut re-reads and re-judges the status before adopting", () => {"the shortcut adopts the status it opened with, across every await above it",);assert.match(- source.slice(decision, decision + 200),+ USE_CHAT_MODEL_RUNTIME.slice(decision, decision + 200),/if \(confirmedStatus && adoptable\(confirmedStatus\)\)/,"the re-read is not judged, only fetched",);// And the adopted status is the fresh one, not the one the window opened with.- const adopt = source.indexOf("applyActiveModelStatusToStore(", decision);+ const adopt = USE_CHAT_MODEL_RUNTIME.indexOf("applyActiveModelStatusToStore(", decision);assert.match(- source.slice(adopt, adopt + 60),+ USE_CHAT_MODEL_RUNTIME.slice(adopt, adopt + 60),/applyActiveModelStatusToStore\(confirmedStatus/,);// The pick's own GPU selection survives the hydration, which would otherwise widen it// back: the backend records the incoming pool when it adopts on a fitted subset, and// skipping /load skips that, so the status still names the GPUs the user removed.- const restore = source.indexOf("selectedGpuIds: picked", decision);- const hydrate = source.indexOf("applyActiveModelStatusToStore(", decision);+ const restore = USE_CHAT_MODEL_RUNTIME.indexOf("selectedGpuIds: picked", decision);+ const hydrate = USE_CHAT_MODEL_RUNTIME.indexOf("applyActiveModelStatusToStore(", decision);assert.ok(restore > hydrate,"the adopted pick no longer keeps its own GPU selection",);// A failed re-read must not adopt either: falling out of the block reaches /load.assert.ok(- source.indexOf("await getInferenceStatus().catch(() => null)", decision) ===+ USE_CHAT_MODEL_RUNTIME.indexOf("await getInferenceStatus().catch(() => null)", decision) ===decision + "const confirmedStatus = ".length,"the re-read no longer tolerates a failed status",);@@ -1686,29 +1650,20 @@ test("the shortcut re-reads and re-judges the status before adopting", () => {* client had left running.*/test("with no saved config the gate compares what the load would send", () => {- const source = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- ),- "utf8",- );- const configCheck = source.search(/residentRuntimeMatchesConfig\(\s*status/);+ const configCheck = USE_CHAT_MODEL_RUNTIME.search(/residentRuntimeMatchesConfig\(\s*status/);assert.ok(configCheck > 0 &&- /const comparedConfig =\s*\n\s*pendingConfig \?\?/.test(source),+ /const comparedConfig =\s*\n\s*pendingConfig \?\?/.test(USE_CHAT_MODEL_RUNTIME),"the gate takes an absent config as a wildcard again",);// Both doors, and the reset one must not be the live store.assert.match(- source,+ USE_CHAT_MODEL_RUNTIME,/resetsPerModelSettings\s*\?\s*\{\s*\n\s*\.\.\.DEFAULT_PER_MODEL_CONFIG/,"a model switch no longer compares against the defaults it would send",);assert.match(- source,+ USE_CHAT_MODEL_RUNTIME,/: currentRuntimePerModelConfig\(\)\)/,"a re-pick that switches nothing no longer compares against the live runtime",);@@ -1720,15 +1675,7 @@ test("adopting reseeds the slot and batch controls the rollback left behind", ()// kept them: the adopted model could run 4 slots while the control showed the outgoing// count, and the next Apply saved that over it. Reachable coming back from an external// provider to a still-resident GGUF, which is the case this shortcut began as.- const hydrator = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/lib/apply-inference-status-to-store.ts",- import.meta.url,- ),- ),- "utf8",- );+ const hydrator = readSrc("features/chat/lib/apply-inference-status-to-store.ts");assert.match(hydrator.replace(/\s+/g, " "),/const slotsModelChanged = hydratingExistingModel;/,@@ -1736,31 +1683,13 @@ test("adopting reseeds the slot and batch controls the rollback left behind", ()// Every other load-param seed at that call site already keys off the same flag, so the// suppression is gone rather than merely unused.assert.equal(hydrator.includes("readoptingSameModel"), false);- const source = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- ),- "utf8",- );- assert.equal(source.includes("readoptingSameModel"), false);+ assert.equal(USE_CHAT_MODEL_RUNTIME.includes("readoptingSameModel"), false);});/** The repair window is only useful if it is consulted before the reload is decided. */test("selectModel asks about a repairable drafter before adopting", () => {- const source = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- ),- "utf8",- );- const repairCheck = source.indexOf("residentSpeculativeNeedsRepair(");- const confirmPrompt = source.indexOf(+ const repairCheck = USE_CHAT_MODEL_RUNTIME.indexOf("residentSpeculativeNeedsRepair(");+ const confirmPrompt = USE_CHAT_MODEL_RUNTIME.indexOf("await confirmStopRunningChatsIfNeeded(",);assert.ok(@@ -1781,13 +1710,7 @@ test("selectModel asks about a repairable drafter before adopting", () => {* reads it -- but evaluated, so this asserts behavior rather than spelling.*/test("the speculative normalizer reads llama.cpp's disable spellings as off", () => {- const store = readFileSync(- new URL(- "../src/features/chat/stores/chat-runtime-store.ts",- import.meta.url,- ),- "utf8",- );+ const store = readSrc("features/chat/stores/chat-runtime-store.ts");const start = store.indexOf("export function normalizeSpeculativeType");assert.ok(start > 0, "normalizeSpeculativeType moved; follow it here");const source = storediff --git a/studio/frontend/tests/resident-model-match.test.ts b/studio/frontend/tests/resident-model-match.test.tsindex 30d9bd37f16..eff9789545f 100644--- a/studio/frontend/tests/resident-model-match.test.ts+++ b/studio/frontend/tests/resident-model-match.test.ts@@ -9,11 +9,9 @@*/import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();const { residentModelMatchesPick } = await import(@@ -139,15 +137,7 @@ test("nothing resident matches nothing", () => {* dialog is what the report is about, and /load answers already_loaded without stopping* anything. */test("selectModel checks residency before prompting to stop running chats", () => {- const source = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/hooks/use-chat-model-runtime.ts",- import.meta.url,- ),- ),- "utf8",- );+ const source = readSrc("features/chat/hooks/use-chat-model-runtime.ts");const residencyCheck = source.indexOf("residentModelMatchesPick(status",);diff --git a/studio/frontend/tests/resources-shared-memory-display.test.ts b/studio/frontend/tests/resources-shared-memory-display.test.tsindex b39d9a42484..ef78573900e 100644--- a/studio/frontend/tests/resources-shared-memory-display.test.ts+++ b/studio/frontend/tests/resources-shared-memory-display.test.ts@@ -2,13 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const resourcesTab = readFileSync(- new URL("../src/features/settings/tabs/resources-tab.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const resourcesTab = readSrc("features/settings/tabs/resources-tab.tsx");test("Resources separates dedicated VRAM from shared GPU memory", () => {assert.match(resourcesTab, /gpuMemoryTotalsGb\(devices\)/);diff --git a/studio/frontend/tests/rolling-context-window.test.ts b/studio/frontend/tests/rolling-context-window.test.tsindex 89c3a31fe99..bc202abc2f8 100644--- a/studio/frontend/tests/rolling-context-window.test.ts+++ b/studio/frontend/tests/rolling-context-window.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {type ContextTruncation,@@ -11,14 +10,14 @@ import {promptWasShortened,} from "../src/features/chat/utils/context-truncation.ts";-const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",-);-const transport = readFileSync(- new URL("../src/features/chat/api/chat-api.ts", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const COMPACTION_NOTICE = readSrc("components/assistant-ui/compaction-notice.tsx");+const THREAD = readSrc("components/assistant-ui/thread.tsx");+const CHAT_ADAPTER = readSrc("features/chat/api/chat-adapter.ts");++const adapter = readSrc("features/chat/api/chat-adapter.ts");+const transport = readSrc("features/chat/api/chat-api.ts");test("local chat opts into the rolling context policy", () => {assert.match(adapter, /isGguf === true/);@@ -34,10 +33,7 @@ test("the transport preserves standard chunks with context metadata", () => {});test("durable replay persists context-truncation metadata", () => {- const runtimeProvider = readFileSync(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",- );+ const runtimeProvider = readSrc("features/chat/runtime-provider.tsx");assert.match(runtimeProvider, /contextTruncation: mergeContextTruncation\(/);assert.match(runtimeProvider, /generationChunkCount/);assert.match(adapter, /generationFirstChunkAt/);@@ -148,15 +144,8 @@ test("a rescued turn cannot silence the compactions that follow it", () => {});test("the notice and the toast read the same predicate as the boundary", () => {- const notice = readFileSync(- new URL(- "../src/components/assistant-ui/compaction-notice.tsx",- import.meta.url,- ),- "utf8",- );- assert.match(notice, /promptWasShortened\(truncation\)/);- assert.doesNotMatch(notice, /truncation\?\.fits/);+ assert.match(COMPACTION_NOTICE, /promptWasShortened\(truncation\)/);+ assert.doesNotMatch(COMPACTION_NOTICE, /truncation\?\.fits/);assert.match(adapter, /promptWasShortened\(chunk\.context_truncated\)/);});@@ -222,34 +211,22 @@ test("compaction counts accumulate and stay absent on a plain rolling window", (});test("the compaction notice renders from persisted metadata, not from a message", () => {- const notice = readFileSync(- new URL("../src/components/assistant-ui/compaction-notice.tsx", import.meta.url),- "utf8",- );- const thread = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );// Read off metadata.custom so it can never become part of the conversation.- assert.match(thread, /custom\?\.contextTruncation/);- assert.match(thread, /<CompactionNotice truncation=\{contextTruncation\}/);- assert.match(notice, /This conversation got long, so it was compacted/);+ assert.match(THREAD, /custom\?\.contextTruncation/);+ assert.match(THREAD, /<CompactionNotice truncation=\{contextTruncation\}/);+ assert.match(COMPACTION_NOTICE, /This conversation got long, so it was compacted/);});test("the compaction notice is gated on the eviction boundary MOVING", () => {- const thread = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );// Every request after the window fills runs the fit, so "this turn compacted" puts a// notice on every reply. The trigger is dropped_messages rising above the last turn// that reported it: more of the conversation actually leaving the context.- assert.match(thread, /const showsNotice = useAuiState/);- assert.match(thread, /contextTruncation && showsNotice && !isEditing/);- assert.match(thread, /dropped > previousDropped/);+ assert.match(THREAD, /const showsNotice = useAuiState/);+ assert.match(THREAD, /contextTruncation && showsNotice && !isEditing/);+ assert.match(THREAD, /dropped > previousDropped/);// Walked in order, not against the preceding message: turns between two moves report// the same count and must not reset the baseline.- assert.match(thread, /for \(const message of thread\.messages\)/);+ assert.match(THREAD, /for \(const message of thread\.messages\)/);});// The gate is a pure function of the thread's persisted truncation counts, so it can be@@ -302,26 +279,15 @@ const functionBody = (source: string, name: string): string => {};test("the notice is a NOTICE, never part of the conversation", () => {- const thread = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );- const adapter = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );- const exporter = readFileSync(- new URL("../src/features/chat/utils/conversation-markdown-export.ts", import.meta.url),- "utf8",- );+ const exporter = readSrc("features/chat/utils/conversation-markdown-export.ts");// 1. A sibling of the rendered content parts, not one of them: inside// MessagePrimitive.Parts everything that walks parts would pick it up.- const noticeAt = thread.indexOf("<CompactionNotice");- const partsAt = thread.indexOf("<MessagePrimitive.Parts", noticeAt);+ const noticeAt = THREAD.indexOf("<CompactionNotice");+ const partsAt = THREAD.indexOf("<MessagePrimitive.Parts", noticeAt);assert.ok(noticeAt > 0 && partsAt > noticeAt);assert.ok(- !/<MessagePrimitive\.Parts[^>]*>[\s\S]*<CompactionNotice/.test(thread),+ !/<MessagePrimitive\.Parts[^>]*>[\s\S]*<CompactionNotice/.test(THREAD),"the notice must not be rendered inside the message's content parts",);@@ -329,7 +295,7 @@ test("the notice is a NOTICE, never part of the conversation", () => {// function bodies: slicing to end-of-file also catches the streaming handler,// which reads contextTruncation legitimately on the way IN.for (const name of ["toOpenAIMessages", "serializeAssistantReplayMessages"]) {- const body = functionBody(adapter, name);+ const body = functionBody(CHAT_ADAPTER, name);assert.ok(body.length > 0, `${name} not found`);assert.ok(!body.includes("contextTruncation"),@@ -342,7 +308,7 @@ test("the notice is a NOTICE, never part of the conversation", () => {assert.ok(!exporter.includes("compacted"));// 4. Suppressed while editing, so it cannot be saved back as message text.- assert.match(thread, /contextTruncation && showsNotice && !isEditing/);+ assert.match(THREAD, /contextTruncation && showsNotice && !isEditing/);});test("an irreducible fit reports a diagnosis, and it is dropped once something fits", () => {@@ -381,57 +347,41 @@ test("an irreducible fit reports a diagnosis, and it is dropped once something f});test("the too-long advice depends on WHICH part does not fit", () => {- const adapterSource = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );// Telling someone to shorten the conversation is a dead end when the history has// already been evicted and the single message is what overflows.- assert.match(adapterSource, /contextTruncation\?\.fits === false/);- assert.match(adapterSource, /shortening the conversation will not help/);+ assert.match(CHAT_ADAPTER, /contextTruncation\?\.fits === false/);+ assert.match(CHAT_ADAPTER, /shortening the conversation will not help/);// Matching the wire field name would pin nothing: after the floor fix its only// occurrence in that file is prose in a comment.- assert.match(adapterSource, /latestTurnOwnTokens\(irreducible\)/);+ assert.match(CHAT_ADAPTER, /latestTurnOwnTokens\(irreducible\)/);});test("a fits:false diagnosis is not a compaction", () => {- const source = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );// The fitter returned the ORIGINAL messages with dropped_messages 0, so "older turns// were removed" is untrue, and toasting it burns the once-per-thread flag. Asserted on// the predicate rather than the literal expression, so it survives a rewording.- assert.match(source, /const reallyCompacted = promptWasShortened\(/);+ assert.match(CHAT_ADAPTER, /const reallyCompacted = promptWasShortened\(/);assert.equal(promptWasShortened({ dropped_messages: 0, fits: false }), false);});test("the advice depends on WHOSE turn does not fit", () => {- const source = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );// A tool loop refits with the tool result appended, so the offending turn is often// output the user never wrote and cannot edit, leaving no remedy.- assert.match(source, /latest_turn_role/);- assert.match(source, /const userCanShortenIt =/);- assert.match(source, /The last tool result is/);+ assert.match(CHAT_ADAPTER, /latest_turn_role/);+ assert.match(CHAT_ADAPTER, /const userCanShortenIt =/);+ assert.match(CHAT_ADAPTER, /The last tool result is/);// The user-authored case keeps its advice, and an older server that sends no role// still gets it (the default is "user").- assert.match(source, /latest_turn_role \?\? "user"/);- assert.match(source, /Shorten this message/);+ assert.match(CHAT_ADAPTER, /latest_turn_role \?\? "user"/);+ assert.match(CHAT_ADAPTER, /Shorten this message/);});test("the too-long check uses the prompt budget, not the raw window", () => {- const source = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",- );// The fit reserves up to a quarter of the window for the reply, so a 3,500-token// message cannot fit a 4,096-token context. The raw window would blame the// conversation and send the user to a new chat that fails identically.- assert.match(source, /irreducible\?\.prompt_target \?\? irreducible\?\.context_length/);+ assert.match(CHAT_ADAPTER, /irreducible\?\.prompt_target \?\? irreducible\?\.context_length/);// Still measured against the budget, but through the helper that takes the prompt's// shared floor off the turn first.- assert.match(source, /latestTurnIsTheProblem\(\s*irreducible,\s*budget,?\s*\)/);+ assert.match(CHAT_ADAPTER, /latestTurnIsTheProblem\(\s*irreducible,\s*budget,?\s*\)/);});diff --git a/studio/frontend/tests/sandbox-image-lifecycle.test.ts b/studio/frontend/tests/sandbox-image-lifecycle.test.tsindex 61a7e0c279a..4a5d53beca0 100644--- a/studio/frontend/tests/sandbox-image-lifecycle.test.ts+++ b/studio/frontend/tests/sandbox-image-lifecycle.test.ts@@ -2,21 +2,16 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { runInNewContext } from "node:vm";import ts from "typescript";+import { readSrc } from "./helpers/kit.ts";+type Load = { status: string; url?: string };function imageHook() {- const source = readFileSync(- new URL(- "../src/components/assistant-ui/use-sandbox-image.ts",- import.meta.url,- ),- "utf8",- );+ const source = readSrc("components/assistant-ui/use-sandbox-image.ts");const code = ts.transpileModule(source.replace(/^import .*$/gm, ""), {compilerOptions: {module: ts.ModuleKind.CommonJS,diff --git a/studio/frontend/tests/scan-folder-status.test.ts b/studio/frontend/tests/scan-folder-status.test.tsindex 5c485d53737..3d6a9b27ea1 100644--- a/studio/frontend/tests/scan-folder-status.test.ts+++ b/studio/frontend/tests/scan-folder-status.test.ts@@ -2,10 +2,9 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrcAsync, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -70,24 +69,16 @@ test("an unreadable folder points at the drive", () => {});test("the model picker renders the status on its folder rows too", async () => {- const source = await readFile(- new URL(- "../src/features/model-picker/components/model-selector/pickers.tsx",- import.meta.url,- ),- "utf8",+ const source = await readSrcAsync(+ "features/model-picker/components/model-selector/pickers.tsx",);assert.match(source, /scanFolderStatusCopy\(f\.status\)/);assert.match(source, /\{problem\.title\}/);});test("the folders dialog renders the status on the row", async () => {- const source = await readFile(- new URL(- "../src/features/hub/catalog/on-device-folders-dialog.tsx",- import.meta.url,- ),- "utf8",+ const source = await readSrcAsync(+ "features/hub/catalog/on-device-folders-dialog.tsx",);assert.match(source, /scanFolderStatusCopy\(folder\.status\)/);assert.match(source, /\{problem\.title\}\. \{problem\.hint\}/);diff --git a/studio/frontend/tests/search-images.test.ts b/studio/frontend/tests/search-images.test.tsindex 85ae3ee9320..229ad405ea0 100644--- a/studio/frontend/tests/search-images.test.ts+++ b/studio/frontend/tests/search-images.test.ts@@ -2,9 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import ts from "typescript";@@ -33,6 +31,10 @@ import {} from "../src/components/assistant-ui/sandbox-files.ts";import { safeMarkdownUrl } from "../src/lib/safe-markdown-url.ts";+import { readSrc } from "./helpers/kit.ts";++const SEARCH_IMAGE = readSrc("components/assistant-ui/search-image.tsx");+const ENTRY = {id: "0123456789ab",title: "Golden Retriever",@@ -42,10 +44,7 @@ const ENTRY = {const OTHER = { ...ENTRY, id: "abcdef012345", title: "Labrador" };const KNOWN = new Set([ENTRY.id, OTHER.id]);-const adapterSource = readFileSync(- fileURLToPath(new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url)),- "utf8",-);+const adapterSource = readSrc("features/chat/api/chat-adapter.ts");function liftAdapterFunction(opener: string): string {const start = adapterSource.indexOf(opener);@@ -450,12 +449,8 @@ test("extractListSubjects reads the lead of each listed item", () => {test("the inline card is block-level, so a list item cannot flow text around it", () => {// A list item styles its paragraphs `[&>p]:inline`. An inline card lands in the// middle of the sentence and the text wraps around it, which is what shipped once.- const source = readFileSync(- new URL("../src/components/assistant-ui/search-image.tsx", import.meta.url),- "utf8",- );- const wrapper = /data-search-image=\{entry\.id\}/.test(source)- ? source.slice(source.indexOf("if (!entry) return null;"))+ const wrapper = /data-search-image=\{entry\.id\}/.test(SEARCH_IMAGE)+ ? SEARCH_IMAGE.slice(SEARCH_IMAGE.indexOf("if (!entry) return null;")): "";assert.match(wrapper, /className="[^"]*\bflex\b/, "wrapper must not be inline");assert.match(wrapper, /empty:hidden/, "an unloaded card must not leave a gap");@@ -851,12 +846,7 @@ test("a replayed web_search result carries no image tokens either", () => {// to run on the previous value. The store and the adapter cannot be imported in// a bare node test (a .tsx barrel sits in both graphs), so these pin the source// the way the sibling store tests do.-const storeSource = readFileSync(- fileURLToPath(- new URL("../src/features/chat/stores/chat-runtime-store.ts", import.meta.url),- ),- "utf8",-);+const storeSource = readSrc("features/chat/stores/chat-runtime-store.ts");test("a queued settings patch is sent before a run reads it", () => {const flush = storeSource.slice(@@ -940,12 +930,7 @@ test("every export path strips the tokens, not just the clipboard", () => {// The tokens are renderer markup. A per-message export, a reply saved as a// project source and a whole chat saved as one all reach disk (or back into// model context) by a different route than the copy button.- const threadSource = readFileSync(- fileURLToPath(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- ),- "utf8",- );+ const threadSource = readSrc("components/assistant-ui/thread.tsx");const exporter = threadSource.slice(threadSource.indexOf("async function exportMessageMarkdown("),threadSource.indexOf("const AssistantActionBar"),@@ -961,15 +946,7 @@ test("every export path strips the tokens, not just the clipboard", () => {/stripSearchImageTokens\(\s*replySourceMarkdown\(/,"a reply saved as a project source must strip the tokens",);- const dialogSource = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- ),- "utf8",- );+ const dialogSource = readSrc("features/chat/prompt-storage/prompt-storage-dialog.tsx");const saveSource = dialogSource.slice(dialogSource.indexOf("async function saveConversationAsProjectSource("),dialogSource.indexOf("export async function saveChatItemAsProjectSource("),@@ -985,15 +962,7 @@ test("every export path strips the tokens, not just the clipboard", () => {test("the web search card survives a query that is not a string", () => {// Local models emit `"query": 42` and `"query": {}` routinely, and .trim() on// one threw straight through the renderer.- const cardSource = readFileSync(- fileURLToPath(- new URL(- "../src/components/assistant-ui/tool-ui-web-search.tsx",- import.meta.url,- ),- ),- "utf8",- );+ const cardSource = readSrc("components/assistant-ui/tool-ui-web-search.tsx");const args = cardSource.slice(cardSource.indexOf("const query ="),cardSource.indexOf("const isUrlFetch ="),@@ -1018,15 +987,9 @@ test("the web search card survives a query that is not a string", () => {test("a thumbnail response that lands after the id changed is ignored", () => {// Render falls through to idle for a state written under the previous id, and// the effect has no reason to run again: a skeleton that never resolves.- const source = readFileSync(- fileURLToPath(- new URL("../src/components/assistant-ui/search-image.tsx", import.meta.url),- ),- "utf8",- );- const effect = source.slice(- source.indexOf("authFetch(searchImagePath(id)"),- source.indexOf("function useNearViewport"),+ const effect = SEARCH_IMAGE.slice(+ SEARCH_IMAGE.indexOf("authFetch(searchImagePath(id)"),+ SEARCH_IMAGE.indexOf("function useNearViewport"),);assert.ok(effect.length > 0, "the thumbnail effect moved");const notOk = effect.slice(effect.indexOf("if (!response.ok)"));diff --git a/studio/frontend/tests/server-tuning-settings.test.ts b/studio/frontend/tests/server-tuning-settings.test.tsindex b526e5adae4..d81443de8a1 100644--- a/studio/frontend/tests/server-tuning-settings.test.ts+++ b/studio/frontend/tests/server-tuning-settings.test.ts@@ -7,11 +7,9 @@// extra-arguments diagnostics that name the control a typed flag duplicates.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -114,15 +112,7 @@ test("the four take part in the editor's identity", () => {test("a record only claims the new schema version when it carries one", () => {// toStoredConfig stamps the OLDEST version that understands every field// present, so an older client can still rewrite a record it fully knows.- const source = readFileSync(- fileURLToPath(- new URL(- "../src/features/model-picker/model-config/per-model-config.ts",- import.meta.url,- ),- ),- "utf8",- );+ const source = readSrc("features/model-picker/model-config/per-model-config.ts");assert.match(source, /const STORAGE_SCHEMA_VERSION = 5;/);assert.match(source, /const PRE_SERVER_TUNING_SCHEMA_VERSION = 4;/);assert.match(source, /hasServerTuning\s*\n?\s*\?\s*STORAGE_SCHEMA_VERSION/);diff --git a/studio/frontend/tests/settings-panel-prefs.test.ts b/studio/frontend/tests/settings-panel-prefs.test.tsindex 094198c0f9e..86d0081d77d 100644--- a/studio/frontend/tests/settings-panel-prefs.test.ts+++ b/studio/frontend/tests/settings-panel-prefs.test.ts@@ -2,10 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {installLocalStorageFake,+ readSrc,+ readSrcAsync,registerBundlerResolver,} from "./helpers/kit.ts";@@ -33,6 +34,8 @@ store.set(}),);+const AGENTS_TAB = readSrc("features/settings/tabs/agents-tab.tsx");+const { useSettingsPanelPrefsStore, SETTINGS_PANEL_PREFS_STORAGE_KEY } =await import("../src/features/settings/stores/settings-panel-prefs-store.ts");@@ -154,13 +157,9 @@ test("a record from a newer build falls back to defaults", () => {// Settling in a .finally let a superseded or failed poll release the retire// with no resident model recorded, which erased the saved model and quant.test("the status poll settles only on the read that applied", async () => {- const source = await readFile(- new URL("../src/features/settings/tabs/agents-tab.tsx", import.meta.url),- "utf8",- );- const sync = source.slice(- source.indexOf("const sync = ()"),- source.indexOf("const timer = window.setInterval"),+ const sync = AGENTS_TAB.slice(+ AGENTS_TAB.indexOf("const sync = ()"),+ AGENTS_TAB.indexOf("const timer = window.setInterval"),);assert.ok(sync, "the status poll moved; this contract needs updating");assert.ok(@@ -176,10 +175,7 @@ test("the status poll settles only on the read that applied", async () => {// Reset-all is the only in-app escape hatch from a bad pinned model.test("Reset all local preferences clears this key", async () => {- const source = await readFile(- new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("features/settings/tabs/general-tab.tsx");const keys = source.slice(source.indexOf("const PREFS_KEYS"),source.indexOf("];", source.indexOf("const PREFS_KEYS")),@@ -195,18 +191,14 @@ test("Reset all local preferences clears this key", async () => {// status endpoints can disagree on repo-id casing, so that scope check has to// normalize or the user's quant is dropped when the spelling differs.test("the remembered quant is scoped through modelKey, not an exact compare", async () => {- const source = await readFile(- new URL("../src/features/settings/tabs/agents-tab.tsx", import.meta.url),- "utf8",- );assert.match(- source,+ AGENTS_TAB,/modelKey\(chosen\.model\) === modelKey\(model\)/,"rememberedVariant must compare through modelKey",);- const exact = source- .split("\n")- .filter((line) => line.includes("chosenVariant.current?.model ==="));+ const exact = AGENTS_TAB.split("\n").filter((line) =>+ line.includes("chosenVariant.current?.model ==="),+ );assert.deepEqual(exact,[],diff --git a/studio/frontend/tests/settings-row-text-width.test.ts b/studio/frontend/tests/settings-row-text-width.test.tsindex 051a31b0a60..8c84469d293 100644--- a/studio/frontend/tests/settings-row-text-width.test.ts+++ b/studio/frontend/tests/settings-row-text-width.test.ts@@ -1,17 +1,14 @@import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readSrcAsync } from "./helpers/kit.ts";+const BOUNDED_TEXT_COLUMN =/<div className="[^"]*w-full[^"]*max-w-lg[^"]*flex-col[^"]*">\s*\{\/\* Flex only when hinted/;test("settings row titles and descriptions share a bounded text column", async () => {- const source = await readFile(- new URL(- "../src/features/settings/components/settings-row.tsx",- import.meta.url,- ),- "utf8",+ const source = await readSrcAsync(+ "features/settings/components/settings-row.tsx",);assert.match(source, BOUNDED_TEXT_COLUMN);diff --git a/studio/frontend/tests/shortcut-dispatch-guards.test.ts b/studio/frontend/tests/shortcut-dispatch-guards.test.tsindex 5bdd179eaa7..7690c68d198 100644--- a/studio/frontend/tests/shortcut-dispatch-guards.test.ts+++ b/studio/frontend/tests/shortcut-dispatch-guards.test.ts@@ -7,7 +7,11 @@ import test from "node:test";import ts from "typescript";-import { registerBundlerResolver } from "./helpers/kit.ts";+import {+ readSrc,+ readSrcAsync,+ registerBundlerResolver,+} from "./helpers/kit.ts";registerBundlerResolver();@@ -23,6 +27,12 @@ const { isAcceptableBinding, parseBinding } = await import("../src/features/settings/lib/keyboard-shortcuts.ts");+const SRC__ROOT = readSrc("app/routes/__root.tsx");+const APP_SIDEBAR = readSrc("components/app-sidebar.tsx");+const THREAD = readSrc("components/assistant-ui/thread.tsx");+const CHAT_PAGE = readSrc("features/chat/chat-page.tsx");+const USE_SHORTCUT = readSrc("features/settings/hooks/use-shortcut.ts");+/** A keydown the dispatcher would see, with only the fields it reads. */function keydown(init: { isComposing?: boolean; keyCode?: number }) {return {@@ -43,14 +53,10 @@ test("a keydown mid-IME-composition is not a chord", () => {});test("the dispatcher checks composition before it matches anything", async () => {- const source = await readFile(- new URL("../src/features/settings/hooks/use-shortcut.ts", import.meta.url),- "utf8",- );// Before the match, so no chord is found, and before preventDefault, so the// candidate window keeps its key.assert.match(- source,+ USE_SHORTCUT,/if \(isImeComposing\(event\)\) return;\n\s*const hit = bindings\.find/,);});@@ -120,13 +126,9 @@ test("every match under a modal is still not the foreground", () => {});test("dictation asks at press time, not through enabled", async () => {- const source = await readFile(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );- const at = source.indexOf('useShortcut(\n "startDictation"');+ const at = THREAD.indexOf('useShortcut(\n "startDictation"');assert.notEqual(at, -1, "the dictation chord lost its call site");- const body = source.slice(at, source.indexOf("\n );", at));+ const body = THREAD.slice(at, THREAD.indexOf("\n );", at));// Inside the handler: `enabled` is read at render, and a dialog opening need// not re-render this component.assert.match(@@ -138,27 +140,19 @@ test("dictation asks at press time, not through enabled", async () => {// A write that fails with a good payload used to report nothing at all, so the// chord was indistinguishable from a dead key.test("both copy chords report a failed write", async () => {- const source = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );assert.match(- source,+ APP_SIDEBAR,/} else if \(empty\.value\) \{[\s\S]*?\} else \{[\s\S]*?toast\.error\("Could not copy this chat\."\)/,);- assert.match(source, /toast\.error\("Could not copy the session id\."\)/);+ assert.match(APP_SIDEBAR, /toast\.error\("Could not copy the session id\."\)/);});// Current membership says nothing about where a chat's older files went: it can// join a project, record that session, and move back out.test("the sandbox probe does not skip a chat that is out of a project", async () => {- const source = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );- const at = source.indexOf("async function sandboxSessionIdsHolding");+ const at = APP_SIDEBAR.indexOf("async function sandboxSessionIdsHolding");assert.notEqual(at, -1);- const body = source.slice(at, source.indexOf("\n }", at));+ const body = APP_SIDEBAR.slice(at, APP_SIDEBAR.indexOf("\n }", at));assert.doesNotMatch(body, /if \(!item\.projectId\) return recorded;/);assert.match(body,@@ -186,13 +180,9 @@ test("both composers gate dictation on the foreground", async () => {});test("route shortcuts stay idle while Settings is open", async () => {- const sourceText = await readFile(- new URL("../src/app/routes/__root.tsx", import.meta.url),- "utf8",- );const source = ts.createSourceFile("__root.tsx",- sourceText,+ SRC__ROOT,ts.ScriptTarget.ESNext,true,ts.ScriptKind.TSX,@@ -240,7 +230,7 @@ test("route shortcuts stay idle while Settings is open", async () => {"routeShortcutEnabled && !videoDisabled",);assert.match(- sourceText,+ SRC__ROOT,/const routeShortcutEnabled = !isAuthFlowRoute && !settingsDialogOpen;/,);});@@ -248,20 +238,13 @@ test("route shortcuts stay idle while Settings is open", async () => {// The sidebar used to hold the unread set in component state, which died with// it. A module store does not, so the next account inherits it.test("signing out drops the previous account's navigation state", async () => {- const store = await readFile(- new URL("../src/features/chat/stores/chat-navigation-store.ts", import.meta.url),- "utf8",- );+ const store = await readSrcAsync("features/chat/stores/chat-navigation-store.ts");assert.match(store, /resetAccountState: \(\) =>/);// A fresh Set, or every account after the first shares one.assert.match(store, /set\(\{ \.\.\.ACCOUNT_STATE, unreadThreadIds: new Set\(\), unreadRowIds: \{\} \}\)/);- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );// On unmount, which is what the auth routes do to the sidebar.assert.match(- sidebar,+ APP_SIDEBAR,/useEffect\(\n\s*\(\) => \(\) => useChatNavigationStore\.getState\(\)\.resetAccountState\(\),\n\s*\[\],\n\s*\);/,);});@@ -269,31 +252,20 @@ test("signing out drops the previous account's navigation state", async () => {// The latch holds back a repeat of the action that took the selection, not a// different command issued straight after it.test("the selection latch is keyed by action", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );- assert.match(sidebar, /selectionActedRef = useRef<\{ id: ShortcutId; at: number \} \| null>/);- assert.match(sidebar, /last\?\.id === id &&/);- assert.doesNotMatch(sidebar, /followsSelectionAction\(\)/);+ assert.match(APP_SIDEBAR, /selectionActedRef = useRef<\{ id: ShortcutId; at: number \} \| null>/);+ assert.match(APP_SIDEBAR, /last\?\.id === id &&/);+ assert.doesNotMatch(APP_SIDEBAR, /followsSelectionAction\(\)/);});// One selector has to mean "the composer" whichever of the two is on screen, or// Escape stops declining in Compare and the dictation gate reads the wrong one.test("both composers answer to the shared selector", async () => {- const shared = await readFile(- new URL("../src/features/chat/shared-composer.tsx", import.meta.url),- "utf8",- );- const thread = await readFile(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );+ const shared = await readSrcAsync("features/chat/shared-composer.tsx");const { COMPOSER_INPUT_SELECTOR } = await import("../src/features/settings/hooks/use-shortcut.ts");const className = COMPOSER_INPUT_SELECTOR.replace(/^\./, "");- for (const [name, source] of [["shared", shared], ["thread", thread]]) {+ for (const [name, source] of [["shared", shared], ["thread", THREAD]]) {assert.match(source,new RegExp(`className="[^"]*\\b${className}\\b[^"]*"`),@@ -373,10 +345,6 @@ test("an absent surface is not a covered one", () => {// Window-level chords stay registered under a dialog, so the destructive ones// have to ask at press time whether the sidebar is still the foreground.test("the sidebar's mutating chords refuse to fire under a dialog", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );for (const id of ["archiveChat","markChatUnread",@@ -385,9 +353,9 @@ test("the sidebar's mutating chords refuse to fire under a dialog", async () =>"renameChat","clearAllUnreads",]) {- const at = sidebar.indexOf(`useShortcut("${id}", () => {`);+ const at = APP_SIDEBAR.indexOf(`useShortcut("${id}", () => {`);assert.notEqual(at, -1, `${id} is gone`);- const body = sidebar.slice(at, sidebar.indexOf("\n });", at));+ const body = APP_SIDEBAR.slice(at, APP_SIDEBAR.indexOf("\n });", at));assert.match(body,/if \(sidebarCovered\(\)\) return;/,@@ -395,11 +363,11 @@ test("the sidebar's mutating chords refuse to fire under a dialog", async () =>);}// Covered, not "not in the foreground", or the mobile drawer kills them all.- assert.match(sidebar, /isSurfaceBackgrounded\(SIDEBAR_SELECTOR\)/);+ assert.match(APP_SIDEBAR, /isSurfaceBackgrounded\(SIDEBAR_SELECTOR\)/);// And with the drawer closed the sidebar is unmounted, so the app root is// what carries the modal signal there.assert.match(- sidebar,+ APP_SIDEBAR,/document\.querySelector\(SIDEBAR_SELECTOR\) === null &&\n\s*isSurfaceBackgrounded\("#root"\)/,);});@@ -408,31 +376,23 @@ test("the sidebar's mutating chords refuse to fire under a dialog", async () =>// thread folder and in the project one. Probing only the thread folder// answered for one and hid the other.test("the sandbox probe leaves the shared project folder alone", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );- const at = sidebar.indexOf("async function sandboxSessionIdsHolding(");+ const at = APP_SIDEBAR.indexOf("async function sandboxSessionIdsHolding(");assert.notEqual(at, -1);- const body = sidebar.slice(at, sidebar.indexOf("\n }", at));+ const body = APP_SIDEBAR.slice(at, APP_SIDEBAR.indexOf("\n }", at));// The shared project workspace is not probed: every chat in the project// writes there, so its files are no evidence about this one, and counting// them reported a second folder for any chat that joined a used project.assert.doesNotMatch(body, /sandboxSessionIdFor\(/);assert.doesNotMatch(body, /candidates\.add\(/);- assert.equal(sidebar.split("sandboxSessionIdsHolding(ids)").length - 1, 2);+ assert.equal(APP_SIDEBAR.split("sandboxSessionIdsHolding(ids)").length - 1, 2);});// Loading a model that drops the level in force leaves the effort set to one// the model does not list, and indexOf then returns -1.test("an unlisted reasoning effort steps to the first supported level", async () => {- const page = await readFile(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );- const at = page.indexOf("const current = levels.indexOf(state.reasoningEffort);");+ const at = CHAT_PAGE.indexOf("const current = levels.indexOf(state.reasoningEffort);");assert.notEqual(at, -1);- const body = page.slice(at, at + 700);+ const body = CHAT_PAGE.slice(at, at + 700);assert.match(body,/if \(current === -1\) \{\n\s*state\.setReasoningEffort\(levels\[0\]\);/,@@ -465,27 +425,17 @@ test("only a chord that types nothing keeps the composer exception", () => {});test("the dispatcher drops the exception for a typing chord", async () => {- const source = await readFile(- new URL("../src/features/settings/hooks/use-shortcut.ts", import.meta.url),- "utf8",- );assert.match(- source,+ USE_SHORTCUT,/const exception = typesInTextField\(hit\) \? undefined : textFieldException;/,);- assert.match(source, /isTextEntryFocused\(exception\)/);+ assert.match(USE_SHORTCUT, /isTextEntryFocused\(exception\)/);});// Every keydown is swallowed while recording, and on a bare-key row Escape is// a chord rather than a cancel, so a keyboard-only user had no way out.test("recording can be left from the keyboard", async () => {- const tab = await readFile(- new URL(- "../src/features/settings/tabs/keyboard-shortcuts-tab.tsx",- import.meta.url,- ),- "utf8",- );+ const tab = await readSrcAsync("features/settings/tabs/keyboard-shortcuts-tab.tsx");const at = tab.indexOf("const onKeyDown = (event: KeyboardEvent) => {");assert.notEqual(at, -1);const body = tab.slice(at, at + 900);@@ -497,21 +447,17 @@ test("recording can be left from the keyboard", async () => {// The page stays mounted under a dialog, so `enabled` still says yes.test("the header pickers do not open behind a dialog", async () => {- const page = await readFile(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );for (const id of ["openModelPicker", "openProjectPicker"]) {- const at = page.indexOf(`"${id}",`);+ const at = CHAT_PAGE.indexOf(`"${id}",`);assert.notEqual(at, -1, `${id} is gone`);assert.match(- page.slice(at, at + 260),+ CHAT_PAGE.slice(at, at + 260),/if \(chatCovered\(\)\) return;/,`${id} opens a control on the covered surface`,);}assert.match(- page,+ CHAT_PAGE,/isSurfaceBackgrounded\(COMPOSER_INPUT_SELECTOR\)/,);});@@ -538,13 +484,7 @@ test("both composers refuse to attach from behind a modal", async () => {// not be reachable by accident, and the Chat route stays mounted under a// dialog, so `keyboardReady` alone still says yes.test("a tool call cannot be answered from behind a dialog", async () => {- const source = await readFile(- new URL(- "../src/components/assistant-ui/tool-confirmation-controls.tsx",- import.meta.url,- ),- "utf8",- );+ const source = await readSrcAsync("components/assistant-ui/tool-confirmation-controls.tsx");for (const id of ["approveToolRequest", "declineToolRequest"]) {const at = source.indexOf(`"${id}",`);assert.notEqual(at, -1, `${id} is gone`);@@ -560,14 +500,10 @@ test("a tool call cannot be answered from behind a dialog", async () => {// A selection made behind a dialog is invisible and still what the mutating// chords act on afterwards, and the clipboard is outside the app entirely.test("selection and clipboard chords stop at a covered sidebar", async () => {- const sidebar = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );for (const id of ["selectAllChats", "copyChatAsMarkdown", "copySessionId"]) {- const at = sidebar.indexOf(`useShortcut("${id}", () => {`);+ const at = APP_SIDEBAR.indexOf(`useShortcut("${id}", () => {`);assert.notEqual(at, -1, `${id} is gone`);- const body = sidebar.slice(at, sidebar.indexOf("\n });", at));+ const body = APP_SIDEBAR.slice(at, APP_SIDEBAR.indexOf("\n });", at));assert.match(body,/if \(sidebarCovered\(\)\) return;/,@@ -581,16 +517,9 @@ test("selection and clipboard chords stop at a covered sidebar", async () => {// so the click lands on a page that shows its own loading state. Gating the// chords on the unknown verdict would make them disagree with their own rows.test("the workspace chords wait on the same verdict their rows do", async () => {- const root = await readFile(- new URL("../src/app/routes/__root.tsx", import.meta.url),- "utf8",- );- assert.match(root, /enabled: routeShortcutEnabled && !chatOnlyMeasured,/);- assert.match(root, /enabled: routeShortcutEnabled && !videoDisabled,/);- const rowState = await readFile(- new URL("../src/components/nav-row-state.ts", import.meta.url),- "utf8",- );+ assert.match(SRC__ROOT, /enabled: routeShortcutEnabled && !chatOnlyMeasured,/);+ assert.match(SRC__ROOT, /enabled: routeShortcutEnabled && !videoDisabled,/);+ const rowState = await readSrcAsync("components/nav-row-state.ts");assert.match(rowState,/if \(row\.pending\) \{\n\s*return \{\n\s*disabled: false,/,@@ -601,32 +530,24 @@ test("the workspace chords wait on the same verdict their rows do", async () =>// The reasoning, Fast mode and fork chords drive controls on the page behind a// dialog just as the pickers do.test("the remaining chat-page chords stop at a covered surface", async () => {- const page = await readFile(- new URL("../src/features/chat/chat-page.tsx", import.meta.url),- "utf8",- );for (const id of ["cycleReasoningEffort","increaseReasoningEffort","decreaseReasoningEffort","toggleFastMode",]) {- const at = page.indexOf(`"${id}",`);+ const at = CHAT_PAGE.indexOf(`"${id}",`);assert.notEqual(at, -1, `${id} is gone`);assert.match(- page.slice(at, at + 220),+ CHAT_PAGE.slice(at, at + 220),/if \(chatCovered\(\)\) return;/,`${id} acts on the covered surface`,);}- const thread = await readFile(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );- const at = thread.indexOf('"forkChat",');+ const at = THREAD.indexOf('"forkChat",');assert.notEqual(at, -1);assert.match(- thread.slice(at, at + 320),+ THREAD.slice(at, at + 320),/if \(!isSurfaceInForeground\(COMPOSER_INPUT_SELECTOR\)\) return;/,);});diff --git a/studio/frontend/tests/shortcut-text-field-gate.test.ts b/studio/frontend/tests/shortcut-text-field-gate.test.tsindex 6d6d0fb8ea2..a6e60aaff65 100644--- a/studio/frontend/tests/shortcut-text-field-gate.test.ts+++ b/studio/frontend/tests/shortcut-text-field-gate.test.ts@@ -2,10 +2,9 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-import { registerBundlerResolver } from "./helpers/kit.ts";+import { readSrcAsync, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();@@ -63,12 +62,8 @@ test("the composer exception frees the composer and nothing else", () => {});test("the decline chord takes the exception and the approve chord does not", async () => {- const controls = await readFile(- new URL(- "../src/components/assistant-ui/tool-confirmation-controls.tsx",- import.meta.url,- ),- "utf8",+ const controls = await readSrcAsync(+ "components/assistant-ui/tool-confirmation-controls.tsx",);// Escape leaves the text alone. Enter sends, so it stays behind the gate.assert.match(@@ -84,10 +79,7 @@ test("the decline chord takes the exception and the approve chord does not", asy});test("the selector matches the class the composer actually carries", async () => {- const thread = await readFile(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",- );+ const thread = await readSrcAsync("components/assistant-ui/thread.tsx");assert.equal(COMPOSER_INPUT_SELECTOR, ".aui-composer-input");// A selector naming a class nothing carries would silently gate everything.assert.match(thread, /className="aui-composer-input /);diff --git a/studio/frontend/tests/sidebar-action-rows-inert.test.ts b/studio/frontend/tests/sidebar-action-rows-inert.test.tsindex 11ab3c2993e..ff273dbe4ba 100644--- a/studio/frontend/tests/sidebar-action-rows-inert.test.ts+++ b/studio/frontend/tests/sidebar-action-rows-inert.test.ts@@ -2,20 +2,18 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readSrc } from "./helpers/kit.ts";++const APP_SIDEBAR = readSrc("components/app-sidebar.tsx");++const INDEX = readSrc("index.css");+// The pinned top rows run an action rather than open a page, so neither may// mark itself active: nav rows paint one pill for both states, and an active// action row therefore sits there looking permanently hovered.-async function sidebarSource(): Promise<string> {- return readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );-}-/** The props of the NavItem carrying `label`, from its tag to the next one. */function navItemFor(source: string, label: string): string {const rows = source.split("<NavItem").slice(1);@@ -25,27 +23,20 @@ function navItemFor(source: string, label: string): string {}test("New chat never marks itself active", async () => {- const row = navItemFor(await sidebarSource(), "shell.navigation.newChat");+ const row = navItemFor(APP_SIDEBAR, "shell.navigation.newChat");assert.match(row, /active=\{false\}/);});test("Search never marks itself active either", async () => {- const row = navItemFor(- await sidebarSource(),- 'label={t("shell.navigation.search")}',- );+ const row = navItemFor(APP_SIDEBAR, 'label={t("shell.navigation.search")}');assert.match(row, /active=\{false\}/);});test("a nav row paints the same pill when active and when hovered", async () => {// The reason the rows above pass false. If active ever gets its own// background, that reason is gone and this can be revisited.- const css = await readFile(- new URL("../src/index.css", import.meta.url),- "utf8",- );const rule = /([^}]*)\{\s*background-color: var\(--nav-surface-hover\)/.exec(- css,+ INDEX,);assert.ok(rule, "no rule paints a nav row with --nav-surface-hover");assert.match(rule[1], /\.sidebar-nav-btn:hover/);@@ -53,7 +44,7 @@ test("a nav row paints the same pill when active and when hovered", async () =>});test("desktop branding clears the titlebar actions", async () => {- const source = await sidebarSource();+ const source = APP_SIDEBAR;assert.match(source,/shrink-0 p-0 pt-\[calc\(var\(--studio-desktop-titlebar-height,34px\)\+17px\)\]/,@@ -61,12 +52,12 @@ test("desktop branding clears the titlebar actions", async () => {});test("desktop branding keeps an 11px gap above New chat", async () => {- const source = await sidebarSource();+ const source = APP_SIDEBAR;assert.match(source, /usesDesktopTitlebar \? "pt-\[11px\]" : "pt-\[9px\]"/);});test("footer profile sits 11px above the sidebar edge", async () => {- const source = await sidebarSource();+ const source = APP_SIDEBAR;assert.match(source,/relative pb-\[11px\] group-data-\[collapsible=icon\]:px-0/,@@ -78,7 +69,7 @@ test("navigation rows align while the profile footer ignores the scroll rail", a// lose the rail's width, so New Chat adds it back and both end on one edge.// The profile footer is unrelated to that list and must keep its full width// when the scrollbar appears. Logical sides, since the rail moves under rtl.- const source = await sidebarSource();+ const source = APP_SIDEBAR;assert.match(source,/const rowPadding = usesDesktopTitlebar\s*\?\s*"ps-\[5px\] pe-\[calc\(var\(--sidebar-rail,0px\)\+5px\)\]"\s*:\s*"ps-1\.5 pe-\[calc\(var\(--sidebar-rail,0px\)\+6px\)\]"/,@@ -106,7 +97,7 @@ test("navigation rows align while the profile footer ignores the scroll rail", atest("the sidebar list measures its scroll rail", async () => {// 0 where scrollbars overlay, the platform's thin rail where they are// classic. Read off the scroller and written to the DOM: state loops (#185).- const source = await sidebarSource();+ const source = APP_SIDEBAR;assert.match(source,/const rail = el\.offsetWidth - el\.clientWidth;[\s\S]*el\.parentElement\?\.style\.setProperty\(\s*"--sidebar-rail",\s*`\$\{rail\}px`,?\s*\)/,@@ -134,50 +125,42 @@ test("the sidebar list measures its scroll rail", async () => {/const observer = new ResizeObserver\(\(\) => measureScrollRail\(el\)\);\s*observer\.observe\(el\);\s*railObserverRef\.current = observer;/,);// Writes a variable, never state: that pairing is what looped.- assert.equal(- /new ResizeObserver\([^)]*set[A-Z]/.test(source),- false,- );+ assert.equal(/new ResizeObserver\([^)]*set[A-Z]/.test(source), false);// And only on a change, so it cannot re-trigger itself.- assert.match(- source,- /if \(rail === railWidthRef\.current\) return;/,- );+ assert.match(source, /if \(rail === railWidthRef\.current\) return;/);// The fade stops at the rail too: the thumb ends its travel in that band.assert.match(source,/absolute start-0 end-\[var\(--sidebar-rail,0px\)\] bottom-full/,);- const css = await readFile(- new URL("../src/index.css", import.meta.url),- "utf8",- );// Only the Windows auto reset may set a width; hiding the rail is what a// width override caused before.const railWidthDecls = (- css.match(/\.sidebar-scroll-fade[^{]*\{[^}]*scrollbar-width:\s*[^;}]+/g) ?? []+ INDEX.match(+ /\.sidebar-scroll-fade[^{]*\{[^}]*scrollbar-width:\s*[^;}]+/g,+ ) ?? []).map((rule) => /scrollbar-width:\s*([^;}]+)/.exec(rule)?.[1].trim());assert.deepEqual(railWidthDecls, ["auto"]);- assert.match(css, /:root\.client-windows \.sidebar-scroll-fade,/);+ assert.match(INDEX, /:root\.client-windows \.sidebar-scroll-fade,/);assert.equal(- /\.sidebar-scroll-fade::-webkit-scrollbar \{/.test(css),+ /\.sidebar-scroll-fade::-webkit-scrollbar \{/.test(INDEX),false,);// Thumb stays hidden until the list is hovered, as the other lists do.- assert.match(css, /\.sidebar-scroll-fade:hover::-webkit-scrollbar-thumb,/);+ assert.match(INDEX, /\.sidebar-scroll-fade:hover::-webkit-scrollbar-thumb,/);// A mask covers the scrollbar, so the top fade keeps the rail column opaque.assert.match(- css,+ INDEX,/mask-image: linear-gradient\(to bottom, transparent 0, #000 14px\),\s*linear-gradient\(to left, #000 var\(--sidebar-rail, 0px\), transparent 0\);/,);assert.match(- css,+ INDEX,/\[dir="rtl"\] \.sidebar-scroll-fade\.is-scrolled \{[\s\S]*linear-gradient\(to right, #000 var\(--sidebar-rail, 0px\), transparent 0\);/,);});test("Tauri chat Recents label keeps its 2px shift", async () => {- const source = await sidebarSource();+ const source = APP_SIDEBAR;assert.match(source,/scrolled && "is-scrolled",\s*usesDesktopTitlebar && "translate-x-\[2px\]"/,diff --git a/studio/frontend/tests/sidebar-more-menu-interaction.test.ts b/studio/frontend/tests/sidebar-more-menu-interaction.test.tsindex e6a8ae12f77..d25cb45bf86 100644--- a/studio/frontend/tests/sidebar-more-menu-interaction.test.ts+++ b/studio/frontend/tests/sidebar-more-menu-interaction.test.ts@@ -2,14 +2,12 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readSrcAsync } from "./helpers/kit.ts";+test("the sidebar More flyout previews on hover and pins on click", async () => {- const source = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("components/app-sidebar.tsx");assert.match(source, /const \[moreHoverOpen, setMoreHoverOpen\] = useState\(false\)/);assert.match(source, /const \[morePinnedOpen, setMorePinnedOpen\] = useState\(false\)/);diff --git a/studio/frontend/tests/sidebar-nav-backend-parity.test.ts b/studio/frontend/tests/sidebar-nav-backend-parity.test.tsindex 362d2cd5415..8a1f074a99b 100644--- a/studio/frontend/tests/sidebar-nav-backend-parity.test.ts+++ b/studio/frontend/tests/sidebar-nav-backend-parity.test.ts@@ -2,19 +2,17 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import { DEFAULT_CUSTOMIZATION } from "../src/features/settings/stores/appearance-custom-store.ts";+import { readSrcAsync, readText } from "./helpers/kit.ts";+// A record predating sidebarNav is served the backend's own defaults, so a drift there// hands the user a layout this side never shipped. settings.py says the two must match;// the backend's parity test compares against a hand-copied list, which cannot catch a// frontend-only change. Read the real constant instead.test("the backend sidebar nav defaults match the frontend", async () => {- const source = await readFile(- new URL("../../backend/routes/settings.py", import.meta.url),- "utf8",- );+ const source = readText("../../backend/routes/settings.py");const block = /SIDEBAR_NAV_ITEM_DEFAULTS = \{([\s\S]*?)^\}/m.exec(source);assert.ok(block, "could not find SIDEBAR_NAV_ITEM_DEFAULTS in settings.py");const backend = [...block[1].matchAll(/"([a-z]+)":\s*(True|False)/g)].map((m) => ({@@ -30,10 +28,7 @@ test("the backend sidebar nav defaults match the frontend", async () => {// keyed by SidebarNavItemId, so a dropped `pending` there just stops spinning, it does not// fail to compile.test("Train and Video are still the capability-gated rows", async () => {- const source = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("components/app-sidebar.tsx");const rows = /const navRows: Record<SidebarNavItemId, NavRowDef> = \{([\s\S]*?)\n \};/.exec(source,);@@ -47,10 +42,7 @@ test("Train and Video are still the capability-gated rows", async () => {bodies.set(key[1], rows[1].slice(start, end));});// Every id the backend knows about has a row, or the personalization round-trip renders a gap.- const backend = await readFile(- new URL("../../backend/routes/settings.py", import.meta.url),- "utf8",- );+ const backend = readText("../../backend/routes/settings.py");const block = /SIDEBAR_NAV_ITEM_DEFAULTS = \{([\s\S]*?)^\}/m.exec(backend);assert.ok(block, "could not find SIDEBAR_NAV_ITEM_DEFAULTS in settings.py");for (const [, id] of block[1].matchAll(/"([a-z]+)":/g)) {diff --git a/studio/frontend/tests/sidebar-nav-migration.test.ts b/studio/frontend/tests/sidebar-nav-migration.test.tsindex 992a1a4ae7d..6a30cef0e99 100644--- a/studio/frontend/tests/sidebar-nav-migration.test.ts+++ b/studio/frontend/tests/sidebar-nav-migration.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {DEFAULT_CUSTOMIZATION,@@ -11,6 +10,8 @@ import {sanitizeCustomization,} from "../src/features/settings/stores/appearance-custom-store.ts";+import { readSrcAsync } from "./helpers/kit.ts";+const shippedLayouts: SidebarNavItemPref[][] = [[{ id: "projects", pinned: true },@@ -140,13 +141,7 @@ test("a shipped-looking layout chosen after migration is preserved", () => {/** The sync module uses path aliases, so read its constant rather than import it. */async function personalizationVersion(): Promise<number> {- const source = await readFile(- new URL(- "../src/features/profile/hooks/use-personalization-sync.ts",- import.meta.url,- ),- "utf8",- );+ const source = await readSrcAsync("features/profile/hooks/use-personalization-sync.ts");const match = /PERSONALIZATION_VERSION = (\d+)/.exec(source);assert.ok(match, "no PERSONALIZATION_VERSION in the sync module");return Number(match[1]);diff --git a/studio/frontend/tests/sidebar-organization-store.test.ts b/studio/frontend/tests/sidebar-organization-store.test.tsindex aa1807ea79f..1cfceb11252 100644--- a/studio/frontend/tests/sidebar-organization-store.test.ts+++ b/studio/frontend/tests/sidebar-organization-store.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {@@ -18,6 +17,8 @@ import {useSidebarOrganizationStore,} from "../src/features/chat/stores/sidebar-organization-store.ts";+import { readSrcAsync } from "./helpers/kit.ts";+const ids = (rows: Array<{ id: string }>) => rows.map((row) => row.id);test("a dragged chat takes the target's slot and pushes the rest along", () => {@@ -148,10 +149,7 @@ test("Pinned sorts independently of the chat lists", () => {// Reset-all is the only in-app way back to the shipped sidebar layout, and it// only removes the keys it lists, so an unlisted one survives the reload.test("Reset all local preferences clears this key", async () => {- const source = await readFile(- new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("features/settings/tabs/general-tab.tsx");const keys = source.slice(source.indexOf("const PREFS_KEYS"),source.indexOf("];", source.indexOf("const PREFS_KEYS")),diff --git a/studio/frontend/tests/sidebar-scroll-fade-deps.test.ts b/studio/frontend/tests/sidebar-scroll-fade-deps.test.tsindex 31343a760d9..79331d09298 100644--- a/studio/frontend/tests/sidebar-scroll-fade-deps.test.ts+++ b/studio/frontend/tests/sidebar-scroll-fade-deps.test.ts@@ -2,19 +2,17 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readSrcAsync } from "./helpers/kit.ts";+// onScroll never fires for a list that is not scrolling, so the bottom fade is// only re-measured when this effect re-runs. Every input that can add or remove// a row has to be in its deps, and a missing one is invisible: the fade just// stays wrong until an unrelated scroll or resize.test("the bottom fade re-measures on every row-count input", async () => {- const source = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("components/app-sidebar.tsx");const effect =/Recompute bottom-fade on mount[\s\S]*?\}, \[([\s\S]*?)\n \]\);/.exec(source,diff --git a/studio/frontend/tests/sidebar-selection-coverage.test.ts b/studio/frontend/tests/sidebar-selection-coverage.test.tsindex e2c730a870e..7beb10121de 100644--- a/studio/frontend/tests/sidebar-selection-coverage.test.ts+++ b/studio/frontend/tests/sidebar-selection-coverage.test.ts@@ -2,22 +2,18 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readSrc } from "./helpers/kit.ts";++const APP_SIDEBAR = readSrc("components/app-sidebar.tsx");+// A row is only selectable if it is handed the list it belongs to. Dropping// that argument still compiles, since it is optional, and the row just stops// responding to cmd and shift click.-async function sidebarSource(): Promise<string> {- return readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );-}-test("every chat list hands its rows a selection list", async () => {- const source = await sidebarSource();+ const source = APP_SIDEBAR;for (const list of [/\{ scope: PINNED_ORDER_SCOPE, ids: pinnedRowIds \}/,/\{ scope: RECENTS_ORDER_SCOPE, ids: recentRowIds \}/,@@ -28,7 +24,7 @@ test("every chat list hands its rows a selection list", async () => {});test("folder rows select too, and open their own bulk menu", async () => {- const source = await sidebarSource();+ const source = APP_SIDEBAR;assert.match(source, /handleProjectSelectionClick\(event, project\.id\)/);assert.match(source, /selectProjectForContextMenu\(project\.id\)/);assert.match(source, /\{renderProjectContextMenu\(\)\}/);@@ -47,7 +43,7 @@ test("picking one kind of row drops the other", async () => {// Chats and folders have no shared bulk action, so a mixed selection would// leave the menu unable to say what it acts on. All four entry points, since// one that skips it is what puts the sidebar in that state.- const source = await sidebarSource();+ const source = APP_SIDEBAR;for (const [name, drop] of [["handleSelectionClick", "dropProjectSelection()"],["selectForContextMenu", "dropProjectSelection()"],@@ -65,7 +61,7 @@ test("a right-click drops the other kind even on an already-selected row", async// Both menus return early when the row is already selected. Dropping after// that return would keep a mixed selection alive for exactly the rows a bulk// action is most likely to run on.- const source = await sidebarSource();+ const source = APP_SIDEBAR;for (const [name, drop] of [["selectForContextMenu", "dropProjectSelection()"],["selectProjectForContextMenu", "dropChatSelection()"],@@ -85,7 +81,7 @@ test("a right-click drops the other kind even on an already-selected row", asynctest("dropping a selection clears its anchor too", async () => {// A kept anchor shift-selects a range from a row that no longer looks// selected, which is how a cleared list grows again on the next click.- const source = await sidebarSource();+ const source = APP_SIDEBAR;assert.match(source,/const dropChatSelection = useCallback\(\(\) => \{\s*selectionAnchorRef\.current = null;/,@@ -99,7 +95,7 @@ test("dropping a selection clears its anchor too", async () => {test("the bulk archive failure reads a translated string", async () => {// Its wording already exists as a key, so a literal here would be the one// English toast in an otherwise translated flow.- const source = await sidebarSource();+ const source = APP_SIDEBAR;const archive = /async function archiveSelected\(([\s\S]*?)\n \}/.exec(source);assert.ok(archive, "no archiveSelected");assert.match(archive[1], /translate\("settings\.data\.failedToArchiveChats"\)/);@@ -109,7 +105,7 @@ test("one failed archive does not abandon the rest of the batch", async () => {// The selection is cleared up front, so chats skipped by an early exit are// left unarchived with nothing left highlighted to retry from. The other two// bulk loops catch per item; this one has to as well.- const source = await sidebarSource();+ const source = APP_SIDEBAR;const archive = /async function archiveSelected\(([\s\S]*?)\n \}/.exec(source);assert.ok(archive, "no archiveSelected");const body = archive[1];@@ -126,7 +122,7 @@ test("one failed archive does not abandon the rest of the batch", async () => {test("deleting folders in bulk cleans up like deleting one", async () => {// Both branches end the same way, or a batch leaves stale chat rows behind// and strands the user on a page whose project is gone.- const source = await sidebarSource();+ const source = APP_SIDEBAR;const branch = /if \(target\.kind === "projects"\) \{([\s\S]*?)\n return;/.exec(source,);@@ -150,7 +146,7 @@ test("both sidebar expanders read translated labels", async () => {// The two sit one control apart, so an English literal next to a translated// twin is the visible half of the omission.// Comments name the control too, so match the rendered ternary, not the words.- const source = await sidebarSource();+ const source = APP_SIDEBAR;assert.equal(/\?\s*"Show less"\s*:\s*"Show more"/.test(source),false,diff --git a/studio/frontend/tests/sidebar-spinner-column.test.ts b/studio/frontend/tests/sidebar-spinner-column.test.tsindex 986e0795415..2b8518b48a4 100644--- a/studio/frontend/tests/sidebar-spinner-column.test.ts+++ b/studio/frontend/tests/sidebar-spinner-column.test.ts@@ -2,9 +2,12 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readSrc } from "./helpers/kit.ts";++const APP_SIDEBAR = readSrc("components/app-sidebar.tsx");+// Both spinners are ml-auto, so each one sits at its row's padding-right plus// its own margin-right. The two rows carry different padding, so the margins// have to make up the difference or the column visibly steps.@@ -22,30 +25,26 @@ function grab(source: string, pattern: RegExp, what: string): string {}test("nav and Recents spinners land on one trailing column", async () => {- const source = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );const navRow = grab(- source,+ APP_SIDEBAR,/className="(sidebar-nav-btn h-\[33px\] rounded-full[^"]*)"/,"NavItem row",);const navSpinner = grab(- source,+ APP_SIDEBAR,/<Spinner className="(ml-auto[^"]*group-data-\[collapsible=icon\]:hidden)"/,"NavItem spinner",);const chatRow = grab(- source,+ APP_SIDEBAR,// Row height is a density choice and moves independently of the trailing// column, so match any h-[Npx]; cursor-pointer is what makes this the chat row./"(sidebar-nav-btn h-\[\d+px\] cursor-pointer rounded-full[^"]*)"/,"Recents chat row",);const chatSpinner = grab(- source,+ APP_SIDEBAR,/data-testid="chat-row-spinner"[\s\S]{0,400}?className="(ml-auto[^"]*)"/,"Recents chat spinner",);@@ -64,8 +63,8 @@ test("nav and Recents spinners land on one trailing column", async () => {// The kebab overlays the row's right edge, so a spinner row must pad past it.test("a working Recents row clears the kebab on hover", async () => {const [source, css] = await Promise.all([- readFile(new URL("../src/components/app-sidebar.tsx", import.meta.url), "utf8"),- readFile(new URL("../src/index.css", import.meta.url), "utf8"),+ readSrc("components/app-sidebar.tsx"),+ readSrc("index.css"),]);const kebabInset =@@ -153,8 +152,8 @@ test("a pending row is marked so both renderers can show its tooltip", async ()test("the expanded row and the flyout both show a pending tooltip", async () => {const [sidebar, appSidebar] = await Promise.all([- readFile(new URL("../src/components/ui/sidebar.tsx", import.meta.url), "utf8"),- readFile(new URL("../src/components/app-sidebar.tsx", import.meta.url), "utf8"),+ readSrc("components/ui/sidebar.tsx"),+ readSrc("components/app-sidebar.tsx"),]);// The rail-only rule has to make an exception, or an enabled row is silent while expanded.@@ -177,12 +176,8 @@ test("the expanded row and the flyout both show a pending tooltip", async () =>});test("both capability rows carry a pending tooltip", async () => {- const source = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );for (const row of ["train", "video"]) {- const block = source.slice(source.indexOf(` ${row}: {`));+ const block = APP_SIDEBAR.slice(APP_SIDEBAR.indexOf(` ${row}: {`));const body = block.slice(0, block.indexOf("\n },"));assert.match(body,@@ -213,14 +208,10 @@ test("a measured row is left exactly as it was", async () => {// Two render sites take these props: the inline rows and the More flyout. A row moved into// More by Settings -> Appearance must not go back to rendering the guess.test("both nav render sites resolve pending the same way", async () => {- const source = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );- const resolves = source.match(/const rowState = resolveNavRowState\(row\);/g) ?? [];+ const resolves = APP_SIDEBAR.match(/const rowState = resolveNavRowState\(row\);/g) ?? [];assert.equal(resolves.length, 2, `expected both render sites to resolve, got ${resolves.length}`);// And neither passes the raw fields past it.for (const raw of ["disabled={row.disabled}", "tooltip={row.tooltip}", "spinner={row.spinner}"]) {- assert.ok(!source.includes(raw), `a render site still passes ${raw} unresolved`);+ assert.ok(!APP_SIDEBAR.includes(raw), `a render site still passes ${raw} unresolved`);}});diff --git a/studio/frontend/tests/sidebar-touch-reorder.test.ts b/studio/frontend/tests/sidebar-touch-reorder.test.tsindex 5d05a47bdc6..7cf09af9dd1 100644--- a/studio/frontend/tests/sidebar-touch-reorder.test.ts+++ b/studio/frontend/tests/sidebar-touch-reorder.test.ts@@ -2,20 +2,16 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readSrc, readSrcAsync } from "./helpers/kit.ts";++const APP_SIDEBAR = readSrc("components/app-sidebar.tsx");+// Touch never fires dragstart, so the row menu is the only way to reorder a// list there. A menu behind a trigger without sidebar-touch-reveal is inert on// coarse pointers, which silently takes manual ordering away from touch users.-async function sidebarSource(): Promise<string> {- return readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",- );-}-/** The className string of the button carrying `label`. */function actionClassFor(source: string, label: string): string {const match = new RegExp(@@ -27,17 +23,14 @@ function actionClassFor(source: string, label: string): string {test("only sidebar-touch-reveal actions work on a coarse pointer", async () => {// The rule the rest of this file depends on.- const css = await readFile(- new URL("../src/index.css", import.meta.url),- "utf8",- );+ const css = await readSrcAsync("index.css");const coarse = /@media \(pointer: coarse\) \{([\s\S]*?)\n\t\}/.exec(css);assert.ok(coarse, "no coarse-pointer block in index.css");assert.match(coarse[1], /\.sidebar-row-action\.sidebar-touch-reveal/);});test("rows that reorder can open their menu on touch", async () => {- const source = await sidebarSource();+ const source = APP_SIDEBAR;// Chat rows, both variants.const chatActions = source.match(/"sidebar-row-action[^"]*"/g) ?? [];@@ -58,7 +51,7 @@ test("rows that reorder can open their menu on touch", async () => {test("a folder row reserves the room its touch actions take", async () => {// Revealed without reserved padding, the buttons sit on top of the name.- const source = await sidebarSource();+ const source = APP_SIDEBAR;const row = /className="(sidebar-nav-btn h-\[33px\] rounded-full gap-\[8\.5px\][^"]*group-hover\/recent-item:pr-16[^"]*)"/.exec(source,);diff --git a/studio/frontend/tests/sidebar-unread-dot.test.ts b/studio/frontend/tests/sidebar-unread-dot.test.tsindex 235762597b8..78df6080bd7 100644--- a/studio/frontend/tests/sidebar-unread-dot.test.ts+++ b/studio/frontend/tests/sidebar-unread-dot.test.ts@@ -5,13 +5,11 @@// node suite has no DOM to mount the sidebar in.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const SIDEBAR = readFileSync(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const SIDEBAR = readSrc("components/app-sidebar.tsx");test("the unread dot is grey", () => {assert.match(SIDEBAR, /size-2 rounded-full bg-muted-foreground\/60/);diff --git a/studio/frontend/tests/sidebar-width.test.ts b/studio/frontend/tests/sidebar-width.test.tsindex 861bd45e3fd..93dd37686eb 100644--- a/studio/frontend/tests/sidebar-width.test.ts+++ b/studio/frontend/tests/sidebar-width.test.ts@@ -3,7 +3,8 @@import assert from "node:assert/strict";import test from "node:test";-import { readFile } from "node:fs/promises";++import { readSrcAsync } from "./helpers/kit.ts";// Every localStorage key written by a panel width store.const PANEL_WIDTH_KEYS = ["sidebar_width", "chat_settings_width"];@@ -58,10 +59,7 @@ test("re-evaluates the cap per call, so a resize can re-clamp", () => {// The reset action promises to clear every stored preference, so a persisted// panel width that is missing from the list survives the reload.test("persisted panel widths are cleared by the preference reset", async () => {- const source = await readFile(- new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("features/settings/tabs/general-tab.tsx");const keys = source.slice(source.indexOf("const PREFS_KEYS"),source.indexOf("];", source.indexOf("const PREFS_KEYS")),diff --git a/studio/frontend/tests/spec-fallback-partial-offload-copy.test.ts b/studio/frontend/tests/spec-fallback-partial-offload-copy.test.tsindex f2937f704b7..831087ea863 100644--- a/studio/frontend/tests/spec-fallback-partial-offload-copy.test.ts+++ b/studio/frontend/tests/spec-fallback-partial-offload-copy.test.ts@@ -2,16 +2,14 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";+import { readSrc } from "./helpers/kit.ts";+// specFallbackMessage is a module-local helper inside a .tsx, which this runner// cannot import (it strips types but does not transform JSX), so the file is read// as source -- the same guard the other chat-settings-sheet tests use.-const settings = readFileSync(- new URL("../src/features/chat/chat-settings-sheet.tsx", import.meta.url),- "utf8",-);+const settings = readSrc("features/chat/chat-settings-sheet.tsx");test("the Hybrid Mamba partial-offload stand-down has its own notice", () => {const branch = settings.match(diff --git a/studio/frontend/tests/streaming-has-prefix.test.ts b/studio/frontend/tests/streaming-has-prefix.test.tsindex ea1331dbcf4..52c3d9d2369 100644--- a/studio/frontend/tests/streaming-has-prefix.test.ts+++ b/studio/frontend/tests/streaming-has-prefix.test.ts@@ -14,11 +14,12 @@*/import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { hasPrefix } from "../src/components/assistant-ui/streaming-render-schedule.ts";+import { readSrc } from "./helpers/kit.ts";+const CORPUS = ["","a",@@ -121,12 +122,8 @@ test("hasPrefix agrees with startsWith under randomised growth", () => {// helper cannot express takes a start position and compares a fixed block, so// it does not grow with the reply and is left alone.test("the incremental cache tests prefixes without scanning the reply", () => {- const source = readFileSync(- new URL(- "../src/components/assistant-ui/streaming-render-schedule.ts",- import.meta.url,- ),- "utf8",+ const source = readSrc(+ "components/assistant-ui/streaming-render-schedule.ts",);const bare = [...source.matchAll(/\.startsWith\(([^)]*)\)/g)].filter((match) => !match[1].includes(","),diff --git a/studio/frontend/tests/stt-download-mirror-policy.test.ts b/studio/frontend/tests/stt-download-mirror-policy.test.tsindex 2687e00292c..c50cb52183d 100644--- a/studio/frontend/tests/stt-download-mirror-policy.test.ts+++ b/studio/frontend/tests/stt-download-mirror-policy.test.ts@@ -2,16 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const source = readFileSync(- new URL(- "../src/features/settings/lib/stt-download-mirror.ts",- import.meta.url,- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/settings/lib/stt-download-mirror.ts");test("an adopted STT transfer keeps progress and merges its Voice owner", () => {assert.match(diff --git a/studio/frontend/tests/stuck-generation-run.test.ts b/studio/frontend/tests/stuck-generation-run.test.tsindex 8c2c1e24d1b..521115cf993 100644--- a/studio/frontend/tests/stuck-generation-run.test.ts+++ b/studio/frontend/tests/stuck-generation-run.test.ts@@ -10,14 +10,13 @@// generating" from storage alone, and no loop may run without a bound.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import { register } from "node:module";import test, { afterEach } from "node:test";-import { fileURLToPath } from "node:url";import type { ChatGenerationRun } from "../src/features/chat/api/chat-generation-api.ts";import {installLocalStorageFake,+ readText,registerBundlerResolver,} from "./helpers/kit.ts";@@ -25,9 +24,6 @@ register("./helpers/settings-api-resolver.mjs", import.meta.url);registerBundlerResolver();installLocalStorageFake();-const read = (relative: string): string =>- readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");-const originalFetch = globalThis.fetch;afterEach(() => {globalThis.fetch = originalFetch;@@ -188,7 +184,7 @@ test("the reload path gates the running status on corroboration", () => {// Source-pinned: toThreadMessage needs a MessageRecord and the module's whole import// graph, so the rule is asserted where it sits. Losing the call restores the wedge// while every behavioural test stays green.- const provider = read("../src/features/chat/runtime-provider.tsx");+ const provider = readText("../src/features/chat/runtime-provider.tsx");const gate = provider.indexOf("generationIsCorroboratedLive(custom, m.threadId)");assert.ok(gate > 0, "toThreadMessage no longer asks whether the run is live");assert.match(@@ -210,7 +206,7 @@ test("the reload path gates the running status on corroboration", () => {});test("the interrupted restore keeps the partial body untouched", () => {- const provider = read("../src/features/chat/runtime-provider.tsx");+ const provider = readText("../src/features/chat/runtime-provider.tsx");// The only content assignment in toThreadMessage is the clone of the stored parts.// Nothing between the gate and the return may drop or truncate it.const start = provider.indexOf("function toThreadMessage(");@@ -406,7 +402,7 @@ test("the default deadline outlasts any reasonable generation", () => {// C. the stop path after a reloadtest("stopChatThread falls back to the server when the registries are empty", () => {- const api = read("../src/features/chat/utils/stop-chat-thread.ts");+ const api = readText("../src/features/chat/utils/stop-chat-thread.ts");assert.match(api,/getActiveChatGenerationRuns/,@@ -431,7 +427,7 @@ test("a failed second active-run read leaves the thread unanswered", () => {// Source-pinned for the same reason as the gate above. `missed` proves the first list// predates the run, so keeping it AND recording it as an answer would restore a live// reply as interrupted and re-enable a conflicting send.- const provider = read("../src/features/chat/runtime-provider.tsx");+ const provider = readText("../src/features/chat/runtime-provider.tsx");assert.match(provider, /let answered = true;/);assert.match(provider,@@ -446,7 +442,7 @@ test("a failed second active-run read leaves the thread unanswered", () => {});test("the recovery follower settles when the follow throws a stall", () => {- const provider = read("../src/features/chat/runtime-provider.tsx");+ const provider = readText("../src/features/chat/runtime-provider.tsx");assert.match(provider,/catch \(error\) \{\s*if \(!\(error instanceof ChatGenerationStalledError\)\) throw error;\s*followStalled = true;\s*\}/,@@ -507,7 +503,7 @@ test("a locally interrupted follower is not revived by the benefit of the doubt"});test("the marker is cleared when the server corroborates the run", () => {- const provider = read("../src/features/chat/runtime-provider.tsx");+ const provider = readText("../src/features/chat/runtime-provider.tsx");assert.match(provider,/generationLocallyInterrupted: false,/,@@ -531,7 +527,7 @@ test("the marker is cleared when the server corroborates the run", () => {});test("a legacy fallback releases the durable claim at once", () => {- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");const fallback = adapter.indexOf('generationDecision = "legacy";\n //');assert.ok(fallback > 0, "the legacy-fallback branch moved");const release = adapter.indexOf("releaseLiveGenerationRun(cancelId);", fallback);@@ -548,7 +544,7 @@ test("the initial durable stream marks itself interrupted when it stalls", () =>// metadata still reads running and unsettled. Without the marker, generationNeedsRecovery// stays true, the next reload attaches another follower, and the composer is blocked for// another full deadline.- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");const stream = adapter.indexOf("const durableStream = async function* () {");assert.ok(stream > 0, "the durable stream moved");const caught = adapter.indexOf("instanceof ChatGenerationStalledError", stream);@@ -597,7 +593,7 @@ test("a completed run overrides the local interruption marker", () => {});test("a failed initial active-run read retracts the earlier answer too", () => {- const provider = read("../src/features/chat/runtime-provider.tsx");+ const provider = readText("../src/features/chat/runtime-provider.tsx");assert.match(provider,/if \(!activeGenerationRunsLoaded\) \{[^]*?markServerActiveGenerationRunsUnknown\(remoteId\)/,@@ -606,7 +602,7 @@ test("a failed initial active-run read retracts the earlier answer too", () => {});test("the lease is renewed while the model is being prepared", () => {- const runs = read("../../backend/core/inference/chat_generation_runs.py");+ const runs = readText("../../backend/core/inference/chat_generation_runs.py");assert.match(runs, /_renew_lease_while_preparing/);assert.match(runs,@@ -711,7 +707,7 @@ test("a run finished between the two reads never reaches the durable registry",// The registry sync runs BEFORE the overlay, so skipping only at the overlay left the// thread reading as durable. In another tab nothing removes that mapping, and the next// subscriber-owned stream on the thread would be capped and lose its tail.- const provider = read("../src/features/chat/runtime-provider.tsx");+ const provider = readText("../src/features/chat/runtime-provider.tsx");const filter = provider.indexOf("terminalMessageRuns");const sync = provider.indexOf("syncServerActiveGenerationRuns(", filter);assert.ok(filter > 0, "the terminal-message filter is missing");@@ -723,7 +719,6 @@ test("a run finished between the two reads never reaches the durable registry",);});-test("a pre-admission claim does not make the thread bounded yet", () => {resetServerActiveGenerationRuns();// The claim is taken before the create POST so a recovery trigger during that await@@ -752,7 +747,6 @@ test("releasing a provisional claim clears it rather than leaving it bounded", (releaseLiveGenerationRun("run-2");});-test("a repeated keep-alive stamp does NOT hold the follower open", async () => {// The other half of the rule above, and the case the whole frontend fallback exists for:// a wedged producer with a healthy socket. The server keeps sending keep-alives, but the@@ -885,7 +879,7 @@ test("a stalled follower fences the server run before offering Continue", () =>// Settling only in this tab leaves the row queued/running/cancelling, and create_run// refuses a thread that already has an active generation, so Continue and the next// message would both 409 against a reply the UI had just declared finished.- const provider = read("../src/features/chat/runtime-provider.tsx");+ const provider = readText("../src/features/chat/runtime-provider.tsx");const settle = provider.indexOf("followStalled || generationNeedsRecovery(currentMetadata)");assert.ok(settle > 0, "the stall settle branch moved");const commit = provider.indexOf("incomplete: { reason: \"interrupted\" as const }", settle);diff --git a/studio/frontend/tests/studio-tool-history.test.ts b/studio/frontend/tests/studio-tool-history.test.tsindex eaa85f72cb6..0e4f65da689 100644--- a/studio/frontend/tests/studio-tool-history.test.ts+++ b/studio/frontend/tests/studio-tool-history.test.ts@@ -2,15 +2,15 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import {hasOnlyStudioOwnedToolHistory,studioToolHistoryRequestFields,} from "../src/features/chat/utils/studio-tool-history.ts";+import { readSrc } from "./helpers/kit.ts";+function assistantToolCall(provenance?: unknown) {return {role: "assistant",@@ -107,12 +107,7 @@ test("ownership ignores hosted builtins that OpenAI replay drops", () => {});test("the live request and token-count paths mark ownership after replay", () => {- const adapter = readFileSync(- fileURLToPath(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- ),- "utf8",- );+ const adapter = readSrc("features/chat/api/chat-adapter.ts");const helper = adapter.indexOf("function studioToolHistoryRequestFieldsAfterReplay",);@@ -139,15 +134,7 @@ test("the live request and token-count paths mark ownership after replay", () =>});test("the context recount forwards the tool-history request fields", () => {- const source = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/utils/refresh-context-usage.ts",- import.meta.url,- ),- ),- "utf8",- );+ const source = readSrc("features/chat/utils/refresh-context-usage.ts");const historyBuild = source.indexOf("const countHistory = await buildLocalTokenCountHistory(",);diff --git a/studio/frontend/tests/system-status-verdict.test.ts b/studio/frontend/tests/system-status-verdict.test.tsindex fa8144c6436..adbc306207a 100644--- a/studio/frontend/tests/system-status-verdict.test.ts+++ b/studio/frontend/tests/system-status-verdict.test.ts@@ -11,17 +11,12 @@// rendering it told an AMD/ROCm user "No visible GPU detected".import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-const tabSrc = await readFile(- new URL("../src/features/settings/tabs/resources-tab.tsx", import.meta.url),- "utf8",-);-const hookSrc = await readFile(- new URL("../src/hooks/use-system.ts", import.meta.url),- "utf8",-);+import { readSrcAsync } from "./helpers/kit.ts";++const tabSrc = await readSrcAsync("features/settings/tabs/resources-tab.tsx");+const hookSrc = await readSrcAsync("hooks/use-system.ts");function lift(src: string, pattern: RegExp, what: string, where: string): string {const found = pattern.exec(src);diff --git a/studio/frontend/tests/tauri-log-follow.test.ts b/studio/frontend/tests/tauri-log-follow.test.tsindex 7f6ebcc474a..5f1bc1eb7fd 100644--- a/studio/frontend/tests/tauri-log-follow.test.ts+++ b/studio/frontend/tests/tauri-log-follow.test.ts@@ -6,7 +6,6 @@// only acceptable if that scroll-up wins until they come back down on their own.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {@@ -14,6 +13,8 @@ import {isFollowingTail,} from "../src/components/tauri/log-follow.ts";+import { readSrcAsync } from "./helpers/kit.ts";+/** A log box 100px tall holding 500px of lines: 400px of travel, bottom at 400. */const TALL = { scrollHeight: 500, clientHeight: 100 };@@ -55,10 +56,7 @@ test("a closed panel reports zeroes and stays armed to follow", () => {});test("LogDetails drives its scrolling through the shared predicate", async () => {- const source = await readFile(- new URL("../src/components/tauri/log-details.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("components/tauri/log-details.tsx");assert.match(source, /isFollowingTail\(log\)/);assert.match(source, /onScroll=\{handleScroll\}/);diff --git a/studio/frontend/tests/thread-ancestor-has-scope.test.ts b/studio/frontend/tests/thread-ancestor-has-scope.test.tsindex 3fbd79f4cae..097132b0bf5 100644--- a/studio/frontend/tests/thread-ancestor-has-scope.test.ts+++ b/studio/frontend/tests/thread-ancestor-has-scope.test.ts@@ -44,19 +44,16 @@*/import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import ts from "typescript";import { openingTag } from "./helpers/tsx-ast.ts";-const read = (rel: string): string =>- readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8");+import { readText } from "./helpers/kit.ts";const parse = (rel: string): ts.SourceFile =>- ts.createSourceFile(rel, read(rel), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ ts.createSourceFile(rel, readText(rel), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);/** Every string literal in the file, so a className built by `cn(...)` is covered too. */const stringLiterals = (source: ts.SourceFile): string[] => {diff --git a/studio/frontend/tests/thread-delete-render-budget.test.ts b/studio/frontend/tests/thread-delete-render-budget.test.tsindex 13c56713eae..5a1567610b5 100644--- a/studio/frontend/tests/thread-delete-render-budget.test.ts+++ b/studio/frontend/tests/thread-delete-render-budget.test.ts@@ -12,14 +12,11 @@// delete is linear in thread length again.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-function source(path: string): string {- return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");-}+import { readSrc } from "./helpers/kit.ts";-const thread = source("components/assistant-ui/thread.tsx");+const thread = readSrc("components/assistant-ui/thread.tsx");function block(start: string): string {const [, rest] = thread.split(start, 2);diff --git a/studio/frontend/tests/thread-part-components-stable.test.ts b/studio/frontend/tests/thread-part-components-stable.test.tsindex c66252e4d3f..b924206b499 100644--- a/studio/frontend/tests/thread-part-components-stable.test.ts+++ b/studio/frontend/tests/thread-part-components-stable.test.ts@@ -15,10 +15,9 @@ import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";-const THREAD_SOURCE = readFileSync(- new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const THREAD_SOURCE = readSrc("components/assistant-ui/thread.tsx");test("the assistant part components are not an inline object literal", () => {// `components={{` is the regression's exact shape: an inline JSX literal, sodiff --git a/studio/frontend/tests/thread-scoped-pairing-composition.test.ts b/studio/frontend/tests/thread-scoped-pairing-composition.test.tsindex 2aeba6d43f4..400cf94cdb6 100644--- a/studio/frontend/tests/thread-scoped-pairing-composition.test.ts+++ b/studio/frontend/tests/thread-scoped-pairing-composition.test.ts@@ -13,17 +13,15 @@// module-stubs.ts: only tests that need the TypeScript compiler should pay to load it.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import ts from "typescript";+import { readSrc } from "./helpers/kit.ts";+const source = ts.createSourceFile("runtime-provider.tsx",- readFileSync(- new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),- "utf8",- ),+ readSrc("features/chat/runtime-provider.tsx"),ts.ScriptTarget.ES2022,true,ts.ScriptKind.TSX,diff --git a/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts b/studio/frontend/tests/thread-scoped-pairing-invariants.test.tsindex 9ecf20f9d4d..1cd8699539e 100644--- a/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts+++ b/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts@@ -12,16 +12,13 @@// graph, so it cannot be loaded in a bare node test. The sibling store tests do the same.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-function read(path: string): string {- return readFileSync(new URL(path, import.meta.url), "utf8");-}+import { readText } from "./helpers/kit.ts";-const store = read("../src/features/chat/stores/chat-runtime-store.ts");-const provider = read("../src/features/chat/runtime-provider.tsx");-const composer = read("../src/components/assistant-ui/thread.tsx");+const store = readText("../src/features/chat/stores/chat-runtime-store.ts");+const provider = readText("../src/features/chat/runtime-provider.tsx");+const composer = readText("../src/components/assistant-ui/thread.tsx");function slice(source: string, from: string, to: string): string {const start = source.indexOf(from);@@ -80,7 +77,7 @@ test("the pairing wait still outlasts the worst case read chain", () => {assert.ok(match, `${name} not found`);return Number(match[1].replace(/_/g, ""));};- const store = read("../src/features/chat/stores/chat-runtime-store.ts");+ const store = readText("../src/features/chat/stores/chat-runtime-store.ts");const attempts = constant(provider, "THREAD_READ_RETRIES") + 1;const worstCase =@@ -318,7 +315,7 @@ test("the read that gates sends cannot hang forever", () => {test("every run waits for the chat's settings, not just the composer", () => {// Reload, Continue and send-from-edit never touch handleSubmit; they all reach the// adapter, so the wait belongs there.- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");const run = slice(adapter, "await useChatRuntimeStore.getState().hydratePersistedSettings();", "let runtime =");assert.match(run, /await awaitThreadScopedPairing\(runThreadId\)/);});@@ -358,7 +355,7 @@ test("the run's wait is bound to the run's own chat", () => {const wait = slice(store, "export function awaitThreadScopedPairing", "\n}");assert.match(wait, /threadId: string \| null \| undefined/);assert.match(wait, /pairingSettledByThreadId\.get\(threadId\)/);- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");assert.match(adapter, /await awaitThreadScopedPairing\(runThreadId\)/);});@@ -419,7 +416,7 @@ test("the thread read that gates sends aborts when it times out", () => {test("a read nobody is waiting for any more is cancelled", () => {const effect = slice(provider, "const reads = new Set<AbortController>();", "\n }, [activeThreadId");assert.match(effect, /abortReads\(\);/);- const api = read("../src/features/chat/api/chat-api.ts");+ const api = readText("../src/features/chat/api/chat-api.ts");const get = slice(api, "export async function getChatThread", "\n}");assert.match(get, /options\.timeoutMs !== undefined/);assert.match(get, /combineAbortSignals\(\[timeout\.signal, options\.signal\]\)/);@@ -428,7 +425,7 @@ test("a read nobody is waiting for any more is cancelled", () => {test("the ensure step in front of a settings write is bounded too", () => {// It runs BEFORE the write, so neither the caller's signal nor the write timeout// reaches it, and a stall there leaves the whole per-thread chain pending.- const storage = read("../src/features/chat/utils/chat-history-storage.ts");+ const storage = readText("../src/features/chat/utils/chat-history-storage.ts");const update = slice(storage, "export async function updateStoredChatThread", "\n}");assert.match(update, /ensureStoredChatThread\(threadId, undefined, \{/);assert.match(update, /bounded: true/);@@ -542,7 +539,7 @@ test("a run whose pairing never settled is refused, not run on another chat's seconst wait = slice(store, "export function awaitThreadScopedPairing", "\n}");assert.match(wait, /Promise<boolean>/);assert.match(wait, /resolve\(false\)/);- const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const adapter = readText("../src/features/chat/api/chat-adapter.ts");assert.match(adapter, /if \(!\(await awaitThreadScopedPairing\(runThreadId\)\)\) \{/);assert.match(adapter, /the message was not sent/);});@@ -648,8 +645,8 @@ test("only a user edit to a sampling param lands on the chat", () => {);// Both paths that apply a model's own params say so.- const runtime = read("../src/features/chat/hooks/use-chat-model-runtime.ts");- const status = read("../src/features/chat/lib/apply-inference-status-to-store.ts");+ const runtime = readText("../src/features/chat/hooks/use-chat-model-runtime.ts");+ const status = readText("../src/features/chat/lib/apply-inference-status-to-store.ts");for (const source of [runtime, status]) {assert.match(source,@@ -699,7 +696,7 @@ test("a model's recommendation does not overwrite the chat's sampling", () => {// user just asked for arrives with the previous mode's temperature and top-p. The// load-time path applies the same table unasked, so it stays marked.test("toggling Think applies its params even in a chat that pins sampling", () => {- const qwen = read("../src/features/chat/utils/qwen-params.ts");+ const qwen = readText("../src/features/chat/utils/qwen-params.ts");assert.match(qwen, /store\.setParams\(\{ \.\.\.store\.params, \.\.\.params \}\);/);assert.doesNotMatch(qwen,@@ -707,7 +704,7 @@ test("toggling Think applies its params even in a chat that pins sampling", () ="the toggle is treated as a model default, so a pinned chat never changes mode params",);// The post-load application of the same table stays marked.- const runtime = read("../src/features/chat/hooks/use-chat-model-runtime.ts");+ const runtime = readText("../src/features/chat/hooks/use-chat-model-runtime.ts");const post = slice(runtime, "store.setParams({ ...store.params, ...p }", "\n }");assert.match(post, /fromModelDefaults: true/);});diff --git a/studio/frontend/tests/titlebar-modal-layering.test.ts b/studio/frontend/tests/titlebar-modal-layering.test.tsindex caf66e8b24a..c52491c2331 100644--- a/studio/frontend/tests/titlebar-modal-layering.test.ts+++ b/studio/frontend/tests/titlebar-modal-layering.test.ts@@ -2,11 +2,9 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-const source = (path: string) =>- readFile(new URL(`../src/${path}`, import.meta.url), "utf8");+import { readSrc } from "./helpers/kit.ts";const Z_INDEX_PATTERN = /z-\[(\d+)\]|\bz-(\d+)\b/;const DECORATION_PATTERN =@@ -27,9 +25,9 @@ function zIndex(block: string): number {test("titlebar decoration stays below modal backdrops and window controls", async () => {const [titlebar, dialog, alertDialog] = await Promise.all([- source("components/tauri/window-titlebar.tsx"),- source("components/ui/dialog.tsx"),- source("components/ui/alert-dialog.tsx"),+ readSrc("components/tauri/window-titlebar.tsx"),+ readSrc("components/ui/dialog.tsx"),+ readSrc("components/ui/alert-dialog.tsx"),]);const decoration = titlebar.match(DECORATION_PATTERN);@@ -52,7 +50,7 @@ test("titlebar decoration stays below modal backdrops and window controls", asyn});test("below-titlebar decoration is not trapped in the titlebar stacking context", async () => {- const titlebar = await source("components/tauri/window-titlebar.tsx");+ const titlebar = await readSrc("components/tauri/window-titlebar.tsx");const decorationIndex = titlebar.indexOf('data-slot="window-titlebar-decoration"',);diff --git a/studio/frontend/tests/tool-activity-preference.test.ts b/studio/frontend/tests/tool-activity-preference.test.tsindex 07ff4d4f11d..101b65b2aa0 100644--- a/studio/frontend/tests/tool-activity-preference.test.ts+++ b/studio/frontend/tests/tool-activity-preference.test.ts@@ -11,13 +11,13 @@// Rendered behaviour lives in tests/studio/playwright_tool_activity.py.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import ts from "typescript";import {installLocalStorageFake,+ readText,registerBundlerResolver,} from "./helpers/kit.ts";@@ -50,8 +50,6 @@ const { resolveToolActivityOpen, syncToolActivityPreference } = await import("../src/components/assistant-ui/tool-activity-open-state.ts");-const read = (path: string) => readFile(new URL(path, import.meta.url), "utf8");-/** Write `state` as a persisted record and hydrate the live store from it. */async function rehydrateFrom(state: unknown): Promise<void> {store.set(PREFERENCES_KEY, JSON.stringify({ state, version: 0 }));@@ -247,7 +245,7 @@ test("disabling collapsed activity respects a closed fallback default", () => {const sourceOf = async (path: string): Promise<ts.SourceFile> =>ts.createSourceFile(path,- await read(path),+ await readText(path),ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX,diff --git a/studio/frontend/tests/tool-call-arguments-precision.test.ts b/studio/frontend/tests/tool-call-arguments-precision.test.tsindex 73ba7b85d66..6e7aa1b1471 100644--- a/studio/frontend/tests/tool-call-arguments-precision.test.ts+++ b/studio/frontend/tests/tool-call-arguments-precision.test.ts@@ -2,9 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import {mergedToolCallArgumentsText,@@ -12,6 +10,8 @@ import {toolCallReplayArguments,} from "../src/features/chat/tool-call-arguments.ts";+import { readSrc } from "./helpers/kit.ts";+const WIRE ='{"arguments":{"id":9007199254740993},"arguments_text":"{\\"id\\":9007199254740993}"}';@@ -97,21 +97,8 @@ test("prompt replay prefers exact parsable argument text", () => {});// Read as source: the helpers only hold the line if the adapter routes through them.-const ADAPTER = readFileSync(- fileURLToPath(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- ),- "utf8",-);-const PROMPT_STORAGE = readFileSync(- fileURLToPath(- new URL(- "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",- import.meta.url,- ),- ),- "utf8",-);+const ADAPTER = readSrc("features/chat/api/chat-adapter.ts");+const PROMPT_STORAGE = readSrc("features/chat/prompt-storage/prompt-storage-dialog.tsx");test("the adapter builds tool-call argument text through the helpers", () => {assert.match(ADAPTER, /toolCallArgumentsText\(\s*toolEvent\.arguments_text/);diff --git a/studio/frontend/tests/trailing-placeholder-prefix-safety.test.ts b/studio/frontend/tests/trailing-placeholder-prefix-safety.test.tsindex f3fc582ed27..fc287da5166 100644--- a/studio/frontend/tests/trailing-placeholder-prefix-safety.test.ts+++ b/studio/frontend/tests/trailing-placeholder-prefix-safety.test.ts@@ -2,11 +2,12 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { stripTrailingTemplatePlaceholder } from "../src/features/chat/utils/trailing-template-placeholder.ts";+import { readSrc } from "./helpers/kit.ts";+/*** #9098. The trailing `${...}` strip is a statement about a FINISHED reply: a* provider occasionally leaves a fragment on the end of an otherwise complete@@ -300,10 +301,7 @@ test("randomised replies keep the two placements apart", () => {// ---------------------------------------------------------- the shipped placement ----const ADAPTER = readFileSync(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- "utf8",-);+const ADAPTER = readSrc("features/chat/api/chat-adapter.ts");/*** Which of the two modes above the adapter is actually running.diff --git a/studio/frontend/tests/training-ui-preferences.test.ts b/studio/frontend/tests/training-ui-preferences.test.tsindex 35c1de93771..c72cbbaebc2 100644--- a/studio/frontend/tests/training-ui-preferences.test.ts+++ b/studio/frontend/tests/training-ui-preferences.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";import {@@ -13,6 +12,8 @@ import {TRAINING_UI_PREFERENCE_KEYS,} from "../src/features/training/lib/training-ui-preferences.ts";+import { readSrcAsync } from "./helpers/kit.ts";+test("the training UI preference list contains every owned storage key once", () => {assert.deepEqual(TRAINING_UI_PREFERENCE_KEYS, [TRAINING_MODEL_PICKER_TAB_STORAGE_KEY,@@ -27,10 +28,7 @@ test("the training UI preference list contains every owned storage key once", ()});test("reset all local preferences includes the training UI preference list", async () => {- const source = await readFile(- new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),- "utf8",- );+ const source = await readSrcAsync("features/settings/tabs/general-tab.tsx");const start = source.indexOf("const PREFS_KEYS");const keys = source.slice(start, source.indexOf("];", start));assert.ok(keys.includes("...TRAINING_UI_PREFERENCE_KEYS"));diff --git a/studio/frontend/tests/training-upgrade-gate-contract.test.ts b/studio/frontend/tests/training-upgrade-gate-contract.test.tsindex 065a359d051..06738e295e0 100644--- a/studio/frontend/tests/training-upgrade-gate-contract.test.ts+++ b/studio/frontend/tests/training-upgrade-gate-contract.test.ts@@ -9,22 +9,19 @@// guard against the gate being dropped from either one.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";+import { readText } from "./helpers/kit.ts";+const START_PATHS = ["../src/features/training/lib/start-fresh-training-run.ts","../src/features/training/lib/resume-training-run.ts",] as const;-function read(relative: string): string {- return readFileSync(new URL(relative, import.meta.url), "utf8");-}-test("both training start paths consult the transformers-upgrade gate", () => {for (const file of START_PATHS) {assert.ok(- read(file).includes("confirmTrainingTransformersUpgrade"),+ readText(file).includes("confirmTrainingTransformersUpgrade"),`${file} must consult the transformers-upgrade gate: without it a model whose ` +"architecture no installed transformers ships is accepted and then dies at " +"model load, with no prompt and no way for the user to act on it",@@ -36,7 +33,7 @@ test("the upgrade dialog is raised before the custom-code dialog", () => {// Chat's order, and for the same reason: installing a newer transformers changes// what the load would even run, so consenting to the install has to come first.for (const file of START_PATHS) {- const source = read(file);+ const source = readText(file);const upgradeAt = source.indexOf("confirmTrainingTransformersUpgrade(");const remoteCodeAt = source.indexOf("confirmRemoteCodeIfNeeded(");// Both must be present: a missing call indexes to -1, which would otherwise@@ -66,7 +63,7 @@ test("both gates on a start path inspect the same copy of the model", () => {"resumeModelCachePin(",],] as const) {- const source = read(file);+ const source = readText(file);assert.equal(source.split(resolver).length - 1,3,@@ -78,13 +75,15 @@ test("both gates on a start path inspect the same copy of the model", () => {test("the resume gate names the run it precedes", () => {// Without the run id the check cannot tell that installing would permanently strand// a checkpoint attested against a 4-bit model load the latest sidecar refuses.- const source = read("../src/features/training/lib/resume-training-run.ts");+ const source = readText(+ "../src/features/training/lib/resume-training-run.ts",+ );assert.ok(source.includes("resumeRunId"));});test("the gate reaches the install through the shared consent dialog", () => {// Not a second implementation of the flow chat already owns.- const gate = read(+ const gate = readText("../src/features/training/lib/training-transformers-upgrade.ts",);assert.ok(gate.includes("confirmTransformersUpgradeIfNeeded"));@@ -96,7 +95,7 @@ test("the Configure preview re-asks the check after an install", () => {// the store counts completed installs and the hook keys its answers on that count.// Break either end and Configure keeps offering an install that already ran, and// 4-bit for a run the new sidecar loads in 16-bit.- const store = read(+ const store = readText("../src/features/transformers-upgrade/stores/transformers-upgrade-dialog-store.ts",);assert.ok(@@ -104,7 +103,7 @@ test("the Configure preview re-asks the check after an install", () => {"a successful install must advance sidecarGeneration",);- const hook = read(+ const hook = readText("../src/features/training/hooks/use-training-transformers-upgrade-notice.ts",);assert.ok(hook.includes("s.sidecarGeneration"));@@ -119,7 +118,7 @@ test("the consent dialog offers the custom-code way out before an install fails"// run can be. For a model shipping its own code the install is the more expensive way// forward, activating the 16-bit sidecar, so gating the fallback on the error phase// left a QLoRA run with Install or Cancel and no way to the 4-bit run it asked for.- const dialog = read(+ const dialog = readText("../src/features/transformers-upgrade/components/transformers-upgrade-dialog.tsx",);assert.ok(@@ -138,7 +137,7 @@ test("both start paths carry the upgrade gate's custom-code verdict forward", ()// scan request fails, and the stored flag is false on a fresh run. The upgrade check// has already answered the question, so it has to be the one that travels.for (const file of START_PATHS) {- const source = read(file);+ const source = readText(file);assert.ok(source.includes("verdict.requiresTrustRemoteCode = outcome.requiresTrustRemoteCode",diff --git a/studio/frontend/tests/transfer-stats-hook-hidden.test.ts b/studio/frontend/tests/transfer-stats-hook-hidden.test.tsindex 330a0982aea..cdd797e6613 100644--- a/studio/frontend/tests/transfer-stats-hook-hidden.test.ts+++ b/studio/frontend/tests/transfer-stats-hook-hidden.test.ts@@ -13,7 +13,6 @@// visible again.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -22,12 +21,11 @@ import {computeTransferStats,} from "../src/lib/transfer-stats.ts";+import { readSrc } from "./helpers/kit.ts";+const MB = 1e6;-const hookSource = readFileSync(- new URL("../src/features/chat/hooks/use-transfer-stats.ts", import.meta.url),- "utf8",-);+const hookSource = readSrc("features/chat/hooks/use-transfer-stats.ts");test("the shared hook skips sampling while the tab is hidden", () => {const guard = hookSource.indexOf("document.hidden");diff --git a/studio/frontend/tests/tray-server-status.test.ts b/studio/frontend/tests/tray-server-status.test.tsindex 6c93491a169..e117c2bd46e 100644--- a/studio/frontend/tests/tray-server-status.test.ts+++ b/studio/frontend/tests/tray-server-status.test.ts@@ -2,28 +2,18 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";+import { readSrc, readText } from "./helpers/kit.ts";+// The tray label is settled across two languages: the hook pushes a BackendStatus over the// IPC and main.rs turns it into a label and an enabled flag. Neither half can be rendered// here, so both are asserted against source, as the rest of the desktop startup tests do.// tray_toggle_label's own table is covered by the Rust unit tests in main.rs; only a test// spanning both files can hold that the two halves still agree on the set of statuses.-function hookSource(): Promise<string> {- return readFile(- new URL("../src/hooks/use-tauri-backend.ts", import.meta.url),- "utf8",- );-}--function tauriSource(): Promise<string> {- return readFile(- new URL("../../src-tauri/src/main.rs", import.meta.url),- "utf8",- );-}+const USE_TAURI_BACKEND = readSrc("hooks/use-tauri-backend.ts");+const MAIN = readText("../../src-tauri/src/main.rs");/*** The body of a `function name(...)` in the hook, to its closing brace. syncTrayStatus@@ -78,7 +68,7 @@ function actionableStatuses(hook: string): string[] {}test("every status the hook commits is also pushed to the tray", async () => {- const hook = await hookSource();+ const hook = USE_TAURI_BACKEND;// setStatus is reached through these three and nowhere else, so covering them// covers every transition the tray can be told about.@@ -100,7 +90,7 @@ test("every status the hook commits is also pushed to the tray", async () => {});test("a tray sync never surfaces on the web build or on a binary without the command", async () => {- const hook = await hookSource();+ const hook = USE_TAURI_BACKEND;const sync = hookFunction(hook, "syncTrayStatus");// The browser build has no IPC at all, so the import must not even be attempted.@@ -119,7 +109,8 @@ test("a tray sync never surfaces on the web build or on a binary without the com});test("the tray offers a click exactly when the listener would act on it", async () => {- const [hook, rust] = await Promise.all([hookSource(), tauriSource()]);+ const hook = USE_TAURI_BACKEND;+ const rust = MAIN;assert.deepEqual(enabledStatuses(rust),@@ -129,7 +120,7 @@ test("the tray offers a click exactly when the listener would act on it", async});test("an unlisted status falls through rather than going unhandled", async () => {- const rust = await tauriSource();+ const rust = MAIN;const table = trayToggleLabel(rust);// BackendStatus grows; the command takes a bare String. A wildcard arm keeps a new@@ -140,7 +131,7 @@ test("an unlisted status falls through rather than going unhandled", async () =>"tray_toggle_label has no wildcard arm for an unknown status",);- const hook = await hookSource();+ const hook = USE_TAURI_BACKEND;const union = hook.slice(hook.indexOf("export type BackendStatus ="),hook.indexOf(";", hook.indexOf("export type BackendStatus =")),@@ -156,7 +147,7 @@ test("an unlisted status falls through rather than going unhandled", async () =>});test("set_tray_server_status is registered, so the invoke can be answered", async () => {- const rust = await tauriSource();+ const rust = MAIN;const handler = rust.slice(rust.indexOf("invoke_handler(tauri::generate_handler!["),rust.indexOf("])", rust.indexOf("invoke_handler(tauri::generate_handler![")),@@ -169,7 +160,7 @@ test("set_tray_server_status is registered, so the invoke can be answered", asyn});test("the tray toggle starts clickable, for a frontend older than this binary", async () => {- const rust = await tauriSource();+ const rust = MAIN;const built = rust.match(/MenuItemBuilder::with_id\("toggle", "([^"]*)"\)([\s\S]{0,40}?)\.build\(app\)/,);diff --git a/studio/frontend/tests/tts-custom-connections-disabled.test.ts b/studio/frontend/tests/tts-custom-connections-disabled.test.tsindex 54c18208e20..d5490dacdf6 100644--- a/studio/frontend/tests/tts-custom-connections-disabled.test.ts+++ b/studio/frontend/tests/tts-custom-connections-disabled.test.ts@@ -5,11 +5,12 @@// whole enforcement; custom TTS posted assistant text with connections switched off.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import { loadWithStubs } from "./helpers/module-stubs.ts";+import { readSrc } from "./helpers/kit.ts";+type Adapter = {generateCustomTtsAudio: (text: string,@@ -340,10 +341,7 @@ test("custom TTS sends no key when the connection already has one saved", async// #9214: a deleted connection left ttsProviderId persisted, so the select pointed at a// missing item and every read aloud posted the stale id. Mirrors the dictation guard.test("the custom TTS selection is dropped when its connection disappears", () => {- const voiceTab = readFileSync(- new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url),- "utf8",- );+ const voiceTab = readSrc("features/settings/tabs/voice-tab.tsx");assert.match(voiceTab,/if \(ttsProviderId && !hasSelectedTtsConnection\) \{\s*setTtsProviderId\(""\);/,diff --git a/studio/frontend/tests/uncaptioned-image-empty-text-block.test.ts b/studio/frontend/tests/uncaptioned-image-empty-text-block.test.tsindex e687879d2c4..c09cd6ee0f6 100644--- a/studio/frontend/tests/uncaptioned-image-empty-text-block.test.ts+++ b/studio/frontend/tests/uncaptioned-image-empty-text-block.test.ts@@ -2,19 +2,14 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import ts from "typescript";+import { readSrc } from "./helpers/kit.ts";+// chat-adapter.ts drags in the stores, so lift the source; assistant is a stub.-const adapterSource = readFileSync(- fileURLToPath(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),- ),- "utf8",-);+const adapterSource = readSrc("features/chat/api/chat-adapter.ts");function liftAdapterFunction(opener: string): string {const start = adapterSource.indexOf(opener);diff --git a/studio/frontend/tests/update-banner-flex-priority.test.ts b/studio/frontend/tests/update-banner-flex-priority.test.tsindex 97ea09055dd..f10d59fce57 100644--- a/studio/frontend/tests/update-banner-flex-priority.test.ts+++ b/studio/frontend/tests/update-banner-flex-priority.test.ts@@ -13,23 +13,20 @@// Read from the source: the node suite has no DOM to compute styles in.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-function read(path: string): string {- return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");-}+import { readSrc } from "./helpers/kit.ts";-const TAURI = read("components/tauri/update-banner.tsx");-const WEB = read("components/web/update-banner.tsx");-const LLAMA = read("components/llama-update-banner.tsx");-const LLAMA_CHANGELOG = read(+const TAURI = readSrc("components/tauri/update-banner.tsx");+const WEB = readSrc("components/web/update-banner.tsx");+const LLAMA = readSrc("components/llama-update-banner.tsx");+const LLAMA_CHANGELOG = readSrc("components/update/llama-update-changelog-panel.tsx",);-const NOTES_LAYOUT = read("components/update/update-notes-layout.ts");-const NOTES = read("components/update/release-notes-panel.tsx");-const PROVIDER = read("app/provider.tsx");-const STORE = read("features/settings/stores/monitor-frame-store.ts");+const NOTES_LAYOUT = readSrc("components/update/update-notes-layout.ts");+const NOTES = readSrc("components/update/release-notes-panel.tsx");+const PROVIDER = readSrc("app/provider.tsx");+const STORE = readSrc("features/settings/stores/monitor-frame-store.ts");/** The class string opened by `anchor`, up to its closing quote. */function classes(source: string, anchor: string): string {@@ -328,7 +325,7 @@ test("the rail's block gutter costs the cards no room", () => {// The gutter drops the rail's box to the floor and `-mx-3` put it 4px from the right// edge, so it spans the window's resize grips, which are under it on Tailwind's scale.// All eight: a narrow window spans the rail across the north and west targets too.- const TITLEBAR = read("components/tauri/window-titlebar.tsx");+ const TITLEBAR = readSrc("components/tauri/window-titlebar.tsx");// A z-index on the toolbar would read as protection and give none: it sits inside a// positioned, numbered header, which is a stacking context.const toolbar = TITLEBAR.slice(diff --git a/studio/frontend/tests/verdict-poll-stall-guard.test.ts b/studio/frontend/tests/verdict-poll-stall-guard.test.tsindex 162dd9202b7..f25f5f1fc5d 100644--- a/studio/frontend/tests/verdict-poll-stall-guard.test.ts+++ b/studio/frontend/tests/verdict-poll-stall-guard.test.ts@@ -13,13 +13,11 @@// is waiting for.import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";-const src = await readFile(- new URL("../src/components/app-sidebar.tsx", import.meta.url),- "utf8",-);+import { readSrcAsync } from "./helpers/kit.ts";++const src = await readSrcAsync("components/app-sidebar.tsx");// The interval, verbatim, from the marker it opens with to the cleanup it returns.const START = "let pollingSince = 0;";diff --git a/studio/frontend/tests/video-download-plan-payload.test.ts b/studio/frontend/tests/video-download-plan-payload.test.tsindex cc08b54989a..5d6b14a4d40 100644--- a/studio/frontend/tests/video-download-plan-payload.test.ts+++ b/studio/frontend/tests/video-download-plan-payload.test.ts@@ -10,14 +10,11 @@*/import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import test from "node:test";-const source = readFileSync(- fileURLToPath(new URL("../src/features/video/video-page.tsx", import.meta.url)),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/video/video-page.tsx");test("the video download plan is asked with the selected precision", () => {const call = source.slice(diff --git a/studio/frontend/tests/video-gallery-clear-confirmation.test.ts b/studio/frontend/tests/video-gallery-clear-confirmation.test.tsindex 17ad466fe1e..c9830346381 100644--- a/studio/frontend/tests/video-gallery-clear-confirmation.test.ts+++ b/studio/frontend/tests/video-gallery-clear-confirmation.test.ts@@ -2,18 +2,13 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";++import { readSrc } from "./helpers/kit.ts";// Normalized: the assertions below span lines, and while .gitattributes keeps this tree at// LF, a source archive or a stray core.autocrlf would make every multi-line marker miss.-const source = readFileSync(- fileURLToPath(- new URL("../src/features/video/video-page.tsx", import.meta.url),- ),- "utf8",-).replace(/\r\n/g, "\n");+const source = readSrc("features/video/video-page.tsx").replace(/\r\n/g, "\n");/** The source between two markers. Throws if either moved: a silent empty slice would let* the negative assertion below ("no longer calls handleClearAll") pass over nothing. */diff --git a/studio/frontend/tests/video-generate-refusal-resync.test.ts b/studio/frontend/tests/video-generate-refusal-resync.test.tsindex 6991f580236..191e66e0a55 100644--- a/studio/frontend/tests/video-generate-refusal-resync.test.ts+++ b/studio/frontend/tests/video-generate-refusal-resync.test.ts@@ -10,14 +10,11 @@// The refusal is the page's only news that the model is gone, so it has to act on it.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-const VIDEO = readFileSync(- fileURLToPath(new URL("../src/features/video/video-page.tsx", import.meta.url)),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const VIDEO = readSrc("features/video/video-page.tsx");const RESYNC = VIDEO.slice(VIDEO.indexOf("const resyncAfterGenerateRefusal = useCallback("),@@ -73,10 +70,7 @@ test("a load started while the re-read was in flight is left alone", () => {test("the images page already corrects itself on every generate exit", () => {// It has the same dead-button shape, but its finally re-reads status on success,// failure and cancel alike, so there is nothing to fix there.- const images = readFileSync(- fileURLToPath(new URL("../src/features/images/images-page.tsx", import.meta.url)),- "utf8",- );+ const images = readSrc("features/images/images-page.tsx");const finallyBlock = images.slice(images.indexOf(" cancelRequested.current = false;"));assert.match(finallyBlock.slice(0, 1200), /if \(isMounted\.current\) await refreshStatus\(\);/);});diff --git a/studio/frontend/tests/video-h3-task-dialog.test.ts b/studio/frontend/tests/video-h3-task-dialog.test.tsindex cdddab1def8..d50bc6d0393 100644--- a/studio/frontend/tests/video-h3-task-dialog.test.ts+++ b/studio/frontend/tests/video-h3-task-dialog.test.ts@@ -14,14 +14,11 @@*/import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import test from "node:test";-const source = readFileSync(- fileURLToPath(new URL("../src/features/video/video-page.tsx", import.meta.url)),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const source = readSrc("features/video/video-page.tsx");test("only a non-hub pick skips the plan, so a cached hub pick still gets one", () => {// The bypass is keyed on the pick's SOURCE. A curated artifact already on disk is stilldiff --git a/studio/frontend/tests/vision-toggle-gating.test.ts b/studio/frontend/tests/vision-toggle-gating.test.tsindex 7deb31a11d1..33c2e4719f9 100644--- a/studio/frontend/tests/vision-toggle-gating.test.ts+++ b/studio/frontend/tests/vision-toggle-gating.test.ts@@ -13,23 +13,16 @@// tests next door.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import path from "node:path";import test from "node:test";-import { fileURLToPath } from "node:url";import { getImageInputUnavailableReason } from "../src/features/chat/utils/image-input-support.ts";-const HERE = path.dirname(fileURLToPath(import.meta.url));-const read = (relative: string) =>- readFileSync(path.join(HERE, "..", relative), "utf8");+import { readSrc } from "./helpers/kit.ts";-const APPLIER = read(- "src/features/chat/lib/apply-inference-status-to-store.ts",-);-const API_TYPES = read("src/features/chat/types/api.ts");-const CONFIG_PAGE = read(- "src/features/model-picker/components/model-config-page.tsx",+const APPLIER = readSrc("features/chat/lib/apply-inference-status-to-store.ts");+const API_TYPES = readSrc("features/chat/types/api.ts");+const CONFIG_PAGE = readSrc(+ "features/model-picker/components/model-config-page.tsx",);test("both response types carry the raw disable_vision echo", () => {@@ -189,7 +182,7 @@ test("every other refusal is untouched by the new branch", () => {// which is false for a model that cannot do images. Source-level for the same reason// as the reseed above: the replay sits inside one large object literal.test("the rollback replays the loaded vision baseline, not the control or the gate", () => {- const runtime = read("src/features/chat/hooks/use-chat-model-runtime.ts");+ const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts");const replay = runtime.slice(runtime.indexOf("tensor_parallel: stateBeforeUnload.loadedTensorParallel"),);@@ -219,7 +212,7 @@ test("the rollback replays the loaded vision baseline, not the control or the ga// model whose projector is running, and arms the next Apply to switch it off for real.// Source-level for the same reason as the replay above.test("the rollback seeds the Vision control from the restored model, not the target", () => {- const runtime = read("src/features/chat/hooks/use-chat-model-runtime.ts");+ const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts");const assignment = runtime.slice(runtime.indexOf("loadedSpeculativeType: rollbackSpeculativeType"),);@@ -249,7 +242,7 @@ test("the rollback seeds the Vision control from the restored model, not the tar// where it parts company with tensorParallel, which is deliberately standing across// models. Source-level for the same reason as the tests above.test("an unconfigured target gets the default Vision value, not the outgoing model's", () => {- const runtime = read("src/features/chat/hooks/use-chat-model-runtime.ts");+ const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts");const decl = runtime.slice(runtime.indexOf("const loadDisableVision ="),runtime.indexOf("const loadActivePresetSource"),@@ -265,7 +258,7 @@ test("an unconfigured target gets the default Vision value, not the outgoing mod});test("a compare pane with no saved config does not inherit the live Vision value", () => {- const composer = read("src/features/chat/shared-composer.tsx");+ const composer = readSrc("features/chat/shared-composer.tsx");const decl = composer.slice(composer.indexOf("const effectiveDisableVision ="),composer.indexOf("if (ownConfig.selectedGpuIds != null)"),diff --git a/studio/frontend/tests/voice-download-model-switch.test.ts b/studio/frontend/tests/voice-download-model-switch.test.tsindex afc18f36d58..f29ee7eea94 100644--- a/studio/frontend/tests/voice-download-model-switch.test.ts+++ b/studio/frontend/tests/voice-download-model-switch.test.ts@@ -12,7 +12,6 @@// another model is another job. The second test pins what the reset is worth.import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -21,28 +20,21 @@ import {computeTransferStats,} from "../src/lib/transfer-stats.ts";+import { readSrc } from "./helpers/kit.ts";+const MB = 1e6;-const voiceTabSource = readFileSync(- new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url),- "utf8",-);+const voiceTabSource = readSrc("features/settings/tabs/voice-tab.tsx");test("each download's samples belong to its own job, not to the tab", () => {- const pollLoopSource = readFileSync(- new URL("../src/features/hub/download-manager/poll-loop.ts", import.meta.url),- "utf8",- );+ const pollLoopSource = readSrc("features/hub/download-manager/poll-loop.ts");// Empty per job, so a second model cannot inherit the first one's samples.assert.ok(/speedSamples:\s*\[\]/.test(pollLoopSource),"each job runtime should start with its own empty sample buffer",);// And voice settings must not grow a second estimator back.- const voiceTabSource = readFileSync(- new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url),- "utf8",- );+ const voiceTabSource = readSrc("features/settings/tabs/voice-tab.tsx");for (const gone of ["computeTransferStats", "appendSample", "downloadSamplesRef"]) {assert.ok(!voiceTabSource.includes(gone),diff --git a/studio/frontend/tests/voice-settings-stt-migration.test.ts b/studio/frontend/tests/voice-settings-stt-migration.test.tsindex 5577914457a..8c53db07e17 100644--- a/studio/frontend/tests/voice-settings-stt-migration.test.ts+++ b/studio/frontend/tests/voice-settings-stt-migration.test.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";import {@@ -12,6 +11,8 @@ import {migrateVoiceSettings,} from "../src/features/settings/stores/stt-model-catalog.ts";+import { readSrc } from "./helpers/kit.ts";+const CUSTOM_ENGINE_BEFORE_TAURI =/savedEngine === "custom"\s*\? "custom"\s*:\s*isTauri/;const EXTERNAL_PROVIDER_FORM_FIELD = /form\.set\("provider_id", providerId\)/;@@ -61,20 +62,8 @@ test("migration keeps the rest of the save intact", () => {});test("custom transcription uses a saved connection without loading local STT", () => {- const storeSource = readFileSync(- new URL(- "../src/features/settings/stores/voice-settings-store.ts",- import.meta.url,- ),- "utf8",- );- const adapterSource = readFileSync(- new URL(- "../src/features/chat/adapters/studio-model-dictation-adapter.ts",- import.meta.url,- ),- "utf8",- );+ const storeSource = readSrc("features/settings/stores/voice-settings-store.ts");+ const adapterSource = readSrc("features/chat/adapters/studio-model-dictation-adapter.ts");assert.match(storeSource, CUSTOM_ENGINE_BEFORE_TAURI);assert.match(adapterSource, EXTERNAL_PROVIDER_FORM_FIELD);@@ -84,13 +73,7 @@ test("custom transcription uses a saved connection without loading local STT", (});test("the custom dictation connection picker handles deleted and empty connections", () => {- const voiceTabSource = readFileSync(- new URL(- "../src/features/settings/tabs/voice-tab.tsx",- import.meta.url,- ),- "utf8",- );+ const voiceTabSource = readSrc("features/settings/tabs/voice-tab.tsx");assert.match(voiceTabSource,diff --git a/studio/frontend/tests/voice-stt-device-control.test.ts b/studio/frontend/tests/voice-stt-device-control.test.tsindex 9903ed14baf..7d89f969dc3 100644--- a/studio/frontend/tests/voice-stt-device-control.test.ts+++ b/studio/frontend/tests/voice-stt-device-control.test.ts@@ -2,20 +2,12 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-const voiceTab = readFileSync(- new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url),- "utf8",-);-const adapter = readFileSync(- new URL(- "../src/features/chat/adapters/studio-model-dictation-adapter.ts",- import.meta.url,- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const voiceTab = readSrc("features/settings/tabs/voice-tab.tsx");+const adapter = readSrc("features/chat/adapters/studio-model-dictation-adapter.ts");test("changing the dictation device releases only this tab's model", () => {// Unscoped, the unload can tear down a model this tab never owned.diff --git a/studio/frontend/tests/vram-budget.test.ts b/studio/frontend/tests/vram-budget.test.tsindex cb1c425de98..8cdc9c05baa 100644--- a/studio/frontend/tests/vram-budget.test.ts+++ b/studio/frontend/tests/vram-budget.test.ts@@ -2,12 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";import {installLocalStorageFake,+ readSrc,registerBundlerResolver,} from "./helpers/kit.ts";@@ -25,6 +24,8 @@ const {"../src/features/model-picker/model-config/per-model-config.ts");+const VRAM_BUDGET = readSrc("features/settings/api/vram-budget.ts");+test("percent and fraction round-trip exactly across the whole range", () => {// Every stop the slider can land on: a value that does not survive the trip// reads as "changed" and re-saves itself on every remount.@@ -80,14 +81,8 @@ test("percentToFraction tolerates an off-grid slider value", () => {// chat-adapter tests do. The bug it guards: clearing the timer without sending the// pending fraction discarded a drag followed within 400ms by Run, the Advanced// toggle or closing the panel, and the server-wide budget lives nowhere else.-const pageSource = readFileSync(- fileURLToPath(- new URL(- "../src/features/model-picker/components/model-config-page.tsx",- import.meta.url,- ),- ),- "utf8",+const pageSource = readSrc(+ "features/model-picker/components/model-config-page.tsx",);function vramBudgetRowSource(): string {@@ -134,17 +129,11 @@ test("commit stages the fraction before arming the debounce", () => {test("the staged fraction is held outside the component that unmounts", () => {// The row unmounts on Run, so a ref inside it cannot be read by the load.- const client = readFileSync(- fileURLToPath(- new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),- ),- "utf8",- );- assert.match(client, /export function stageVramBudgetSave/);- assert.match(client, /export function flushVramBudgetSave/);+ assert.match(VRAM_BUDGET, /export function stageVramBudgetSave/);+ assert.match(VRAM_BUDGET, /export function flushVramBudgetSave/);// Cleared as it sends, so two flushes cannot write the same edit twice.- const flush = client.slice(- client.indexOf("export function flushVramBudgetSave"),+ const flush = VRAM_BUDGET.slice(+ VRAM_BUDGET.indexOf("export function flushVramBudgetSave"),);assert.ok(flush.indexOf("stagedVramBudgetFraction = null") <@@ -200,18 +189,12 @@ test("Run reports a rejected budget flush instead of voiding it", () => {});test("budget writes are serialised and only the newest publishes", () => {- const client = readFileSync(- fileURLToPath(- new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),- ),- "utf8",- );// Two debounced saves can overlap on a slow link; out-of-order responses would// let the older edit win both the row and the stored value.- assert.match(client, /vramBudgetWriteChain/);- assert.match(client, /vramBudgetWriteGeneration/);- const update = client.slice(- client.indexOf("export function updateVramBudgetSettings"),+ assert.match(VRAM_BUDGET, /vramBudgetWriteChain/);+ assert.match(VRAM_BUDGET, /vramBudgetWriteGeneration/);+ const update = VRAM_BUDGET.slice(+ VRAM_BUDGET.indexOf("export function updateVramBudgetSettings"),);assert.match(update,@@ -222,16 +205,10 @@ test("budget writes are serialised and only the newest publishes", () => {});test("Run also waits for a save the debounce already sent", () => {- const client = readFileSync(- fileURLToPath(- new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),- ),- "utf8",- );// Pause past the 400 ms debounce, then click Load: nothing is staged any more,// but the PUT is still open and the load would use the fraction it replaces.- const settle = client.slice(- client.indexOf("export function settleVramBudgetSave"),+ const settle = VRAM_BUDGET.slice(+ VRAM_BUDGET.indexOf("export function settleVramBudgetSave"),);assert.match(settle, /flushVramBudgetSave\(\) \?\?/);assert.match(@@ -239,20 +216,17 @@ test("Run also waits for a save the debounce already sent", () => {/vramBudgetWritesOpen > 0 \? vramBudgetNewestWrite : null/,);// The counter has to come back down however the write ends.- assert.match(client, /\.finally\(\(\) => \{\s*vramBudgetWritesOpen -= 1;/);+ assert.match(+ VRAM_BUDGET,+ /\.finally\(\(\) => \{\s*vramBudgetWritesOpen -= 1;/,+ );});test("a read waits behind an open write", () => {- const client = readFileSync(- fileURLToPath(- new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),- ),- "utf8",- );// A remount right after a flushed drag can read before the PUT commits and// answer after it, repainting the row with the value the server just replaced.- const read = client.slice(- client.indexOf("export async function loadVramBudgetSettings"),+ const read = VRAM_BUDGET.slice(+ VRAM_BUDGET.indexOf("export async function loadVramBudgetSettings"),);assert.match(read, /vramBudgetWritesOpen > 0 \? vramBudgetWriteChain/);assert.ok(@@ -276,17 +250,11 @@ test("the budget reads as a percentage and steps in tenths", () => {});test("a failed save is re-staged, but never over a newer edit", () => {- const client = readFileSync(- fileURLToPath(- new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),- ),- "utf8",- );// The flush clears the staged value as it sends, so without putting it back the// control shows a fraction the server never took. It goes back only while it is// still the newest intent.- const update = client.slice(- client.indexOf("export function updateVramBudgetSettings"),+ const update = VRAM_BUDGET.slice(+ VRAM_BUDGET.indexOf("export function updateVramBudgetSettings"),);// Whitespace-collapsed: the formatter wraps this condition across lines.const rejection = update@@ -345,13 +313,7 @@ test("a save that fails during Run is dropped, not left to race the load", () =>});test("only the retry is dropped, never a newer edit staged over it", () => {- const client = readFileSync(- fileURLToPath(- new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),- ),- "utf8",- );- const flat = client.replace(/\s+/g, " ");+ const flat = VRAM_BUDGET.replace(/\s+/g, " ");// Run drops the failed fraction so it cannot race the load, but a drag landing// during that PUT stages a newer one, and dropping that would discard the edit// the user is looking at.@@ -367,13 +329,7 @@ test("only the retry is dropped, never a newer edit staged over it", () => {});test("a post-load read is not answered by one taken before the load finished", () => {- const client = readFileSync(- fileURLToPath(- new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),- ),- "utf8",- );- const flat = client.replace(/\s+/g, " ");+ const flat = VRAM_BUDGET.replace(/\s+/g, " ");// reloadRequired describes the running child, so an in-flight GET answers about// the child being replaced; sharing it republishes the stale notice.assert.match(flat, /if \(options\.force\) \{[^}]*inFlightVramBudget = null;/);@@ -382,15 +338,7 @@ test("a post-load read is not answered by one taken before the load finished", (flat,/if \(inFlightVramBudget === read\) \{ inFlightVramBudget = null;/,);- const row = readFileSync(- fileURLToPath(- new URL(- "../src/features/model-picker/components/model-config-page.tsx",- import.meta.url,- ),- ),- "utf8",- );+ const row = readSrc("features/model-picker/components/model-config-page.tsx");assert.match(row, /loadVramBudgetSettings\(\{ force: true \}\)/);});@@ -445,29 +393,17 @@ test("Reload is reachable when only the server-wide budget changed", () => {});test("a read displaced by a forced one does not publish", () => {- const client = readFileSync(- fileURLToPath(- new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),- ),- "utf8",- );// Clearing the handle is not enough: the displaced GET still resolves, and it// describes the child being replaced, so publishing would restore the notice and// the Reload button that the forced read had just cleared.assert.match(- client.replace(/\s+/g, " "),+ VRAM_BUDGET.replace(/\s+/g, " "),/if \( inFlightVramBudget !== read \|\|/,);});test("settling before a load hears about the write that failed", () => {- const client = readFileSync(- fileURLToPath(- new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),- ),- "utf8",- );- const flat = client.replace(/\s+/g, " ");+ const flat = VRAM_BUDGET.replace(/\s+/g, " ");// The chain swallows rejections so one failed save cannot strand the ones behind// it, so a Run waiting on the chain was told the save succeeded and never// dropped the retry, which the teardown then flushed against the load.@@ -482,13 +418,7 @@ test("settling before a load hears about the write that failed", () => {});test("a read does not repaint over a write issued while it was in the air", () => {- const client = readFileSync(- fileURLToPath(- new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),- ),- "utf8",- );- const flat = client.replace(/\s+/g, " ");+ const flat = VRAM_BUDGET.replace(/\s+/g, " ");// Waiting behind the writes open at read time says nothing about a save made// while the GET is in the air; that PUT can publish first and the late GET would// then restore the fraction the server no longer holds.@@ -510,17 +440,11 @@ test("Manual with automatic layers still shows the budget", () => {});test("a superseded read is refused, not handed back to the caller", () => {- const client = readFileSync(- fileURLToPath(- new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),- ),- "utf8",- );// Holding back the publish is not enough: the row applies the return value with// setSettings, so a read overtaken by a save would put back the isStored and// reloadRequired that save had just changed. Null is already this function's// "no usable answer", which every caller treats as keep what you have.- const flat = client.replace(/\s+/g, " ");+ const flat = VRAM_BUDGET.replace(/\s+/g, " ");assert.match(flat, /throw new Error\("superseded"\); \}/);// The binding is optional: one caller inspects the error to tell an absent route from// a failed read, and the contract for everyone else is still null.diff --git a/studio/frontend/tests/web-search-action-variants.test.ts b/studio/frontend/tests/web-search-action-variants.test.tsindex bc505bca609..fef128a0672 100644--- a/studio/frontend/tests/web-search-action-variants.test.ts+++ b/studio/frontend/tests/web-search-action-variants.test.ts@@ -2,19 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-const CARD = readFileSync(- fileURLToPath(- new URL(- "../src/components/assistant-ui/tool-ui-web-search.tsx",- import.meta.url,- ),- ),- "utf8",-);+import { readSrc } from "./helpers/kit.ts";++const CARD = readSrc("components/assistant-ui/tool-ui-web-search.tsx");test("the card tells the three action types apart", () => {// Reading only `action.query` rendered open_page and find_in_page as an emptydiff --git a/tests/sh/_harness.sh b/tests/sh/_harness.shnew file mode 100644index 00000000000..b79a2488c94--- /dev/null+++ b/tests/sh/_harness.sh@@ -0,0 +1,55 @@+#!/bin/bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+#+# Counters and assertions shared by the tests/sh suites. Sourced, never executed:+# both runners glob test_*.sh, so this name deliberately sits outside the glob.+# A suite wanting a different message or comparison shadows one of these after the+# source -- the wording of a failure is part of what the suite tells its reader.++PASS=0+FAIL=0++ok() { echo " PASS: $1"; PASS=$((PASS + 1)); }+bad() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }++assert_eq() {+ _label="$1"; _expected="$2"; _actual="$3"+ if [ "$_actual" = "$_expected" ]; then+ echo " PASS: $_label"+ PASS=$((PASS + 1))+ else+ echo " FAIL: $_label (expected '$_expected', got '$_actual')"+ FAIL=$((FAIL + 1))+ fi+}++assert_contains() {+ _label="$1"; _haystack="$2"; _needle="$3"+ # `--` so a needle that starts with a dash is a pattern, not a grep option.+ if echo "$_haystack" | grep -qF -- "$_needle"; then+ echo " PASS: $_label"+ PASS=$((PASS + 1))+ else+ echo " FAIL: $_label (expected to find '$_needle')"+ FAIL=$((FAIL + 1))+ fi+}++assert_not_contains() {+ _label="$1"; _haystack="$2"; _needle="$3"+ if echo "$_haystack" | grep -qF -- "$_needle"; then+ echo " FAIL: $_label (found '$_needle' but should not)"+ FAIL=$((FAIL + 1))+ else+ echo " PASS: $_label"+ PASS=$((PASS + 1))+ fi+}++# The tally every suite ends on. Non-zero exit is what the CI loop reads.+summary() {+ echo ""+ echo "Results: $PASS passed, $FAIL failed"+ [ "$FAIL" -eq 0 ] || exit 1+}diff --git a/tests/sh/test_get_torch_index_url.sh b/tests/sh/test_get_torch_index_url.shindex af3fb91b68c..151ef0b1220 100755--- a/tests/sh/test_get_torch_index_url.sh+++ b/tests/sh/test_get_torch_index_url.sh@@ -5,10 +5,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0-# Extract get_torch_index_url and its helper functions from install.sh.# Also replace the hardcoded /usr/bin/nvidia-smi fallback with a# controllable path so we can test the "no GPU" scenario on GPU machines.@@ -92,17 +90,6 @@ done# Save system PATH so we always have basic tools (uname, grep, head, etc.)_SYS_PATH="/usr/local/bin:/usr/bin:/bin"-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-# Helper: create a mock nvidia-smi answering the version header, -L (so# _has_usable_nvidia_gpu sees a GPU) and --query-gpu=compute_cap. $1 is the CUDA version,# $2 a space-separated capability list (default one Ampere card), $3 the compute_cap@@ -593,6 +580,4 @@ rm -rf "$_FAKE_SMI_DIR"rm -rf "$_FAKE_ROCM_DIR"rm -rf "$_TOOLS_DIR"-echo ""-echo "Results: $PASS passed, $FAIL failed"-[ "$FAIL" -eq 0 ] || exit 1+summarydiff --git a/tests/sh/test_install_gpu_summary_probe_sources.sh b/tests/sh/test_install_gpu_summary_probe_sources.shindex 0ff57aeecb6..f18b693bdc5 100755--- a/tests/sh/test_install_gpu_summary_probe_sources.sh+++ b/tests/sh/test_install_gpu_summary_probe_sources.sh@@ -5,12 +5,10 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"WORK=$(mktemp -d)trap 'rm -rf "$WORK"' EXIT-PASS=0-FAIL=0-{sed -n '/^_rocminfo_gpu_records()/,/^}/p' "$INSTALL_SH"sed -n '/^_amd_smi_gpu_records()/,/^}/p' "$INSTALL_SH"@@ -54,15 +52,6 @@ esacSTUBchmod +x "$WORK/roc/rocminfo" "$WORK/smi/amd-smi"-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"; PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"; FAIL=$((FAIL + 1))- fi-}-# $1 rocminfo fixture ("-" = the tool is not installed, empty file = installed but silent)# $2 amd-smi fixture, same convention. $3 visible-device mask. Prints "gfx|name".summary() {diff --git a/tests/sh/test_install_host_defaults.sh b/tests/sh/test_install_host_defaults.shindex 7b59b7b13ff..165be50d7bb 100755--- a/tests/sh/test_install_host_defaults.sh+++ b/tests/sh/test_install_host_defaults.sh@@ -54,37 +54,13 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"INSTALL_SH="$REPO_ROOT/install.sh"INSTALL_PS1="$REPO_ROOT/install.ps1"SETUP_SH="$REPO_ROOT/studio/setup.sh"README="$REPO_ROOT/README.md"STUDIO_CLI="$REPO_ROOT/unsloth_cli/commands/studio.py"-PASS=0-FAIL=0--assert_contains() {- _label="$1"; _haystack="$2"; _needle="$3"- if echo "$_haystack" | grep -qF -- "$_needle"; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected to find '$_needle')"- FAIL=$((FAIL + 1))- fi-}--assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-assert_ge() {_label="$1"; _actual="$2"; _min="$3"if [ "$_actual" -ge "$_min" ] 2> /dev/null; then@@ -130,7 +106,6 @@ WILDCARDS = ("0.0.0.0", "[::]", "::")_BEFORE = " \t\"'/"_WORD = "studio"-def host_flags(source):"""Every CLI spelling of the host option, read off the typer.Option that declares it.@@ -161,7 +136,6 @@ def host_flags(source):found.add(a.value)return sorted(found)-def wildcard_pattern(flags):"""A host flag bound to a wildcard address, in any of the flag's spellings.@@ -178,7 +152,6 @@ def wildcard_pattern(flags):r"(?:^|\s)(?:%s)(?:\s+|=)(?:%s)(?=$|[^0-9A-Za-z._-])" % (alternation, values))-def code_blocks(text):"""Fenced code blocks, CommonMark-style. Returns (blocks, unterminated).@@ -210,10 +183,8 @@ def code_blocks(text):return blocks, Truereturn blocks, False-_COMMENT = re.compile(r"(?:^|\s)#.*$")-def studio_commands(text):"""Every `... studio <args>` command in *text*, as the tail from `studio` onwards.@@ -237,7 +208,6 @@ def studio_commands(text):out.append(line[at:].strip())return out-def main():mode = sys.argv[1]if mode == "flags":@@ -274,7 +244,6 @@ def main():return 0raise SystemExit("unknown mode: %s" % mode)-if __name__ == "__main__":raise SystemExit(main())PROBE_PYdiff --git a/tests/sh/test_install_pipe_safety.sh b/tests/sh/test_install_pipe_safety.shindex be479dd5a52..8f3d05bc092 100755--- a/tests/sh/test_install_pipe_safety.sh+++ b/tests/sh/test_install_pipe_safety.sh@@ -15,21 +15,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-echo "=== structure ==="# The wrapper must be invoked on the LAST executable line, or sh starts executingdiff --git a/tests/sh/test_install_python_guard.sh b/tests/sh/test_install_python_guard.shindex 35eb7a0ea72..394876606b3 100755--- a/tests/sh/test_install_python_guard.sh+++ b/tests/sh/test_install_python_guard.sh@@ -9,22 +9,9 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-_HELPERS=$(mktemp){# Quiet stand-ins for the reporting helpers the extracted functions call.diff --git a/tests/sh/test_install_rollback_lifecycle.sh b/tests/sh/test_install_rollback_lifecycle.shindex 77a0264021f..ff3312855cd 100644--- a/tests/sh/test_install_rollback_lifecycle.sh+++ b/tests/sh/test_install_rollback_lifecycle.sh@@ -5,14 +5,9 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"INSTALL_PS1="$SCRIPT_DIR/../../install.ps1"-PASS=0-FAIL=0--ok() { echo " PASS: $1"; PASS=$((PASS + 1)); }-bad() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }-ROLLBACK_BLOCK=$(sed -n '/^_VENV_ROLLBACK_DIR=""/,/^trap '\''_on_install_signal 143'\'' TERM$/p' "$INSTALL_SH")# Both are defined above the block, with the rest of the cache selector, and both are# called from it. Splicing without them makes the cases exit 127 on a command the realdiff --git a/tests/sh/test_install_uv_cache_root.sh b/tests/sh/test_install_uv_cache_root.shindex 874dfa7a346..b07a748924b 100644--- a/tests/sh/test_install_uv_cache_root.sh+++ b/tests/sh/test_install_uv_cache_root.sh@@ -6,13 +6,8 @@set -eSCRIPT_DIR=$(CDPATH= cd -- "$(dirname "$0")" && pwd)+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--ok() { echo " PASS: $1"; PASS=$((PASS + 1)); }-bad() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }-HELPERS=$(awk '/^_configure_uv_cache\(\) \{/ { grab = 1 }/^_prepare_studio_uv_cache_for_launch\(\) \{/ { grab = 1 }@@ -367,7 +362,6 @@ RELWDbad "$shell: recorded [$_rw], wanted [$CASE/uvdir/relcache]"fi-# The marker describes the environment, so a rolled-back install puts it back.ROLLBACK_PROBE="$WORK/$shell rollback.sh"{diff --git a/tests/sh/test_install_uv_override_space.sh b/tests/sh/test_install_uv_override_space.shindex df1a6d807d8..4e76c78312e 100755--- a/tests/sh/test_install_uv_override_space.sh+++ b/tests/sh/test_install_uv_override_space.sh@@ -7,13 +7,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--ok() { echo " PASS: $1"; PASS=$((PASS + 1)); }-bad() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }-# Extract the UV_OVERRIDE hardening block (outer case ... esac plus the export)# and run it directly, so the test tracks install.sh rather than a copy of it.BLOCK=$(awk 'diff --git a/tests/sh/test_linux_uv_python_downloads_manual.sh b/tests/sh/test_linux_uv_python_downloads_manual.shindex a31dff0223e..c425a8ecea8 100755--- a/tests/sh/test_linux_uv_python_downloads_manual.sh+++ b/tests/sh/test_linux_uv_python_downloads_manual.sh@@ -5,43 +5,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}--assert_contains() {- _label="$1"; _haystack="$2"; _needle="$3"- if echo "$_haystack" | grep -qF "$_needle"; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected to find '$_needle')"- FAIL=$((FAIL + 1))- fi-}--assert_not_contains() {- _label="$1"; _haystack="$2"; _needle="$3"- if echo "$_haystack" | grep -qF "$_needle"; then- echo " FAIL: $_label (found '$_needle' but should not)"- FAIL=$((FAIL + 1))- else- echo " PASS: $_label"- PASS=$((PASS + 1))- fi-}-_FN=$(mktemp){sed -n '/^PYTHON_SKIP=/p' "$INSTALL_SH"diff --git a/tests/sh/test_llama_build_jobs.sh b/tests/sh/test_llama_build_jobs.shindex b38528af857..51ee212c5db 100755--- a/tests/sh/test_llama_build_jobs.sh+++ b/tests/sh/test_llama_build_jobs.sh@@ -13,11 +13,9 @@ set -eunset UNSLOTH_LLAMA_BUILD_JOBSSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"SETUP_PS1="$SCRIPT_DIR/../../studio/setup.ps1"-PASS=0-FAIL=0-# Extract the constants and the helper (same sed range as the other function tests)._FUNC_FILE=$(mktemp)sed -n '/^_LLAMA_BUILD_RESERVE_MB=/,/^_LLAMA_BUILD_MB_PER_JOB=/p' "$SETUP_SH" > "$_FUNC_FILE"@@ -27,17 +25,6 @@ if [ ! -s "$_FUNC_FILE" ]; thenexit 1fi-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-# $1 = cores, $2 = total RAM MiB, $3 = UNSLOTH_LLAMA_BUILD_JOBSrun_jobs() {UNSLOTH_LLAMA_BUILD_JOBS="${3:-}" \diff --git a/tests/sh/test_mac_intel_compat.sh b/tests/sh/test_mac_intel_compat.shindex cfc62793af8..bacdd3f138f 100644--- a/tests/sh/test_mac_intel_compat.sh+++ b/tests/sh/test_mac_intel_compat.sh@@ -7,43 +7,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}--assert_contains() {- _label="$1"; _haystack="$2"; _needle="$3"- if echo "$_haystack" | grep -qF "$_needle"; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected to find '$_needle')"- FAIL=$((FAIL + 1))- fi-}--assert_not_contains() {- _label="$1"; _haystack="$2"; _needle="$3"- if echo "$_haystack" | grep -qF "$_needle"; then- echo " FAIL: $_label (found '$_needle' but should not)"- FAIL=$((FAIL + 1))- else- echo " PASS: $_label"- PASS=$((PASS + 1))- fi-}-# ── Extract version_ge function from install.sh ──_VGE_FILE=$(mktemp)sed -n '/^version_ge()/,/^}/p' "$INSTALL_SH" > "$_VGE_FILE"@@ -661,6 +626,4 @@ RUNNER_EOFfirm -f "$_GUARD_FILE"-echo ""-echo "Results: $PASS passed, $FAIL failed"-[ "$FAIL" -eq 0 ] || exit 1+summarydiff --git a/tests/sh/test_macos_clt_gate.sh b/tests/sh/test_macos_clt_gate.shindex 5cbf17f8e43..ec87fed08b2 100755--- a/tests/sh/test_macos_clt_gate.sh+++ b/tests/sh/test_macos_clt_gate.sh@@ -17,43 +17,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}--assert_contains() {- _label="$1"; _haystack="$2"; _needle="$3"- if echo "$_haystack" | grep -qF "$_needle"; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected to find '$_needle')"- FAIL=$((FAIL + 1))- fi-}--assert_not_contains() {- _label="$1"; _haystack="$2"; _needle="$3"- if echo "$_haystack" | grep -qF "$_needle"; then- echo " FAIL: $_label (found '$_needle' but should not)"- FAIL=$((FAIL + 1))- else- echo " PASS: $_label"- PASS=$((PASS + 1))- fi-}-# ── Extract the functions under test ──_FN_FILE=$(mktemp)sed -n '/^_has_working_git()/,/^}/p' "$INSTALL_SH" > "$_FN_FILE"diff --git a/tests/sh/test_macos_uv_install_name_tool_guard.sh b/tests/sh/test_macos_uv_install_name_tool_guard.shindex 357c6ac15fc..03cd035efd0 100755--- a/tests/sh/test_macos_uv_install_name_tool_guard.sh+++ b/tests/sh/test_macos_uv_install_name_tool_guard.sh@@ -7,21 +7,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-assert_empty() {_label="$1"; _path="$2"if [ ! -s "$_path" ]; then@@ -180,7 +167,6 @@ for _sh in sh bash; dorun_case "$_sh" xcodedone-echo "=== exact generic/user and non-macOS forwarding ==="for _sh in sh bash; do_case="$_ROOT/${_sh}-forwarding"@@ -281,7 +267,6 @@ for _sh in sh bash; dofidone-echo ""echo "Passed: $PASS, Failed: $FAIL"[ "$FAIL" -eq 0 ]diff --git a/tests/sh/test_macos_venv_python_preference.sh b/tests/sh/test_macos_venv_python_preference.shindex 83f72264841..27445601037 100755--- a/tests/sh/test_macos_venv_python_preference.sh+++ b/tests/sh/test_macos_venv_python_preference.sh@@ -7,32 +7,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}--assert_contains() {- _label="$1"; _haystack="$2"; _needle="$3"- if echo "$_haystack" | grep -qF "$_needle"; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected to find '$_needle')"- FAIL=$((FAIL + 1))- fi-}-_FN=$(mktemp)sed -n '/^_uv_venv_arm64()/,/^}/p' "$INSTALL_SH" > "$_FN"[ -s "$_FN" ] || { echo " FAIL: _uv_venv_arm64 not found in install.sh"; exit 1; }diff --git a/tests/sh/test_nvcc_meets_llama_minimum.sh b/tests/sh/test_nvcc_meets_llama_minimum.shindex 2a2ac996646..f952ba1f05f 100755--- a/tests/sh/test_nvcc_meets_llama_minimum.sh+++ b/tests/sh/test_nvcc_meets_llama_minimum.sh@@ -7,26 +7,13 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"-PASS=0-FAIL=0-# Extract just the helper function. The sed range is the same pattern the# install.sh tests use._FUNC_FILE=$(mktemp)sed -n '/^_nvcc_meets_llama_minimum()/,/^}/p' "$SETUP_SH" > "$_FUNC_FILE"-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-# Fake nvcc printing "release X.Y" in the canonical nvcc -V layout (the helper# greps for "release X.Y", stable across CUDA 9.x-13.x).make_mock_nvcc() {@@ -118,6 +105,4 @@ rm -rf "$_dir"rm -f "$_FUNC_FILE"-echo ""-echo "Results: $PASS passed, $FAIL failed"-[ "$FAIL" -eq 0 ] || exit 1+summarydiff --git a/tests/sh/test_previous_torch_pin.sh b/tests/sh/test_previous_torch_pin.shindex 98cbccf687c..a71f13536c5 100644--- a/tests/sh/test_previous_torch_pin.sh+++ b/tests/sh/test_previous_torch_pin.sh@@ -11,10 +11,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="${1:-$SCRIPT_DIR/../../install.sh}"-PASS=0-FAIL=0-# Extract _previous_torch_pin and its dependency _torch_release_in_window._FUNC_FILE=$(mktemp){@@ -26,15 +24,6 @@ _FUNC_FILE=$(mktemp). "$_FUNC_FILE"rm -f "$_FUNC_FILE"-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"; PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"; FAIL=$((FAIL + 1))- fi-}-unset UNSLOTH_TORCH_UPGRADEecho "=== _previous_torch_pin: in-window releases are kept, any flavor ==="diff --git a/tests/sh/test_redact_install_output.sh b/tests/sh/test_redact_install_output.shindex 0f10122aea1..6a08613daa0 100755--- a/tests/sh/test_redact_install_output.sh+++ b/tests/sh/test_redact_install_output.sh@@ -9,25 +9,14 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0-_FUNC_FILE=$(mktemp)sed -n '/^_redact_install_output()/,/^}/p' "$INSTALL_SH" > "$_FUNC_FILE"# shellcheck disable=SC1090. "$_FUNC_FILE"rm -f "$_FUNC_FILE"-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"; PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"; FAIL=$((FAIL + 1))- fi-}-# Redact from a file (the actual call site passes a captured-log tempfile).redact_str() {_rs_tmp=$(mktemp)diff --git a/tests/sh/test_resolve_cuda_archs.sh b/tests/sh/test_resolve_cuda_archs.shindex be32bee6add..19543058cf2 100755--- a/tests/sh/test_resolve_cuda_archs.sh+++ b/tests/sh/test_resolve_cuda_archs.sh@@ -5,25 +5,12 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"-PASS=0-FAIL=0-# Extract just the helper function (same sed range as the other function tests)._FUNC_FILE=$(mktemp)sed -n '/^_resolve_cuda_archs()/,/^}/p' "$SETUP_SH" > "$_FUNC_FILE"-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-# $1 = raw compute_cap text, $2 = overriderun_resolve() {bash -c ". '$_FUNC_FILE'; _resolve_cuda_archs \"\$1\" \"\$2\"" _ "$1" "$2"@@ -63,6 +50,4 @@ assert_eq "future 10.0" "100" "$(run_resolve "10.0" "")"rm -f "$_FUNC_FILE"-echo ""-echo "Results: $PASS passed, $FAIL failed"-[ "$FAIL" -eq 0 ] || exit 1+summarydiff --git a/tests/sh/test_rocm_bad_arch_gate.sh b/tests/sh/test_rocm_bad_arch_gate.shindex 54cb1af6674..3500a3c0bd4 100755--- a/tests/sh/test_rocm_bad_arch_gate.sh+++ b/tests/sh/test_rocm_bad_arch_gate.sh@@ -10,21 +10,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-# The gate is inline in get_torch_index_url on purpose: harnesses that extract the function# alone would turn a missed helper into an undefined command sending every ROCm case to cpu.# So exercise the real case block, lifted from the function.diff --git a/tests/sh/test_rocm_no_version_arch_route_e2e.sh b/tests/sh/test_rocm_no_version_arch_route_e2e.shindex edb8d51212f..7bf73c99b9b 100755--- a/tests/sh/test_rocm_no_version_arch_route_e2e.sh+++ b/tests/sh/test_rocm_no_version_arch_route_e2e.sh@@ -8,10 +8,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0-[ -r "$INSTALL_SH" ] || { echo " FAIL: no install.sh at $INSTALL_SH"; exit 1; }_ROOT=$(mktemp -d)@@ -102,17 +100,6 @@ bash -n "$_BLOCK" || _fatal "spliced block does not parse"sh -n "$_FUNCS" || _fatal "spliced functions are not POSIX-parseable"sh -n "$_BLOCK" || _fatal "spliced block is not POSIX-parseable"-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-reset_host() {rm -rf "$_FAKE" "$_MOCK"mkdir -p "$_FAKE" "$_MOCK" "$_F_PROCNV" "$_F_PCI" "$_F_ROCM"@@ -473,7 +460,6 @@ mock_strix_cpuinfo; mock_kfd_gfx 110000assert_eq "a real gfx1100 corroborated by the kernel keeps its own family" \"$_AMD/gfx110X-all/" "$(HSA_OVERRIDE_GFX_VERSION=11.0.0 run_index)"-# gfx1033 (Van Gogh) shares gfx103X-all with gfx1030-gfx1036, so a mixed 103X host is the one# shape where _amd_agreed_index_family AGREES while _amd_sole_index_arch declines, and the# shared-family arm then rewrote the cpu index the gate had just chosen back to ROCm wheels.diff --git a/tests/sh/test_rocminfo_gpu_name_7307.sh b/tests/sh/test_rocminfo_gpu_name_7307.shindex 47bb660380e..a04ed232e1d 100755--- a/tests/sh/test_rocminfo_gpu_name_7307.sh+++ b/tests/sh/test_rocminfo_gpu_name_7307.sh@@ -5,11 +5,9 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"-PASS=0-FAIL=0-_FUNC_FILE=$(mktemp){sed -n '/^_rocminfo_gpu_records()/,/^}/p' "$INSTALL_SH"@@ -33,15 +31,6 @@ _PICK_PROG_SETUP=$(_extract_pick "$SETUP_SH")[ -n "$_PICK_PROG" ] || { echo "FATAL: no record selector found in $INSTALL_SH" >&2; exit 1; }_pick() { awk -v idx="$1" "$_PICK_PROG"; }-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"; PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"; FAIL=$((FAIL + 1))- fi-}-# Installer and updater must use the same parser._body_install=$(sed -n '/^_rocminfo_gpu_records()/,/^}/p' "$INSTALL_SH" | tail -n +2)_body_setup=$(sed -n '/^_setup_rocminfo_gpu_records()/,/^}/p' "$SETUP_SH" | tail -n +2)diff --git a/tests/sh/test_select_cuda_jit_tools.sh b/tests/sh/test_select_cuda_jit_tools.shindex ebc7ea8af45..aa3fd31a25a 100755--- a/tests/sh/test_select_cuda_jit_tools.sh+++ b/tests/sh/test_select_cuda_jit_tools.sh@@ -8,10 +8,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"ENTRYPOINT_SH="$SCRIPT_DIR/../../docker/entrypoint.sh"-PASS=0-FAIL=0-# The fixtures assert through readlink, because retargeting that symlink is what the# function does -- and git-bash copies instead of symlinking unless# MSYS=winsymlinks:nativestrict and the user is elevated.@@ -29,17 +27,6 @@ rm -rf "$_probe"_FUNC_FILE=$(mktemp)sed -n '/^select_cuda_jit_tools()/,/^}/p' "$ENTRYPOINT_SH" > "$_FUNC_FILE"-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-# $1 = compute_cap(s) the mock nvidia-smi reports, ONE PER LINE ("none" = no# nvidia-smi, multi-line = a mixed-GPU host). $2 = the initial libnvrtc.so.12 target# (default cu12.8). Prints "<PTXAS_STATE> <NVRTC_TARGET>".@@ -99,6 +86,4 @@ assert_eq "B300 after B300 -> cu13 kept" "UNSET libnvrtc.so.12.cu13"rm -f "$_FUNC_FILE"-echo ""-echo "Results: $PASS passed, $FAIL failed"-[ "$FAIL" -eq 0 ] || exit 1+summarydiff --git a/tests/sh/test_setup_amd_fastpath_escape.sh b/tests/sh/test_setup_amd_fastpath_escape.shindex 01fb755e06f..1a0bf2b55c9 100755--- a/tests/sh/test_setup_amd_fastpath_escape.sh+++ b/tests/sh/test_setup_amd_fastpath_escape.sh@@ -5,12 +5,10 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"WORK=$(mktemp -d)trap 'rm -rf "$WORK"' EXIT-PASS=0-FAIL=0-# The escape block, from its guard to the first dedented `fi`.awk '/^if \[ "\$_SKIP_PYTHON_DEPS" = true \] && \[ -x "\$VENV_DIR\/bin\/python" \]; then/ {on=1}on {print}@@ -18,15 +16,6 @@ awk '/^if \[ "\$_SKIP_PYTHON_DEPS" = true \] && \[ -x "\$VENV_DIR\/bin\/python"grep -q -- "--amd-torch-needs-dependency-pass" "$WORK/escape.sh" || {echo "FATAL: AMD escape block not found in $SETUP_SH" >&2; exit 1; }-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"; PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"; FAIL=$((FAIL + 1))- fi-}-VENV_DIR="$WORK/venv"mkdir -p "$VENV_DIR/bin": > "$WORK/install_python_stack.py"diff --git a/tests/sh/test_setup_gpu_summary_probe_sources.sh b/tests/sh/test_setup_gpu_summary_probe_sources.shindex 904dfa708d3..ff7f43db12c 100755--- a/tests/sh/test_setup_gpu_summary_probe_sources.sh+++ b/tests/sh/test_setup_gpu_summary_probe_sources.sh@@ -9,11 +9,10 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"WORK=$(mktemp -d)trap 'rm -rf "$WORK"' EXIT-PASS=0-FAIL=0SKIP=0{@@ -83,15 +82,6 @@ esacSTUBchmod +x "$WORK/roc/rocminfo" "$WORK/smi/amd-smi"-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"; PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"; FAIL=$((FAIL + 1))- fi-}-# $1 rocminfo fixture ("-" = not installed), $2 amd-smi fixture, $3 visible-device mask.# Prints "gfx|name". The probe log is left in $WORK/probes for the call-count asserts.summary() {diff --git a/tests/sh/test_torch_constraint.sh b/tests/sh/test_torch_constraint.shindex c742c902e17..e3b27e8be89 100644--- a/tests/sh/test_torch_constraint.sh+++ b/tests/sh/test_torch_constraint.sh@@ -6,45 +6,10 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"INSTALL_PS1="$SCRIPT_DIR/../../install.ps1"NO_TORCH_RT="$SCRIPT_DIR/../../studio/backend/requirements/no-torch-runtime.txt"-PASS=0-FAIL=0--assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}--assert_contains() {- _label="$1"; _haystack="$2"; _needle="$3"- if echo "$_haystack" | grep -qF "$_needle"; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected to find '$_needle')"- FAIL=$((FAIL + 1))- fi-}--assert_not_contains() {- _label="$1"; _haystack="$2"; _needle="$3"- if echo "$_haystack" | grep -qF "$_needle"; then- echo " FAIL: $_label (found '$_needle' but should not)"- FAIL=$((FAIL + 1))- else- echo " PASS: $_label"- PASS=$((PASS + 1))- fi-}-# ── Helper: create a mock python that reports a given minor version ──make_mock_python() {_minor="$1"diff --git a/tests/sh/test_torch_flavor.sh b/tests/sh/test_torch_flavor.shindex 2737357b6ce..bb86f9bc6b1 100755--- a/tests/sh/test_torch_flavor.sh+++ b/tests/sh/test_torch_flavor.sh@@ -7,10 +7,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0-# Extract the helper functions from install.sh and source them# (_torch_index_url_leaf is the shared leaf extractor the classifiers call)._FUNC_FILE=$(mktemp)@@ -31,15 +29,6 @@ _FUNC_FILE=$(mktemp). "$_FUNC_FILE"rm -f "$_FUNC_FILE"-assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"; PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"; FAIL=$((FAIL + 1))- fi-}-echo "=== _torch_flavor_tag ==="assert_eq "cu130 wheel" "cu130" "$(_torch_flavor_tag '2.10.0+cu130')"assert_eq "cu128 wheel" "cu128" "$(_torch_flavor_tag '2.8.0+cu128')"diff --git a/tests/sh/test_uninstall_arg_guard.sh b/tests/sh/test_uninstall_arg_guard.shindex d4c798c8d9d..8978cc8bc0d 100755--- a/tests/sh/test_uninstall_arg_guard.sh+++ b/tests/sh/test_uninstall_arg_guard.sh@@ -7,9 +7,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"SOURCE_UNINSTALL_SH="$SCRIPT_DIR/../../scripts/uninstall.sh"-PASS=0-FAIL=0BODY_MARKER="__UNSLOTH_TEST_BODY_REACHED__"_TMP_ROOT=$(mktemp -d)@@ -31,7 +30,6 @@ XDG_RUNTIME_DIR="$_TMP_ROOT/run"export XDG_RUNTIME_DIRmkdir -p "$XDG_RUNTIME_DIR"-ok() { echo " PASS: $1"; PASS=$((PASS + 1)); }nope() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }check() {diff --git a/tests/sh/test_uv_cache_colocation.sh b/tests/sh/test_uv_cache_colocation.shindex 34ecdb724a9..3f41c9249a1 100755--- a/tests/sh/test_uv_cache_colocation.sh+++ b/tests/sh/test_uv_cache_colocation.sh@@ -20,21 +20,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--assert_eq() {- _label="$1"; _expected="$2"; _actual="$3"- if [ "$_actual" = "$_expected" ]; then- echo " PASS: $_label"- PASS=$((PASS + 1))- else- echo " FAIL: $_label (expected '$_expected', got '$_actual')"- FAIL=$((FAIL + 1))- fi-}-# Lift the block out of install.sh so the real code is what runs here._FN_FILE=$(mktemp)_TMP=$(mktemp -d)diff --git a/tests/sh/test_uv_pinned_release.sh b/tests/sh/test_uv_pinned_release.shindex 9b79ea2ca3a..c4ddad3b639 100755--- a/tests/sh/test_uv_pinned_release.sh+++ b/tests/sh/test_uv_pinned_release.sh@@ -14,13 +14,8 @@set -eSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+. "$SCRIPT_DIR/_harness.sh"INSTALL_SH="$SCRIPT_DIR/../../install.sh"-PASS=0-FAIL=0--ok() { echo " PASS: $1"; PASS=$((PASS + 1)); }-bad() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }-WORK="$(mktemp -d)"trap 'rm -rf "$WORK"' EXIT@@ -573,7 +568,6 @@ elseok "an unpinned architecture declines so the fallback runs"fi-# An interrupted install must not leave the pinned path's temporaries behind: the work# directory holds a ~40 MB unpacked archive, and the staging file sits inside a directory that# is on PATH. The helper's own cleanup only runs when it returns normally, so both have to bediff --git a/tests/version_compat/test_bitsandbytes_pinned_symbols.py b/tests/version_compat/test_bitsandbytes_pinned_symbols.pyindex 24c7bd96eda..a8acd7e2a27 100644--- a/tests/version_compat/test_bitsandbytes_pinned_symbols.py+++ b/tests/version_compat/test_bitsandbytes_pinned_symbols.py@@ -19,9 +19,11 @@ BNB_TAGS = ["main",]+# Every check runs once per tag; one that cannot skips from inside so the tag stays in the report.+pytestmark = pytest.mark.parametrize("tag", BNB_TAGS)+# bnb.functional dequantize_4bit / quantize_4bit: the public 4-bit surface unsloth kernels call into.[email protected]("tag", BNB_TAGS)def test_bnb_functional_4bit(tag: str):candidates = ["bitsandbytes/functional.py",@@ -38,7 +40,6 @@ def test_bnb_functional_4bit(tag: str):# bnb.nn.Linear4bit / Params4bit: peft + unsloth isinstance-check these; renaming breaks 4-bit LoRA.[email protected]("tag", BNB_TAGS)def test_bnb_nn_linear4bit_classes(tag: str):candidates = ["bitsandbytes/nn/modules.py",@@ -64,7 +65,6 @@ def test_bnb_nn_linear4bit_classes(tag: str):# Coverage extension (2026-05):# Top-level export: unsloth/kernels/utils.py + zoo vllm_utils.py call bnb.matmul_4bit(...).[email protected]("tag", BNB_TAGS)def test_bnb_matmul_4bit_top_level(tag: str):src = fetch_text("bitsandbytes-foundation/bitsandbytes", tag, "bitsandbytes/__init__.py")if src is None:@@ -75,7 +75,6 @@ def test_bnb_matmul_4bit_top_level(tag: str):)[email protected]("tag", BNB_TAGS)def test_bnb_functional_4bit_kernel_path(tag: str):"""bnb.functional must expose either the legacy `lib.c*` kernels or the new `torch.ops.bitsandbytes.*` path."""candidates = [@@ -99,7 +98,6 @@ def test_bnb_functional_4bit_kernel_path(tag: str):)[email protected]("tag", BNB_TAGS)def test_bnb_functional_get_ptr(tag: str):"""unsloth/kernels/utils.py top-level: `get_ptr = bnb.functional.get_ptr`."""candidates = [@@ -116,7 +114,6 @@ def test_bnb_functional_get_ptr(tag: str):)[email protected]("tag", BNB_TAGS)def test_bnb_quantstate_from_dict(tag: str):"""unsloth-zoo rebinds QuantState.from_dict; both class and classmethod must be present."""candidates = [@@ -133,7 +130,6 @@ def test_bnb_quantstate_from_dict(tag: str):)[email protected]("tag", BNB_TAGS)def test_bnb_nn_modules_fix_4bit_weight_optional(tag: str):"""fix_4bit_weight_quant_state_from_module is optional; unsloth getattr-fallbacks on older bnb."""src = fetch_text("bitsandbytes-foundation/bitsandbytes", tag, "bitsandbytes/nn/modules.py")@@ -143,7 +139,6 @@ def test_bnb_nn_modules_fix_4bit_weight_optional(tag: str):pytest.skip(f"{tag}: helper not yet added (OK; getattr fallback)")[email protected]("tag", BNB_TAGS)def test_bnb_nn_linear8bitlt(tag: str):"""unsloth/__init__ probes both Linear4bit AND Linear8bitLt."""candidates = [@@ -159,7 +154,6 @@ def test_bnb_nn_linear8bitlt(tag: str):)[email protected]("tag", BNB_TAGS)def test_bnb_optim_optimizer2state(tag: str):"""PagedAdamW32bit + 8bit optimisers subclass Optimizer2State."""src = fetch_text(@@ -174,7 +168,6 @@ def test_bnb_optim_optimizer2state(tag: str):), f"{tag}: bnb.optim.optimizer.Optimizer2State missing"[email protected]("tag", BNB_TAGS)def test_bnb_utils_pack_unpack(tag: str):"""4bit state-dict save/load uses these two helpers."""src = fetch_text("bitsandbytes-foundation/bitsandbytes", tag, "bitsandbytes/utils.py")@@ -184,7 +177,6 @@ def test_bnb_utils_pack_unpack(tag: str):assert has_def(src, name, "func") or name in src, f"{tag}: bnb.utils.{name} missing"[email protected]("tag", BNB_TAGS)def test_bnb_cextension_rocm_warp_size_optional(tag: str):"""ROCM_WARP_SIZE_64 is optional (pre-ROCm bnb lacks it); unsloth probes via try/except."""src = fetch_text("bitsandbytes-foundation/bitsandbytes", tag, "bitsandbytes/cextension.py")@@ -194,7 +186,6 @@ def test_bnb_cextension_rocm_warp_size_optional(tag: str):pytest.skip(f"{tag}: ROCM_WARP_SIZE_64 not yet defined (pre-ROCm bnb)")[email protected]("tag", BNB_TAGS)def test_bnb_autograd_functions_matmul_4bit(tag: str):"""bnb.autograd._functions.matmul_4bit must remain (unsloth-zoo has a dynamo-disable patch site)."""src = fetch_text(@@ -207,7 +198,6 @@ def test_bnb_autograd_functions_matmul_4bit(tag: str):assert "matmul_4bit" in src, f"{tag}: bnb.autograd._functions.matmul_4bit missing"[email protected]("tag", BNB_TAGS)def test_bnb_version_parseable(tag: str):"""bnb.__version__ must be exported via at least one mechanism (unsloth feature-gates on it)."""src = fetch_text("bitsandbytes-foundation/bitsandbytes", tag, "bitsandbytes/__init__.py")diff --git a/tests/version_compat/test_peft_pinned_symbols.py b/tests/version_compat/test_peft_pinned_symbols.pyindex bbbc357d827..ebd0e5af9b4 100644--- a/tests/version_compat/test_peft_pinned_symbols.py+++ b/tests/version_compat/test_peft_pinned_symbols.py@@ -24,10 +24,12 @@ PEFT_TAGS = ["main",]+# Every check runs once per tag; one that cannot skips from inside so the tag stays in the report.+pytestmark = pytest.mark.parametrize("tag", PEFT_TAGS)+# Top-level re-exports: sentence_transformer.py:1948 does `from peft import LoraConfig, get_peft_model`;# unsloth_zoo saving_utils/lora extractors hit PeftModel.[email protected]("tag", PEFT_TAGS)def test_peft_top_level_exports(tag: str):src = fetch_text("huggingface/peft", tag, "src/peft/__init__.py")assert src is not None, f"{tag}: src/peft/__init__.py missing"@@ -47,7 +49,6 @@ def test_peft_top_level_exports(tag: str):# LoraConfig at the canonical sub-module path: peft.tuners.lora.LoraConfig (or# peft.tuners.lora.config.LoraConfig). unsloth-zoo's normaliser inspects it via getattr() and dataclass field# introspection.[email protected]("tag", PEFT_TAGS)def test_peft_lora_config_class(tag: str):candidates = ["src/peft/tuners/lora/config.py",@@ -63,7 +64,6 @@ def test_peft_lora_config_class(tag: str):# get_peft_model: top-level helper used by sentence_transformer.py:2043.[email protected]("tag", PEFT_TAGS)def test_get_peft_model_function(tag: str):"""get_peft_model may live in mapping.py or mapping_func.py (0.18+ split)."""candidates = [@@ -81,7 +81,6 @@ def test_get_peft_model_function(tag: str):# LoraLayer base class: unsloth-zoo's MoE LoRA extractor walks subclasses of peft.tuners.lora.LoraLayer. A# rename/move makes the walk silently return 0.[email protected]("tag", PEFT_TAGS)def test_peft_lora_layer_class(tag: str):candidates = ["src/peft/tuners/lora/layer.py",@@ -101,7 +100,6 @@ def test_peft_lora_layer_class(tag: str):# bnb-aware LoRA: peft.tuners.lora.bnb is the bitsandbytes integration point. Missing it -> 4bit LoRA silently# falls back to fp16 (bigger memory footprint).[email protected]("tag", PEFT_TAGS)def test_peft_lora_bnb_integration(tag: str):candidates = ["src/peft/tuners/lora/bnb.py",@@ -135,7 +133,6 @@ def test_peft_lora_bnb_integration(tag: str):# 1. peft.tuners.lora.layer.VARIANT_KWARG_KEYS, added in peft 0.18. unsloth-zoo#430 injects the import into the# compiled forward.[email protected]("tag", PEFT_TAGS)def test_peft_variant_kwarg_keys_const(tag: str):src = fetch_text("huggingface/peft", tag, "src/peft/tuners/lora/layer.py")if src is None:@@ -149,7 +146,6 @@ def test_peft_variant_kwarg_keys_const(tag: str):# 2. peft.tuners.lora.layer.ParamWrapper: peft 0.18 added the class for MoE 3D-parameter LoRA. unsloth-zoo#618# monkey-patches the MoE LoRA extractor.[email protected]("tag", PEFT_TAGS)def test_peft_param_wrapper_class(tag: str):src = fetch_text("huggingface/peft", tag, "src/peft/tuners/lora/layer.py")if src is None:@@ -166,7 +162,6 @@ def test_peft_param_wrapper_class(tag: str):# 3. peft.tuners.lora.LoraConfig.target_parameters: peft 0.19+. Used by unsloth-zoo's MoE target-parameter# extractor.[email protected]("tag", PEFT_TAGS)def test_peft_lora_config_target_parameters(tag: str):src = fetch_text("huggingface/peft", tag, "src/peft/tuners/lora/config.py")if src is None:@@ -183,7 +178,6 @@ def test_peft_lora_config_target_parameters(tag: str):# 4. peft.tuners.lora.model.LoraModel._create_and_replace: unsloth#4807 monkey-patches this for# Gemma4ClippableLinear.[email protected]("tag", PEFT_TAGS)def test_peft_lora_model_create_and_replace(tag: str):src = fetch_text("huggingface/peft", tag, "src/peft/tuners/lora/model.py")if src is None:@@ -197,7 +191,6 @@ def test_peft_lora_model_create_and_replace(tag: str):# 5. peft.utils.transformers_weight_conversion.build_peft_weight_mapping: unsloth#5167 wraps it to handle# WeightConversion.__init__ kwargs.[email protected]("tag", PEFT_TAGS)def test_peft_transformers_weight_conversion_module(tag: str):candidates = ["src/peft/utils/transformers_weight_conversion.py",@@ -216,7 +209,6 @@ def test_peft_transformers_weight_conversion_module(tag: str):# 6. peft.utils.integrations.dequantize_module_weight: used by 3 unsloth/unsloth-zoo callsites.[email protected]("tag", PEFT_TAGS)def test_peft_integrations_dequantize_module_weight(tag: str):candidates = ["src/peft/utils/integrations.py",@@ -233,7 +225,6 @@ def test_peft_integrations_dequantize_module_weight(tag: str):# 7. peft.PeftType.LORA: used by unsloth-zoo vllm_utils.py:2520-2559.[email protected]("tag", PEFT_TAGS)def test_peft_type_lora_enum(tag: str):candidates = ["src/peft/utils/peft_types.py",@@ -254,7 +245,6 @@ def test_peft_type_lora_enum(tag: str):# 8. peft.utils.ModulesToSaveWrapper: both peft.utils.* and peft.utils.other.* import paths used.[email protected]("tag", PEFT_TAGS)def test_peft_modules_to_save_wrapper(tag: str):candidates = ["src/peft/utils/other.py",@@ -274,7 +264,6 @@ def test_peft_modules_to_save_wrapper(tag: str):# 9. peft.PeftModel.from_pretrained signature pin: unsloth#4807.[email protected]("tag", PEFT_TAGS)def test_peft_peft_model_from_pretrained_signature(tag: str):src = fetch_text("huggingface/peft", tag, "src/peft/peft_model.py")assert src is not None, f"{tag}: src/peft/peft_model.py missing"@@ -285,7 +274,6 @@ def test_peft_peft_model_from_pretrained_signature(tag: str):# 10. peft.__version__ exported via known mechanism.[email protected]("tag", PEFT_TAGS)def test_peft_version_parseable(tag: str):src = fetch_text("huggingface/peft", tag, "src/peft/__init__.py")assert src is not Nonediff --git a/tests/version_compat/test_sentence_transformers_pinned_symbols.py b/tests/version_compat/test_sentence_transformers_pinned_symbols.pyindex bc1555e3224..e062eb4f722 100644--- a/tests/version_compat/test_sentence_transformers_pinned_symbols.py+++ b/tests/version_compat/test_sentence_transformers_pinned_symbols.py@@ -24,9 +24,11 @@ ST_TAGS = ["master",]+# Every check runs once per tag; one that cannot skips from inside so the tag stays in the report.+pytestmark = pytest.mark.parametrize("tag", ST_TAGS)+# Top-level: SentenceTransformer + SentenceTransformerTrainer must be importable.[email protected]("tag", ST_TAGS)def test_st_top_level_exports(tag: str):src = fetch_text("UKPLab/sentence-transformers", tag, "sentence_transformers/__init__.py")assert src is not None, f"{tag}: sentence_transformers/__init__.py missing"@@ -39,7 +41,6 @@ def test_st_top_level_exports(tag: str):# Sub-modules: unsloth walks `sentence_transformers.models` for these classes.[email protected]("tag", ST_TAGS)def test_st_models_re_exports(tag: str):"""Transformer / Pooling / Normalize must stay reachable via`sentence_transformers.models` despite the ST 5.4 package reorg."""@@ -105,7 +106,6 @@ def test_st_models_re_exports(tag: str):# Transformer base class: unsloth probes alternate paths; at least ONE must resolve.[email protected]("tag", ST_TAGS)def test_st_transformer_base_class_either_path(tag: str):candidates = ["sentence_transformers/models/Transformer.py",@@ -125,7 +125,6 @@ def test_st_transformer_base_class_either_path(tag: str):# Transformer.load classmethod: unsloth builds saved-ST modules through it (#6881).[email protected]("tag", ST_TAGS)def test_st_transformer_load_accepts_unsloth_kwargs(tag: str):"""unsloth builds saved ST models via Transformer.load(...) so the savedmodality_config is honored (#6881). If .load stops accepting the hub kwargs it@@ -161,7 +160,6 @@ def test_st_transformer_load_accepts_unsloth_kwargs(tag: str):# sentence_transformers.util: import_from_string + load_dir_path helpers unsloth calls.[email protected]("tag", ST_TAGS)def test_st_util_helpers(tag: str):"""util.{import_from_string, load_dir_path} must resolve; accept either theflat or the ST 5.4+ package layout, or a re-export from a util submodule."""diff --git a/tests/version_compat/test_transformers_pinned_symbols.py b/tests/version_compat/test_transformers_pinned_symbols.pyindex 1c4a5e0708a..96d91aa2b62 100644--- a/tests/version_compat/test_transformers_pinned_symbols.py+++ b/tests/version_compat/test_transformers_pinned_symbols.py@@ -47,9 +47,11 @@ TRANSFORMERS_TAGS = ["main",]+# Every check runs once per tag; one that cannot skips from inside so the tag stays in the report.+pytestmark = pytest.mark.parametrize("tag", TRANSFORMERS_TAGS)+# Trainer surface: unsloth/models/_utils.py rewrites Trainer.{__init__, training_step, get_batch_samples, compute_loss}.[email protected]("tag", TRANSFORMERS_TAGS)def test_trainer_class_importable_path(tag: str):"""transformers.Trainer must remain at trainer.py or trainer/__init__.py."""candidates = ["src/transformers/trainer.py", "src/transformers/trainer/__init__.py"]@@ -59,7 +61,6 @@ def test_trainer_class_importable_path(tag: str):assert has_def(src, "Trainer", "class"), f"{tag}: class Trainer missing"[email protected]("tag", TRANSFORMERS_TAGS)def test_trainer_compute_loss_num_items_in_batch_param(tag: str):"""unsloth-zoo#159 + unsloth#4998 + #4616: Trainer.compute_loss must accept num_items_in_batch kwarg."""candidates = ["src/transformers/trainer.py", "src/transformers/trainer/__init__.py"]@@ -75,7 +76,6 @@ def test_trainer_compute_loss_num_items_in_batch_param(tag: str):)[email protected]("tag", TRANSFORMERS_TAGS)def test_trainer_training_step_grad_accum_pattern(tag: str):"""unsloth#3598 patches Trainer.training_step source; drift = silent no-op = double-scale loss bug."""candidates = ["src/transformers/trainer.py", "src/transformers/trainer/__init__.py"]@@ -97,7 +97,6 @@ def test_trainer_training_step_grad_accum_pattern(tag: str):)[email protected]("tag", TRANSFORMERS_TAGS)def test_trainer_get_batch_samples_returns_num_items(tag: str):"""unsloth-zoo loss_utils.py:241 replaces Trainer.get_batch_samples; must keep the num_items_in_batch return."""candidates = ["src/transformers/trainer.py", "src/transformers/trainer/__init__.py"]@@ -111,7 +110,6 @@ def test_trainer_get_batch_samples_returns_num_items(tag: str):), f"{tag}: Trainer.get_batch_samples / num_items_in_batch contract missing"[email protected]("tag", TRANSFORMERS_TAGS)def test_trainer_inner_training_loop_inplace_loss_v5(tag: str):"""unsloth-zoo#543: transformers 5.0+ switched out-of-place tr_loss add to in-place `self._tr_loss +=`."""candidates = ["src/transformers/trainer.py", "src/transformers/trainer/__init__.py"]@@ -129,7 +127,6 @@ def test_trainer_inner_training_loop_inplace_loss_v5(tag: str):# modeling_utils: checkpoint, PushToHubMixin, ALL_ATTENTION_FUNCTIONS.[email protected]("tag", TRANSFORMERS_TAGS)def test_modeling_utils_exposes_checkpoint(tag: str):"""unsloth-zoo#549: transformers 5.2+ uses modeling_utils.checkpoint; patch must replace it, not just torch's."""src = fetch_text("huggingface/transformers", tag, "src/transformers/modeling_utils.py")@@ -151,7 +148,6 @@ def test_modeling_utils_exposes_checkpoint(tag: str):)[email protected]("tag", TRANSFORMERS_TAGS)def test_pushtohubmixin_create_repo_status(tag: str):"""unsloth-zoo#393: transformers 5.x removed PushToHubMixin._create_repo; snapshot which side."""src = fetch_text("huggingface/transformers", tag, "src/transformers/modeling_utils.py")@@ -162,7 +158,6 @@ def test_pushtohubmixin_create_repo_status(tag: str):# integrations.bitsandbytes: _replace_with_bnb_linear vs new path.[email protected]("tag", TRANSFORMERS_TAGS)def test_integrations_bitsandbytes_module_present(tag: str):src = fetch_text("huggingface/transformers", tag, "src/transformers/integrations/bitsandbytes.py"@@ -174,7 +169,6 @@ def test_integrations_bitsandbytes_module_present(tag: str):), f"{tag}: integrations/bitsandbytes.py has no Linear4bit reference"[email protected]("tag", TRANSFORMERS_TAGS)def test_quantizers_should_convert_module_signature(tag: str):"""unsloth-zoo#491/#488: 5.x moved is_replaceable to quantizers_utils.should_convert_module; snapshot its form."""src = fetch_text(@@ -191,7 +185,6 @@ def test_quantizers_should_convert_module_signature(tag: str):# integrations.finegrained_fp8.FP8Linear: bias/has_bias rename in v5.[email protected]("tag", TRANSFORMERS_TAGS)def test_fp8linear_init_param_names(tag: str):"""unsloth-zoo#572: transformers 5.x renamed FP8Linear.__init__ `bias` -> `has_bias`."""src = fetch_text(@@ -210,7 +203,6 @@ def test_fp8linear_init_param_names(tag: str):), f"{tag}: FP8Linear.__init__ has neither `bias` nor `has_bias` param"[email protected]("tag", TRANSFORMERS_TAGS)def test_processing_utils_unpack_importable(tag: str):"""unsloth-zoo#583/584: transformers.processing_utils.Unpack must keep importing."""src = fetch_text("huggingface/transformers", tag, "src/transformers/processing_utils.py")@@ -226,7 +218,6 @@ def test_processing_utils_unpack_importable(tag: str):# Models: gemma3, gpt_oss forward signature drift.[email protected]("tag", TRANSFORMERS_TAGS)def test_gemma3_attention_forward_present(tag: str):src = fetch_text("huggingface/transformers",@@ -238,7 +229,6 @@ def test_gemma3_attention_forward_present(tag: str):assert has_def(src, "Gemma3Attention", "class"), f"{tag}: class Gemma3Attention missing"[email protected]("tag", TRANSFORMERS_TAGS)def test_gpt_oss_model_forward_present(tag: str):src = fetch_text("huggingface/transformers",@@ -253,7 +243,6 @@ def test_gpt_oss_model_forward_present(tag: str):# auto_factory: unsloth#5155 _LazyAutoMapping private API.[email protected]("tag", TRANSFORMERS_TAGS)def test_auto_factory_lazy_mapping_private_api(tag: str):"""unsloth#5155: resolve_model_class needs all four _LazyAutoMapping private attrs to remain."""src = fetch_text(@@ -276,7 +265,6 @@ def test_auto_factory_lazy_mapping_private_api(tag: str):)[email protected]("tag", TRANSFORMERS_TAGS)def test_configuration_utils_alias(tag: str):"""transformers 5.x renamed PretrainedConfig -> PreTrainedConfig; unsloth-zoo imports both defensively."""src = fetch_text(@@ -295,7 +283,6 @@ def test_configuration_utils_alias(tag: str):# tokenization: apply_chat_template return_dict default flip in v5.[email protected]("tag", TRANSFORMERS_TAGS)def test_apply_chat_template_signature_present(tag: str):"""unsloth-zoo#572: apply_chat_template `return_dict` default flipped False -> True in transformers 5.x."""src = fetch_text(@@ -311,7 +298,6 @@ def test_apply_chat_template_signature_present(tag: str):# Generic-importability sweep: every transformers symbol unsloth/zoo imports must stay reachable.[email protected]("tag", TRANSFORMERS_TAGS)def test_modeling_attn_mask_utils_symbols(tag: str):"""_prepare_4d_attention_mask_for_sdpa is imported by unsloth/models/llama.py + sentence_transformer.py."""src = fetch_text(@@ -329,7 +315,6 @@ def test_modeling_attn_mask_utils_symbols(tag: str):# Generic-importability sweep:[email protected]("tag", TRANSFORMERS_TAGS)def test_cache_utils_classes(tag: str):src = fetch_text("huggingface/transformers", tag, "src/transformers/cache_utils.py")if src is None:@@ -339,7 +324,6 @@ def test_cache_utils_classes(tag: str):assert has_def(src, cls, "class"), f"{tag}: transformers.cache_utils.{cls} missing"[email protected]("tag", TRANSFORMERS_TAGS)def test_training_args_parallel_mode_importable(tag: str):src = fetch_text("huggingface/transformers", tag, "src/transformers/training_args.py")if src is None:diff --git a/tests/version_compat/test_trl_grpo_pinned_symbols.py b/tests/version_compat/test_trl_grpo_pinned_symbols.pyindex 0e2ee67d259..bea7822d06e 100644--- a/tests/version_compat/test_trl_grpo_pinned_symbols.py+++ b/tests/version_compat/test_trl_grpo_pinned_symbols.py@@ -62,6 +62,9 @@ TRL_TAGS = ["main",]+# Every check runs once per tag; one that cannot skips from inside so the tag stays in the report.+pytestmark = pytest.mark.parametrize("tag", TRL_TAGS)+def _tag_ge(tag: str, floor: str) -> bool:"""True if `tag` is `main` or a version >= `floor` (e.g. "1.7.0")."""@@ -76,7 +79,6 @@ def _tag_ge(tag: str, floor: str) -> bool:# unsloth/trainer.py + unsloth/models/rl.py rebind these top-level names.[email protected]("tag", TRL_TAGS)def test_trl_top_level_grpo_sft(tag: str):"""GRPO/SFT Trainer+Config must resolve at the trl package root."""src = fetch_text("huggingface/trl", tag, "trl/__init__.py")@@ -90,7 +92,6 @@ def test_trl_top_level_grpo_sft(tag: str):# trl.trainer.grpo_trainer.GRPOTrainer# unsloth's RL patcher discovers it via `eval(f"trl.trainer.{trainer_file}.{name}")` in unsloth/models/rl.py:548-594.[email protected]("tag", TRL_TAGS)def test_grpo_trainer_class_canonical_path(tag: str):src = fetch_text("huggingface/trl", tag, "trl/trainer/grpo_trainer.py")assert src is not None, (@@ -102,7 +103,6 @@ def test_grpo_trainer_class_canonical_path(tag: str):), f"{tag}: trl.trainer.grpo_trainer.GRPOTrainer not defined as a class"[email protected]("tag", TRL_TAGS)def test_grpo_config_class_canonical_path(tag: str):"""GRPOConfig must be discoverable by the *Config heuristic in rl.py:579-618."""candidates = ["trl/trainer/grpo_config.py", "trl/trainer/grpo_trainer.py"]@@ -117,7 +117,6 @@ def test_grpo_config_class_canonical_path(tag: str):# DataCollatorForPreference: rl_replacements.py:318 hard-imports from trl.trainer.dpo_trainer (old TRL had it in# trl.trainer.utils).[email protected]("tag", TRL_TAGS)def test_data_collator_for_preference_resolvable(tag: str):"""DataCollatorForPreference must exist in dpo_trainer or utils (rl_replacements.py:318 imports it)."""new_path = fetch_text("huggingface/trl", tag, "trl/trainer/dpo_trainer.py")@@ -135,7 +134,6 @@ def test_data_collator_for_preference_resolvable(tag: str):# trl.trainer.utils.pad: emitted into the GRPO compile cell as _unsloth_trl_pad (rl_replacements.py:326).[email protected]("tag", TRL_TAGS)def test_trl_trainer_utils_pad(tag: str):src = fetch_text("huggingface/trl", tag, "trl/trainer/utils.py")if src is None:@@ -151,7 +149,6 @@ def test_trl_trainer_utils_pad(tag: str):# trl.models.unwrap_model_for_generation# unsloth/models/rl.py:152-155 handles both paths.[email protected]("tag", TRL_TAGS)def test_unwrap_model_for_generation_either_path(tag: str):"""unwrap_model_for_generation must resolve via one of the two paths rl.py:152-155 tries (mirror prod exactly)."""candidates = [@@ -172,7 +169,6 @@ def test_unwrap_model_for_generation_either_path(tag: str):# trl.experimental.openenv: gated import (rl_replacements.py:1765-1770). When present, must export the symbols# unsloth patches.[email protected]("tag", TRL_TAGS)def test_trl_experimental_openenv_gated(tag: str):src = fetch_text("huggingface/trl", tag, "trl/experimental/openenv/__init__.py")if src is None:@@ -186,7 +182,6 @@ def test_trl_experimental_openenv_gated(tag: str):# trl.generation.vllm_generation: gated import for the fast_inference server mode (rl_replacements.py:1846-1848).[email protected]("tag", TRL_TAGS)def test_trl_generation_vllm_generation_gated(tag: str):"""VLLMGeneration + its _init_vllm/sync_weights/generate methods mustexist when the module is present, else rl_replacements.py:1851-1971@@ -206,7 +201,6 @@ def test_trl_generation_vllm_generation_gated(tag: str):# TRL's __version__ must be parseable; rl.py:63 string-matches it.[email protected]("tag", TRL_TAGS)def test_trl_version_parseable(tag: str):src = fetch_text("huggingface/trl", tag, "trl/__init__.py")assert src is not None@@ -235,7 +229,6 @@ def test_trl_version_parseable(tag: str):# Coverage extension (added 2026-05): symbols/source-string contracts# unsloth + unsloth-zoo touch that the original suite missed.# 1. trl.is_conversational — soft import in unsloth-zoo dataset_utils.[email protected]("tag", TRL_TAGS)def test_trl_is_conversational_export(tag: str):src = fetch_text("huggingface/trl", tag, "trl/__init__.py")assert src is not None@@ -245,7 +238,6 @@ def test_trl_is_conversational_export(tag: str):# 2-4. trl.trainer.sft_trainer surface used by unsloth tokenizer utils + tests.[email protected]("tag", TRL_TAGS)def test_trl_sft_trainer_module_internals(tag: str):"""sft_trainer symbols for the `from trl.trainer.sft_trainer import *` at tokenizer_utils.py:1538."""src = fetch_text("huggingface/trl", tag, "trl/trainer/sft_trainer.py")@@ -261,7 +253,6 @@ def test_trl_sft_trainer_module_internals(tag: str):# 5-6. trl.trainer.dpo_trainer + MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, patched by# unsloth-zoo/temporary_patches/misc.py:1376-1379.[email protected]("tag", TRL_TAGS)def test_trl_dpo_trainer_module_exists(tag: str):src = fetch_text("huggingface/trl", tag, "trl/trainer/dpo_trainer.py")assert src is not None, (@@ -273,7 +264,6 @@ def test_trl_dpo_trainer_module_exists(tag: str):# 7. trl.trainer.utils.ConstantLengthDataset — optional soft import in# unsloth-zoo/dataset_utils.py:596 (TRL 0.20.0 removed it on some paths).[email protected]("tag", TRL_TAGS)def test_trl_constant_length_dataset_optional(tag: str):candidates = ["trl/trainer/utils.py",@@ -292,7 +282,6 @@ def test_trl_constant_length_dataset_optional(tag: str):# 8. trl.models.utils.disable_gradient_checkpointing — added in TRL 1.0.0+.# rl.py:1976-1994 gates via hasattr(); assert the symbol exists from# 1.0.0 onwards so a future removal gets caught.[email protected]("tag", TRL_TAGS)def test_trl_models_utils_disable_gradient_checkpointing(tag: str):if tag == "main":require = True@@ -317,7 +306,6 @@ def test_trl_models_utils_disable_gradient_checkpointing(tag: str):# 9. trl.import_utils `_*_available` cache pattern — import_fixes.py:508-516# clears these cached booleans so vllm-ascend imports work.[email protected]("tag", TRL_TAGS)def test_trl_import_utils_available_pattern(tag: str):candidates = ["trl/import_utils.py",@@ -338,7 +326,6 @@ def test_trl_import_utils_available_pattern(tag: str):# 10. trl.experimental.openenv.utils generators - one of the two function names must exist# (rl_replacements.py:1775-1781 getattr()s for one).[email protected]("tag", TRL_TAGS)def test_trl_openenv_utils_generators(tag: str):src = fetch_text("huggingface/trl", tag, "trl/experimental/openenv/utils.py")if src is None:@@ -354,7 +341,6 @@ def test_trl_openenv_utils_generators(tag: str):# 11-16. GRPOTrainer required method names. rl_replacements.py dispatches on function_name == "...";# a renamed method silently skips the patch.[email protected]("tag", TRL_TAGS)def test_trl_grpo_trainer_required_methods(tag: str):"""GRPOTrainer methods unsloth rewrites against; drift silently skipsthe rewrite. _get_per_token_logps was renamed to@@ -385,7 +371,6 @@ def test_trl_grpo_trainer_required_methods(tag: str):# some patterns apply only to a subset of minors.[email protected]("tag", TRL_TAGS)def test_trl_grpo_source_inference_mode_unwrap(tag: str):"""`torch.inference_mode` and `self.accelerator.unwrap_model` must bothappear, or rl_replacements.py:526-535 autocast insertion no-ops."""@@ -401,7 +386,6 @@ def test_trl_grpo_source_inference_mode_unwrap(tag: str):# 17. KTOTrainer.get_batch_logps + the literal raise-message rewriter.[email protected]("tag", TRL_TAGS)def test_trl_kto_get_batch_logps_signature(tag: str):"""KTO log-prob computation must stay patchable. Older TRL exposedKTOTrainer.get_batch_logps; TRL 1.x moved the math into@@ -443,7 +427,6 @@ def test_trl_kto_get_batch_logps_signature(tag: str):# 18. SFTTrainer + the `dict_args.pop("push_to_hub_token")` shim. transformers 5.0 removed the kwarg; if TRL stops# emitting the bare pop, our patch no-ops AND TRL itself crashes on transformers 5.0.[email protected]("tag", TRL_TAGS)def test_trl_sft_trainer_class(tag: str):"""SFTTrainer must exist. The push_to_hub_token pop literal is checkedonly when present; its absence means TRL already adapted (fine)."""@@ -453,7 +436,6 @@ def test_trl_sft_trainer_class(tag: str):# 19-21. DPOTrainer methods unsloth-zoo's rl_replacements rewrites.[email protected]("tag", TRL_TAGS)def test_trl_dpo_trainer_methods(tag: str):"""DPOTrainer methods unsloth's rewriters key on (rl_replacements.py:222-394). All version-windowed and non-required (the rewriter@@ -475,7 +457,6 @@ def test_trl_dpo_trainer_methods(tag: str):# 22-23. grpo_trainer must have in scope the helpers unsloth's rewriters reference (profiling_context,# maybe_apply_chat_template, truncate_with_protected_tokens), defined or imported from trl.*.[email protected]("tag", TRL_TAGS)def test_trl_grpo_internal_helpers_in_scope(tag: str):"""Chat-template kwargs must propagate via legacy`maybe_apply_chat_template` (TRL <=0.24, rewritten by unsloth) or@@ -494,7 +475,6 @@ def test_trl_grpo_internal_helpers_in_scope(tag: str):)[email protected]("tag", TRL_TAGS)def test_trl_truncate_with_protected_tokens_optional(tag: str):"""Informational: track truncate_with_protected_tokens (shipped TRL0.22.2-0.23.1, later removed) so a silent rename doesn't slip past@@ -510,7 +490,6 @@ def test_trl_truncate_with_protected_tokens_optional(tag: str):# The 1.7.0 break was invisible to the existence checks because the methods still existed -- only their internal# structure / return arity changed. If TRL restructures one of these, the transform silently no-ops (or the generated# trainer breaks), so failing here on `main` gives a few-day lead.[email protected]("tag", TRL_TAGS)def test_trl_grpo_peft_ref_adapter_block_contract(tag: str):"""rl.py (trl>=1.4.0) strips TRL's PEFT ref-adapter init with a re.DOTALLregex anchored on `elif is_peft_model(model) and args.beta != 0.0:` ...@@ -539,7 +518,6 @@ def test_trl_grpo_peft_ref_adapter_block_contract(tag: str):)[email protected]("tag", TRL_TAGS)def test_trl_grpo_quantized_model_cast_contract(tag: str):"""rl.py (trl>=1.7.0) neutralizes TRL's hardcoded QLoRA bf16 cast`if _is_quantized_model:` -> `if False:`. A rename leaves the cast active,@@ -554,7 +532,6 @@ def test_trl_grpo_quantized_model_cast_contract(tag: str):)[email protected]("tag", TRL_TAGS)def test_trl_grpo_aux_loss_enabled_contract(tag: str):"""rl.py (trl>=1.7.0) appends a fail-fast after`self.aux_loss_enabled = is_moe and args.router_aux_loss_coef != 0.0` so an@@ -571,7 +548,6 @@ def test_trl_grpo_aux_loss_enabled_contract(tag: str):)[email protected]("tag", TRL_TAGS)def test_trl_grpo_per_token_logps_aux_arity_contract(tag: str):"""TRL 1.7.0 added `compute_aux_loss` to_get_per_token_logps_and_entropies and made every call site unpack a