Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Say both load fallbacks when both fire, and repair the two suites that guard it (#9189)

Daniel Handf8fb6a03b00
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.yml
index 6d86c2f5214..baed647c85f 100644
--- a/.github/workflows/studio-ui-smoke.yml
+++ b/.github/workflows/studio-ui-smoke.yml
@@ -206,13 +206,68 @@ jobs:
# --with-deps stays unconditional: the apt side installs system libraries OUTSIDE
# the cached directory, so a restored cache without it gives browsers that cannot
# start. Only the download is skipped, which is the part that costs.
+ #
+ # Bounded and retried, because this step stalls. Three times in one day it sat in
+ # apt's download loop until the job's 30-minute timeout killed it: the shards that
+ # hit it took 30 minutes to report nothing, while their siblings finished the whole
+ # job in 4 to 9. GitHub scores that as "cancelled" rather than a failure, prints no
+ # reason, and skips every step after it, so an infrastructure hiccup costs a shard's
+ # entire surface and reads like a mystery.
+ #
+ # A per-attempt `timeout` makes the stall a failure instead of a silent wait, and
+ # the retry is what actually recovers -- both observed stalls cleared on a plain
+ # re-run of the same commit. The healthy time is about 2 minutes, so 8 is 4x
+ # headroom and a merely slow mirror will not trip it. timeout-minutes bounds the
+ # pair in case `timeout` itself is outlived by an unkillable child.
+ timeout-minutes: 22
run: |
if [ "${{ steps.pw-cache.outputs.cache-hit }}" = "true" ]; then
- python -m playwright install-deps chromium firefox webkit
+ set -- install-deps chromium firefox webkit
else
- python -m playwright install --with-deps chromium firefox webkit
+ set -- install --with-deps chromium firefox webkit
fi
+ # Wait for whatever the killed attempt left behind to let go of dpkg.
+ #
+ # The first version of this retry skipped this and could not recover.
+ # playwright shells out to apt-get as ROOT, so terminating the python
+ # parent leaves that child alive holding the lock, and attempt 2 died two
+ # seconds later with "Could not get lock /var/lib/dpkg/lock-frontend. It
+ # is held by process 4578 (apt-get)". A retry that cannot succeed is worse
+ # than no retry: it buries the real reason under a second, different
+ # failure.
+ release_dpkg_lock() {
+ for _ in $(seq 1 24); do
+ fuser /var/lib/dpkg/lock-frontend > /dev/null 2>&1 || return 0
+ sleep 5
+ done
+ # Still held after two minutes. It is our own orphan and this is a
+ # throwaway runner, so take the lock rather than spend the attempt.
+ echo "::warning::dpkg lock still held after 120s; terminating the holder"
+ fuser -k /var/lib/dpkg/lock-frontend > /dev/null 2>&1 || true
+ sleep 5
+ }
+
+ for attempt in 1 2; do
+ timeout --signal=TERM --kill-after=30 480 python -m playwright "$@"
+ rc=$?
+ [ "$rc" -eq 0 ] && exit 0
+ # 124 is timeout's own "I killed it"; 137 is SIGKILL landing after
+ # --kill-after. Anything else is playwright itself refusing, and saying
+ # "did not finish within 8 minutes" about a 2-second exit sends the next
+ # reader looking for a stall that never happened.
+ if [ "$rc" -eq 124 ] || [ "$rc" -eq 137 ]; then
+ reason="did not finish within 8 minutes"
+ else
+ reason="exited with status ${rc}"
+ fi
+ echo "::warning::playwright install attempt ${attempt} ${reason}"
+ [ "$attempt" -eq 2 ] && break
+ release_dpkg_lock
+ done
+ echo "::error::playwright browser install failed twice; the attempt warnings above say which way each one went"
+ exit 1
+
# Save on main only, like every model cache in this repo. read-write
# `actions/cache` saves from its post-step on EVERY ref, and a PR-scoped entry
# can only be restored by re-runs of that same PR while still competing for the
@@ -646,13 +701,68 @@ jobs:
# --with-deps stays unconditional: the apt side installs system libraries OUTSIDE
# the cached directory, so a restored cache without it gives browsers that cannot
# start. Only the download is skipped, which is the part that costs.
+ #
+ # Bounded and retried, because this step stalls. Three times in one day it sat in
+ # apt's download loop until the job's 30-minute timeout killed it: the shards that
+ # hit it took 30 minutes to report nothing, while their siblings finished the whole
+ # job in 4 to 9. GitHub scores that as "cancelled" rather than a failure, prints no
+ # reason, and skips every step after it, so an infrastructure hiccup costs a shard's
+ # entire surface and reads like a mystery.
+ #
+ # A per-attempt `timeout` makes the stall a failure instead of a silent wait, and
+ # the retry is what actually recovers -- both observed stalls cleared on a plain
+ # re-run of the same commit. The healthy time is about 2 minutes, so 8 is 4x
+ # headroom and a merely slow mirror will not trip it. timeout-minutes bounds the
+ # pair in case `timeout` itself is outlived by an unkillable child.
+ timeout-minutes: 22
run: |
if [ "${{ steps.pw-cache.outputs.cache-hit }}" = "true" ]; then
- python -m playwright install-deps chromium firefox webkit
+ set -- install-deps chromium firefox webkit
else
- python -m playwright install --with-deps chromium firefox webkit
+ set -- install --with-deps chromium firefox webkit
fi
+ # Wait for whatever the killed attempt left behind to let go of dpkg.
+ #
+ # The first version of this retry skipped this and could not recover.
+ # playwright shells out to apt-get as ROOT, so terminating the python
+ # parent leaves that child alive holding the lock, and attempt 2 died two
+ # seconds later with "Could not get lock /var/lib/dpkg/lock-frontend. It
+ # is held by process 4578 (apt-get)". A retry that cannot succeed is worse
+ # than no retry: it buries the real reason under a second, different
+ # failure.
+ release_dpkg_lock() {
+ for _ in $(seq 1 24); do
+ fuser /var/lib/dpkg/lock-frontend > /dev/null 2>&1 || return 0
+ sleep 5
+ done
+ # Still held after two minutes. It is our own orphan and this is a
+ # throwaway runner, so take the lock rather than spend the attempt.
+ echo "::warning::dpkg lock still held after 120s; terminating the holder"
+ fuser -k /var/lib/dpkg/lock-frontend > /dev/null 2>&1 || true
+ sleep 5
+ }
+
+ for attempt in 1 2; do
+ timeout --signal=TERM --kill-after=30 480 python -m playwright "$@"
+ rc=$?
+ [ "$rc" -eq 0 ] && exit 0
+ # 124 is timeout's own "I killed it"; 137 is SIGKILL landing after
+ # --kill-after. Anything else is playwright itself refusing, and saying
+ # "did not finish within 8 minutes" about a 2-second exit sends the next
+ # reader looking for a stall that never happened.
+ if [ "$rc" -eq 124 ] || [ "$rc" -eq 137 ]; then
+ reason="did not finish within 8 minutes"
+ else
+ reason="exited with status ${rc}"
+ fi
+ echo "::warning::playwright install attempt ${attempt} ${reason}"
+ [ "$attempt" -eq 2 ] && break
+ release_dpkg_lock
+ done
+ echo "::error::playwright browser install failed twice; the attempt warnings above say which way each one went"
+ exit 1
+
# Save on main only, like every model cache in this repo. read-write
# `actions/cache` saves from its post-step on EVERY ref, and a PR-scoped entry
# can only be restored by re-runs of that same PR while still competing for the
diff --git a/studio/backend/tests/test_tp_vision_regression.py b/studio/backend/tests/test_tp_vision_regression.py
index e0657e803f4..205db1bc75e 100644
--- a/studio/backend/tests/test_tp_vision_regression.py
+++ b/studio/backend/tests/test_tp_vision_regression.py
@@ -359,9 +359,32 @@ def test_tensor_split_abort_raises_early_to_layer_fallback():
src = inspect.getsource(LlamaCppBackend.load_model)
raise_idx = src.find("(split-axis geometry); retrying with layer split")
assert raise_idx != -1, "the split-axis abort must raise to trigger a layer retry"
- # raises before both the flash-attn-off retry and the text-only mmproj strip
- assert raise_idx < src.find("_with_flash_attn_off")
- assert raise_idx < src.find("_strip_mmproj_args(_last_spawn_cmd)")
+
+ # Raises before both the flash-attn-off retry and the text-only mmproj strip.
+ #
+ # Each landmark is required to exist before it is ordered. A bare
+ # `raise_idx < src.find(x)` reads as an ordering check but is really two
+ # claims, and it fails with "assert 249423 < -1" -- which says the ordering
+ # broke when what actually happened is that the landmark moved. This test
+ # went red on main that way when #9173 renamed the strip's argument from
+ # _last_spawn_cmd to _vision_gpu_cmd, a rename with no behavioural content.
+ #
+ # The strip is matched on the call, not on what is passed to it. What this
+ # test is about is that the abort raises BEFORE the projector is thrown
+ # away; which command the strip reads from is that code's own business.
+ for label, needle in (
+ ("the flash-attn-off retry", "_with_flash_attn_off"),
+ ("the text-only mmproj strip", "_strip_mmproj_args("),
+ ):
+ idx = src.find(needle)
+ assert idx != -1, (
+ f"{label} is no longer in load_model, so the ordering below asserts "
+ f"nothing. If it moved, point this at where it moved to."
+ )
+ assert raise_idx < idx, (
+ f"the split-axis abort no longer raises before {label}, so the layer "
+ f"retry runs after the projector has already been discarded (#6659)"
+ )
# gated on the marker-plus-crash helper, which also drives the record just above
guard = src[max(0, raise_idx - 600) : raise_idx]
assert "_should_record_tensor_split_abort" in guard
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 8547a3f63fe..ee52a8db051 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -146,7 +146,7 @@ import type {
OpenAIReasoningContentPart,
} from "../types/api";
import type { ChatModelSummary } from "../types/runtime";
-import { mmprojFallbackMessage } from "../utils/mmproj-fallback";
+import { loadFallbackNotice } from "../utils/mmproj-fallback";
import {
getStoredChatThread,
getStoredChatThreadReadResult,
@@ -2611,24 +2611,21 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
cpuFallbackReason?: CpuFallbackReason | null,
mmprojFallbackReason?: MmprojFallbackReason | null,
): void => {
+ // Both reasons, composed. Nesting them as `mmproj ? ... : cpu ? ...` dropped the
+ // CPU message whenever both were set, which is reachable and is the case this
+ // feature exists for -- see loadFallbackNotice.
+ const notice = loadFallbackNotice(
+ message,
+ cpuFallbackReason,
+ mmprojFallbackReason,
+ );
const options = {
- description: mmprojFallbackReason
- ? mmprojFallbackMessage(mmprojFallbackReason)
- : cpuFallbackReason
- ? "The auto-selected Vulkan backend crashed during startup, so GPU acceleration is disabled for this model session."
- : undefined,
+ description: notice.description,
duration: 5000,
icon: undefined,
};
- const showToast =
- mmprojFallbackReason || cpuFallbackReason ? toast.warning : toast.success;
- const title = mmprojFallbackReason
- ? mmprojFallbackReason === "cpu_offload"
- ? `${message} with vision on CPU`
- : `${message} without vision`
- : cpuFallbackReason
- ? `${message} on CPU`
- : message;
+ const showToast = notice.degraded ? toast.warning : toast.success;
+ const title = notice.title;
if (autoLoadToastDismissed) {
showToast(title, options);
return;
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index f2436737c73..c0eec72ce23 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -79,7 +79,7 @@ import {
resolveManualAutoCtxPin,
} from "../presets/preset-policy";
import { recordLastLocalModelLoad } from "../utils/last-local-model-load";
-import { mmprojLoadNotice } from "../utils/mmproj-fallback";
+import { loadFallbackNotice } from "../utils/mmproj-fallback";
import { refreshContextUsage } from "../utils/refresh-context-usage";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
import {
@@ -2201,21 +2201,16 @@ export function useChatModelRuntime() {
await performLoad();
// User cancelled mid-refresh; cancelLoading handles teardown.
if (abortCtrl.signal.aborted) return;
- const mmprojNotice = mmprojFallbackReason
- ? mmprojLoadNotice(toastDisplayName, mmprojFallbackReason)
- : null;
- const loadedTitle = mmprojNotice
- ? mmprojNotice.title
- : cpuFallbackReason
- ? `${toastDisplayName} loaded on CPU`
- : `${toastDisplayName} loaded`;
- const loadedDescription = mmprojNotice
- ? mmprojNotice.description
- : cpuFallbackReason
- ? "The auto-selected Vulkan backend crashed during startup, so GPU acceleration is disabled for this model session."
- : undefined;
- const showLoadedToast =
- mmprojNotice || cpuFallbackReason ? toast.warning : toast.success;
+ // Same composition as the auto-load path, through the same helper, so the
+ // two cannot describe an identical failure differently again.
+ const notice = loadFallbackNotice(
+ `${toastDisplayName} loaded`,
+ cpuFallbackReason,
+ mmprojFallbackReason,
+ );
+ const loadedTitle = notice.title;
+ const loadedDescription = notice.description;
+ const showLoadedToast = notice.degraded ? toast.warning : toast.success;
if (loadToastDismissedRef.current) {
showLoadedToast(loadedTitle, {
description: loadedDescription,
diff --git a/studio/frontend/src/features/chat/utils/fork-count-store.ts b/studio/frontend/src/features/chat/utils/fork-count-store.ts
index 847d3079b48..1f0dd98da1e 100644
--- a/studio/frontend/src/features/chat/utils/fork-count-store.ts
+++ b/studio/frontend/src/features/chat/utils/fork-count-store.ts
@@ -8,7 +8,11 @@
* message, so a 200-message thread spent 200 requests on every history event, and
* streaming raises one of those per chunk.
*/
-import { CHAT_HISTORY_UPDATED_EVENT, getThreadForkCounts } from "../api/chat-api";
+import {
+ CHAT_HISTORY_UPDATED_EVENT,
+ getThreadForkCounts,
+} from "../api/chat-api";
+import { isAssistantLocalThreadId } from "./thread-ids";
// Same reasoning as the sidebar's refresh: each quiet window costs one fetch.
export const FORK_COUNT_REFRESH_DEBOUNCE_MS = 300;
@@ -48,6 +52,16 @@ let listening = false;
async function refresh(threadId: string): Promise<void> {
const entry = entries.get(threadId);
if (!entry) return;
+ // A thread the server has never seen cannot have forks, so this request can only
+ // ever 404 -- and getThreadForkCounts already maps that to an empty map, which is
+ // what the entry starts as. It is a round trip whose answer is known.
+ //
+ // Not a rounding error: a new chat is in exactly this state, and this store
+ // refreshes on CHAT_HISTORY_UPDATED_EVENT, which fires once per streaming chunk.
+ // So the first reply in a new chat pays one guaranteed-useless request per debounce
+ // window for as long as it streams. The heavy-thread smoke is what noticed --
+ // it counts requests issued inside a measured interaction, and these landed there.
+ if (isAssistantLocalThreadId(threadId)) return;
const seq = ++entry.seq;
let counts: Counts;
try {
diff --git a/studio/frontend/src/features/chat/utils/mmproj-fallback.ts b/studio/frontend/src/features/chat/utils/mmproj-fallback.ts
index c0c6259b6da..30558c566b1 100644
--- a/studio/frontend/src/features/chat/utils/mmproj-fallback.ts
+++ b/studio/frontend/src/features/chat/utils/mmproj-fallback.ts
@@ -1,7 +1,17 @@
// 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 type { MmprojFallbackReason } from "../types/api";
+import type { CpuFallbackReason, MmprojFallbackReason } from "../types/api";
+
+/**
+ * Said when the whole model, not just the projector, ended up on the CPU.
+ *
+ * Lived as a duplicated string literal in chat-adapter.ts and
+ * use-chat-model-runtime.ts. It is here so the two load paths cannot describe the
+ * same condition differently, which is what let them drift apart below.
+ */
+export const CPU_FALLBACK_MESSAGE =
+ "The auto-selected Vulkan backend crashed during startup, so GPU acceleration is disabled for this model session.";
const MMPROJ_FALLBACK_MESSAGES: Record<MmprojFallbackReason, string> = {
cpu_offload:
@@ -37,3 +47,61 @@ export function mmprojLoadNotice(
description: mmprojFallbackMessage(reason),
};
}
+
+/**
+ * The one description of how a load was degraded, covering BOTH fallbacks.
+ *
+ * The two load paths each wrote this inline as
+ * `mmproj ? mmprojMessage : cpu ? cpuMessage : undefined`, which silently drops the
+ * CPU message whenever both are set. That combination is not hypothetical: on a
+ * CPU-fallback replay `llama_cpp.py` preserves `_cpu_fallback_reason` (it only clears
+ * it when `not _replaying_cpu_fallback`) and clears `_mmproj_fallback_reason` so the
+ * projector can fail again in that same launch. A low-VRAM machine whose Vulkan
+ * backend crashed is exactly where the projector then falls back too -- the case the
+ * feature was written for.
+ *
+ * The user was told "loaded without vision" and never told the model was on the CPU,
+ * so a silently unaccelerated session read as a deliberate, explained one.
+ *
+ * `baseTitle` is suffixed rather than replaced because the two callers name models
+ * differently: the auto-load passes a label that already reads "Loaded X (Q4_K_M)",
+ * the explicit load passes "X loaded". Both take the same suffixes, which is why one
+ * helper can serve them.
+ */
+export function loadFallbackNotice(
+ baseTitle: string,
+ cpuFallbackReason: CpuFallbackReason | null | undefined,
+ mmprojFallbackReason: MmprojFallbackReason | null | undefined,
+): { title: string; description: string | undefined; degraded: boolean } {
+ const textOnly = isTextOnlyMmprojFallback(mmprojFallbackReason);
+
+ // When the whole model is on the CPU, saying the projector is too adds nothing --
+ // "on CPU" already covers it. Losing vision entirely is a different fact and is
+ // always said.
+ let suffix = "";
+ if (cpuFallbackReason && textOnly) {
+ suffix = " on CPU, without vision";
+ } else if (cpuFallbackReason) {
+ suffix = " on CPU";
+ } else if (mmprojFallbackReason === "cpu_offload") {
+ suffix = " with vision on CPU";
+ } else if (textOnly) {
+ suffix = " without vision";
+ }
+
+ // Both sentences, CPU first: it is the broader condition, and the projector
+ // sentence reads as a detail under it.
+ const parts: string[] = [];
+ if (cpuFallbackReason) {
+ parts.push(CPU_FALLBACK_MESSAGE);
+ }
+ if (mmprojFallbackReason) {
+ parts.push(mmprojFallbackMessage(mmprojFallbackReason));
+ }
+
+ return {
+ title: `${baseTitle}${suffix}`,
+ description: parts.length > 0 ? parts.join(" ") : undefined,
+ degraded: Boolean(cpuFallbackReason || mmprojFallbackReason),
+ };
+}
diff --git a/studio/frontend/tests/auto-load-cpu-fallback-toast.test.ts b/studio/frontend/tests/auto-load-cpu-fallback-toast.test.ts
index f47bda2b7ee..00e14bad1ec 100644
--- a/studio/frontend/tests/auto-load-cpu-fallback-toast.test.ts
+++ b/studio/frontend/tests/auto-load-cpu-fallback-toast.test.ts
@@ -6,6 +6,23 @@ import { readFileSync } from "node:fs";
import test from "node:test";
import { fileURLToPath } from "node:url";
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { CPU_FALLBACK_MESSAGE, loadFallbackNotice } = await import(
+ "../src/features/chat/utils/mmproj-fallback.ts"
+);
+
+// Hoisted: biome's useTopLevelRegex flags a literal recompiled per call.
+const ON_CPU_SUFFIX = / on CPU$/;
+const GPU_DISABLED = /GPU acceleration is disabled for this model session/;
+const DELEGATES = /loadFallbackNotice\(/;
+const PICKS_WARNING = /notice\.degraded \? toast\.warning : toast\.success/;
+const PASSES_DESCRIPTION = /description: notice\.description/;
+const FORWARDS_REASON = /cpu_fallback_reason/;
+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(
@@ -15,18 +32,45 @@ const source = readFileSync(
"utf8",
);
+// The wording and the warn-vs-success choice used to be written inline in
+// showAutoLoadSuccess, and this file matched them there by substring. Both now
+// live in loadFallbackNotice, which is the one definition the explicit-load path
+// shares, so the behaviour is asserted by calling it and the call site is
+// asserted only to delegate. Matching the inline form again would go red on a
+// refactor that changed nothing a user can see, and -- worse -- stay green if
+// only the explicit-load path kept the behaviour.
test("an auto-load that fell back to CPU warns instead of claiming plain success", () => {
+ const notice = loadFallbackNotice(
+ "Loaded Qwen3 (Q4_K_M)",
+ "vulkan_startup_crash",
+ null,
+ );
+ assert.equal(notice.degraded, true, "a CPU fallback is not a plain success");
+ assert.match(notice.title, ON_CPU_SUFFIX);
+ assert.match(notice.description ?? "", GPU_DISABLED);
+ assert.equal(notice.description, CPU_FALLBACK_MESSAGE);
+});
+
+test("a load with no fallback stays a plain success", () => {
+ const notice = loadFallbackNotice("Loaded Qwen3 (Q4_K_M)", null, null);
+ assert.equal(notice.degraded, false);
+ assert.equal(notice.title, "Loaded Qwen3 (Q4_K_M)");
+ assert.equal(notice.description, undefined);
+});
+
+test("the auto-load toast is driven by that verdict, not by its own copy of it", () => {
const start = source.indexOf("const showAutoLoadSuccess = (");
assert.ok(start >= 0, "showAutoLoadSuccess is no longer defined");
const helper = source.slice(start, source.indexOf("\n };", start));
- assert.match(helper, /cpuFallbackReason \? toast\.warning : toast\.success/);
- assert.match(helper, /GPU acceleration is disabled for this model session/);
+ assert.match(helper, DELEGATES);
+ assert.match(helper, PICKS_WARNING);
+ assert.match(helper, PASSES_DESCRIPTION);
});
test("every auto-load path forwards the load response's fallback reason", () => {
- const calls = source.match(/\n\s*showAutoLoadSuccess\([\s\S]*?\);/g) ?? [];
+ const calls = source.match(CALL_SITES) ?? [];
assert.ok(calls.length > 0, "no showAutoLoadSuccess call sites found");
for (const call of calls) {
- assert.match(call, /cpu_fallback_reason/);
+ assert.match(call, FORWARDS_REASON);
}
});
diff --git a/studio/frontend/tests/fork-count-batching.test.ts b/studio/frontend/tests/fork-count-batching.test.ts
index 4d7f0eef103..0d3eae6aed7 100644
--- a/studio/frontend/tests/fork-count-batching.test.ts
+++ b/studio/frontend/tests/fork-count-batching.test.ts
@@ -10,6 +10,9 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test, { mock } from "node:test";
+// The real one, not a stub: what counts as a local thread is the rule under test,
+// and a hand-written copy of the prefix here could drift from the app's.
+import { isAssistantLocalThreadId } from "../src/features/chat/utils/thread-ids.ts";
import { loadWithStubs } from "./helpers/module-stubs.ts";
const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";
@@ -59,6 +62,7 @@ function freshStore(counts: Record<string, number> = {}): {
return new Map(Object.entries(counts));
},
},
+ "./thread-ids": { isAssistantLocalThreadId },
},
);
return { store, requests };
@@ -82,7 +86,10 @@ test("a 200-message thread costs one request, not one per message", async () =>
assert.deepEqual(requests, ["thread-a"]);
assert.equal(historyListenerCount(), 1);
// Every badge sees the count the single request brought back.
- assert.equal(seen.every((count) => count === 3), true);
+ assert.equal(
+ seen.every((count) => count === 3),
+ true,
+ );
assert.equal(store.forkCountFor("thread-a", "m7"), 3);
assert.equal(store.forkCountFor("thread-a", "m8"), 0);
@@ -135,7 +142,11 @@ test("badges churning under the hover autohide do not refetch the thread", async
badge();
}
await flush();
- assert.equal(requests.length, 1, "hovering ten messages refetched the whole thread");
+ assert.equal(
+ requests.length,
+ 1,
+ "hovering ten messages refetched the whole thread",
+ );
// Closing the thread is what drops the counts.
thread();
@@ -161,7 +172,10 @@ test("the badge no longer owns a listener or a per-message request", () => {
assert.doesNotMatch(thread, /addEventListener\(CHAT_HISTORY_UPDATED_EVENT/);
assert.match(thread, /subscribeForkCounts\(remoteId, onChange\)/);
// The badges all unmount at rest, so the thread has to hold the subscription itself.
- assert.match(thread, /const useThreadForkCounts[\s\S]*?subscribeForkCounts\(remoteId,/);
+ assert.match(
+ thread,
+ /const useThreadForkCounts[\s\S]*?subscribeForkCounts\(remoteId,/,
+ );
assert.match(thread, /^ {2}useThreadForkCounts\(\);$/m);
});
@@ -193,8 +207,12 @@ test("a continuous stream costs one refresh per ceiling, not one per debounce wi
}
const streamMs = chunks * gap;
const midStream = requests.length - 1;
- const throttleWould = Math.floor(streamMs / store.FORK_COUNT_REFRESH_DEBOUNCE_MS);
- const ceilingAllows = Math.floor(streamMs / store.FORK_COUNT_REFRESH_MAX_WAIT_MS);
+ const throttleWould = Math.floor(
+ streamMs / store.FORK_COUNT_REFRESH_DEBOUNCE_MS,
+ );
+ const ceilingAllows = Math.floor(
+ streamMs / store.FORK_COUNT_REFRESH_MAX_WAIT_MS,
+ );
assert.equal(
midStream,
ceilingAllows,
@@ -324,7 +342,11 @@ test("unsubscribing cancels the ceiling as well as the trailing edge", async (t)
const second = store.subscribeForkCounts("thread-b", () => {});
await flush();
- assert.deepEqual(requests, ["thread-a", "thread-b"], "the new thread fetches once on subscribe");
+ assert.deepEqual(
+ requests,
+ ["thread-a", "thread-b"],
+ "the new thread fetches once on subscribe",
+ );
mock.timers.tick(store.FORK_COUNT_REFRESH_MAX_WAIT_MS * 2);
await flush();
@@ -335,3 +357,58 @@ test("unsubscribing cancels the ceiling as well as the trailing edge", async (t)
);
second();
});
+
+test("a local thread never asks the server for forks it cannot have", async (t) => {
+ // #8992 added this store; it did not exclude threads the server has never seen.
+ // A `__LOCALID_` thread has no server record, so the request can only 404, and
+ // getThreadForkCounts maps 404 to the empty map the entry already holds.
+ //
+ // It is not a rounding error. A new chat is in exactly this state, and this store
+ // refreshes on CHAT_HISTORY_UPDATED_EVENT, which fires once per streaming chunk --
+ // so the first reply in a new chat paid one useless request per debounce window
+ // for as long as it streamed. The heavy-thread smoke, which counts requests issued
+ // inside a measured interaction, is what caught it.
+ mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => mock.timers.reset());
+ const { store, requests } = freshStore({ m1: 2 });
+
+ const unsubscribe = store.subscribeForkCounts("__LOCALID_abc123", () => {});
+ await flush();
+ assert.deepEqual(
+ requests,
+ [],
+ "subscribing to a local thread must not fetch",
+ );
+
+ for (let i = 0; i < 20; i++) fireHistoryUpdated();
+ mock.timers.tick(store.FORK_COUNT_REFRESH_MAX_WAIT_MS);
+ await flush();
+ assert.deepEqual(requests, [], "nor must a burst of history events");
+
+ // The badge still reads, it just reads the empty answer without asking.
+ assert.equal(store.forkCountFor("__LOCALID_abc123", "m1"), 0);
+ unsubscribe();
+});
+
+test("a saved thread alongside a local one still refreshes", async (t) => {
+ // The guard must be per thread, not a global off switch: the local thread is the
+ // one being composed, and a saved thread is on screen next to it.
+ mock.timers.enable({ apis: ["setTimeout"] });
+ t.after(() => mock.timers.reset());
+ const { store, requests } = freshStore({ m1: 2 });
+
+ const stop = [
+ store.subscribeForkCounts("__LOCALID_abc123", () => {}),
+ store.subscribeForkCounts("thread-saved", () => {}),
+ ];
+ await flush();
+ assert.deepEqual(requests, ["thread-saved"]);
+
+ fireHistoryUpdated();
+ mock.timers.tick(store.FORK_COUNT_REFRESH_DEBOUNCE_MS);
+ await flush();
+ assert.deepEqual(requests, ["thread-saved", "thread-saved"]);
+ assert.equal(store.forkCountFor("thread-saved", "m1"), 2);
+
+ for (const unsubscribe of stop) unsubscribe();
+});
diff --git a/studio/frontend/tests/mmproj-fallback.test.ts b/studio/frontend/tests/mmproj-fallback.test.ts
index 351f73b0d1b..d356ca2b27f 100644
--- a/studio/frontend/tests/mmproj-fallback.test.ts
+++ b/studio/frontend/tests/mmproj-fallback.test.ts
@@ -9,8 +9,13 @@ registerBundlerResolver();
const { getImageInputUnavailableReason } = await import(
"../src/features/chat/utils/image-input-support.ts"
);
-const { isTextOnlyMmprojFallback, mmprojFallbackMessage, mmprojLoadNotice } =
- await import("../src/features/chat/utils/mmproj-fallback.ts");
+const {
+ isTextOnlyMmprojFallback,
+ mmprojFallbackMessage,
+ mmprojLoadNotice,
+ loadFallbackNotice,
+ CPU_FALLBACK_MESSAGE,
+} = await import("../src/features/chat/utils/mmproj-fallback.ts");
const IMAGE_INPUT_AVAILABLE = /Image input remains available/;
const RELOADED_TEXT_ONLY = /reloaded this model in text-only mode/;
@@ -115,3 +120,69 @@ test("attachment and send gates forward projector fallback state", () => {
);
assert.match(interactiveLoad, /force_reload:\s*forceReload/);
});
+
+// The combination neither load path handled. Both wrote
+// `mmproj ? mmprojMessage : cpu ? cpuMessage : undefined`, so a session that lost GPU
+// acceleration AND vision reported only the vision loss, and the user was never told
+// the model was running on the CPU.
+//
+// Reachable rather than theoretical: on a CPU-fallback replay llama_cpp.py preserves
+// _cpu_fallback_reason and clears _mmproj_fallback_reason, so the projector can fail
+// again inside that same launch. A low-VRAM box whose Vulkan backend crashed is
+// precisely where both happen.
+
+test("a load that lost both the GPU and the projector reports both", () => {
+ const notice = loadFallbackNotice(
+ "PaddleOCR loaded",
+ "vulkan_startup_crash",
+ "projector_startup_failure",
+ );
+ assert.equal(notice.title, "PaddleOCR loaded on CPU, without vision");
+ assert.match(notice.description ?? "", /GPU acceleration is disabled/);
+ assert.match(notice.description ?? "", /text-only mode/);
+ assert.equal(notice.degraded, true);
+});
+
+test("a CPU-offloaded projector under a CPU fallback does not claim vision is accelerated", () => {
+ const notice = loadFallbackNotice(
+ "PaddleOCR loaded",
+ "vulkan_startup_crash",
+ "cpu_offload",
+ );
+ // "on CPU" already covers the projector, so the title does not also say
+ // "with vision on CPU" -- but the description must still explain both.
+ assert.equal(notice.title, "PaddleOCR loaded on CPU");
+ assert.match(notice.description ?? "", /GPU acceleration is disabled/);
+ assert.match(notice.description ?? "", /Image input remains available/);
+ assert.equal(notice.degraded, true);
+});
+
+test("each fallback alone still reads exactly as it did before", () => {
+ const cpuOnly = loadFallbackNotice("X loaded", "vulkan_startup_crash", null);
+ assert.equal(cpuOnly.title, "X loaded on CPU");
+ assert.equal(cpuOnly.description, CPU_FALLBACK_MESSAGE);
+
+ const offload = loadFallbackNotice("X loaded", null, "cpu_offload");
+ assert.equal(offload.title, "X loaded with vision on CPU");
+ assert.equal(offload.description, mmprojFallbackMessage("cpu_offload"));
+ // The title the standalone helper produces, unchanged.
+ assert.equal(offload.title, mmprojLoadNotice("X", "cpu_offload").title);
+
+ const textOnly = loadFallbackNotice(
+ "X loaded",
+ null,
+ "projector_incompatible",
+ );
+ assert.equal(textOnly.title, "X loaded without vision");
+ assert.equal(
+ textOnly.description,
+ mmprojFallbackMessage("projector_incompatible"),
+ );
+});
+
+test("a clean load is not degraded and carries no description", () => {
+ const notice = loadFallbackNotice("X loaded", null, null);
+ assert.equal(notice.title, "X loaded");
+ assert.equal(notice.description, undefined);
+ assert.equal(notice.degraded, false);
+});
diff --git a/studio/frontend/tests/queued-model-capabilities.test.ts b/studio/frontend/tests/queued-model-capabilities.test.ts
index 7c413eab0c2..7132bbfeeb3 100644
--- a/studio/frontend/tests/queued-model-capabilities.test.ts
+++ b/studio/frontend/tests/queued-model-capabilities.test.ts
@@ -1,8 +1,21 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { getImageInputUnavailableReason } from "../src/features/chat/utils/image-input-support.ts";
-import { mergeQueuedModelCapabilities } from "../src/features/chat/utils/queued-model-capabilities.ts";
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+// image-input-support.ts imports ./mmproj-fallback without an extension, which is
+// what 2314 of the 2367 relative imports under src/ do -- vite and tsconfig's
+// "bundler" mode resolve it, the bare node loader does not. A static import here
+// resolves before any registration can run, so the module has to come in
+// dynamically, after the resolver is registered.
+registerBundlerResolver();
+
+const { getImageInputUnavailableReason } = await import(
+ "../src/features/chat/utils/image-input-support.ts"
+);
+const { mergeQueuedModelCapabilities } = await import(
+ "../src/features/chat/utils/queued-model-capabilities.ts"
+);
test("status capabilities synthesize an audio model missing from the catalog", () => {
assert.deepEqual(
diff --git a/tests/studio/playwright_heavy_thread.py b/tests/studio/playwright_heavy_thread.py
index 3fe72d3758b..a0e5e0d434f 100644
--- a/tests/studio/playwright_heavy_thread.py
+++ b/tests/studio/playwright_heavy_thread.py
@@ -1082,6 +1082,13 @@ def measure_cell(context, engine: str, size: int) -> dict:
# Cumulative over seeding and every action: a liveness check, not attributable to any one.
result["raf_callbacks"] = page.evaluate("window.__rafCount")
result["stray_api_requests"] = len(stray_requests)
+ # The URLs, not only how many. A count alone says an interaction paid for a
+ # round trip without saying which one, so the failure names a symptom and
+ # nothing else -- the reader has to bisect the frontend to learn what the
+ # harness already knew and threw away. Deduplicated and capped: the point is
+ # to name the endpoints, and a per-message request would otherwise print
+ # hundreds of copies of one line.
+ result["stray_api_urls"] = sorted(set(stray_requests))[:8]
# Answered inside the page by the smoke entry's allowlist. Reported rather than hidden:
# these cost no round trip, but they are real requests the app makes and the number
# should not vanish just because the harness declines to pay for them.
@@ -1628,9 +1635,12 @@ def harness_failures(results: dict, report: dict) -> list[str]:
# being timed, once per message. A warning storm is the same cost via the console
# channel. Both scale with content, so both would forge the curve.
if row["stray_api_requests"]:
+ urls = row.get("stray_api_urls") or []
+ named = ", ".join(urls) if urls else "(urls not recorded)"
failures.append(
f"{where} let {row['stray_api_requests']} /api/ requests reach the network "
- "during the measured actions; the timings include a round trip per request"
+ f"during the measured actions; the timings include a round trip per "
+ f"request. Endpoints: {named}"
)
# Console output from inside a timed region is serialised over the debugging channel,
# so a warning the app emits once per message would both cost time and grow like the
diff --git a/tests/studio/test_autoscroll_harness_contract.py b/tests/studio/test_autoscroll_harness_contract.py
index 8d966620056..630739e6838 100644
--- a/tests/studio/test_autoscroll_harness_contract.py
+++ b/tests/studio/test_autoscroll_harness_contract.py
@@ -12,6 +12,8 @@ than left to review.
import ast
import types
+
+import pytest
from pathlib import Path
@@ -19,6 +21,32 @@ ROOT = Path(__file__).resolve().parents[2]
STUDIO_TESTS = ROOT / "tests" / "studio"
+def _require_playwright_page():
+ """
+ Skip unless `from playwright.sync_api import Page` would actually work.
+
+ Two weaker guards were tried and both let this through. Checking the
+ top-level package passes because "playwright" resolves as a namespace
+ directory on the Repo tests (CPU) runner; checking "playwright.sync_api"
+ passes too, because that resolves as a namespace package as well. Only the
+ symbol the harnesses import is a real test of whether the import below can
+ succeed, so that is what is checked, and it is checked the way the harness
+ does it. The failure mode is a skip condition reported as
+
+ ImportError: cannot import name 'Page' from 'playwright.sync_api'
+ (unknown location)
+
+ on every branch, which costs an investigation each time it is seen.
+ """
+ sync_api = pytest.importorskip("playwright.sync_api")
+ if not hasattr(sync_api, "Page"):
+ pytest.skip(
+ "playwright.sync_api resolved from "
+ f"{getattr(sync_api, '__file__', None) or list(getattr(sync_api, '__path__', []))} "
+ "but has no Page; playwright is not usably installed here"
+ )
+
+
def source(name: str) -> str:
return (STUDIO_TESTS / name).read_text(encoding = "utf-8")
@@ -108,7 +136,7 @@ def test_the_ansi_dump_survives_a_vite_server_that_is_still_talking(tmp_path, mo
import pytest
- pytest.importorskip("playwright")
+ _require_playwright_page()
monkeypatch.setenv("PW_ART_DIR", str(tmp_path / "art"))
spec = importlib.util.spec_from_file_location(
"_ansi_smoke_under_test", STUDIO_TESTS / "playwright_strip_ansi_smoke.py"
@@ -264,7 +292,7 @@ def test_thread_weight_row_shapes_stay_distinct() -> None:
sys.path.insert(0, str(STUDIO_TESTS))
pytest = importlib.import_module("pytest")
- pytest.importorskip("playwright")
+ _require_playwright_page()
module = importlib.import_module("playwright_thread_weight")
assert all(len(row) == 2 for row in module.TABLE_ROWS)
assert all(len(row) == 3 for row in module.GROWTH_AXES)
@@ -355,7 +383,7 @@ def test_thread_weight_rejects_a_dead_delete_at_every_size() -> None:
sys.path.insert(0, str(STUDIO_TESTS))
pytest = importlib.import_module("pytest")
- pytest.importorskip("playwright")
+ _require_playwright_page()
module = importlib.import_module("playwright_thread_weight")
sizes = [10, 50]
diff --git a/tests/studio/test_chat_autoload_failure_gate.py b/tests/studio/test_chat_autoload_failure_gate.py
index bf37451783f..b95f555ef04 100644
--- a/tests/studio/test_chat_autoload_failure_gate.py
+++ b/tests/studio/test_chat_autoload_failure_gate.py
@@ -176,6 +176,31 @@ function mlxRuntimeStateFrom(resp: any) {
mlxKvQuantNote: resp.mlx_kv_quant_note ?? null,
};
}
+// Imported by chat-adapter.ts from ../utils/mmproj-fallback, and used by the auto-load
+// success toast to say how a load was degraded. Without a stub it is a bare
+// ReferenceError inside the retry loop, which scores as a failed load and fails every
+// scenario as a wrong-model assertion -- the exact shape the guard below exists to
+// catch, and the third time it has happened (see #7699).
+//
+// Mirrors the real composition rather than returning a fixed string: these scenarios do
+// not assert on toast copy, but a stub that ignored its arguments would let a call site
+// stop passing one of the two reasons without anything here noticing, which is the bug
+// this helper was introduced to fix. The exact wording lives in mmproj-fallback.ts and
+// is tested in studio/frontend/tests/mmproj-fallback.test.ts.
+function loadFallbackNotice(
+ baseTitle: string,
+ cpuFallbackReason: any,
+ mmprojFallbackReason: any,
+) {
+ const parts: string[] = [];
+ if (cpuFallbackReason) parts.push(`cpu:${cpuFallbackReason}`);
+ if (mmprojFallbackReason) parts.push(`mmproj:${mmprojFallbackReason}`);
+ return {
+ title: parts.length > 0 ? `${baseTitle} (${parts.join(", ")})` : baseTitle,
+ description: parts.length > 0 ? parts.join(" ") : undefined,
+ degraded: parts.length > 0,
+ };
+}
async function prepareHfTokenForUse(token: any) {
EVENTS.push({ kind: "prepareHfToken" });
if (SCENARIO.tokenDecision === "decline") return { proceed: false, token };
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 7670f363899..bc80f861762 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -167,13 +167,41 @@ def test_chat_autoload_toast_is_persistent_and_dismissible():
assert "onDismiss:" in auto_load
# Terminal success uses a fresh finite toast after manual progress dismissal.
assert "showAutoLoadSuccess" in auto_load
- # No description on the ordinary path. It stopped being the literal
- # `description: undefined` when the CPU-fallback branch was added, so pin the
- # branch and its undefined arm rather than one spelling of the old constant.
+ # How a degraded load is described belongs to one helper, not to this call site.
+ #
+ # This assertion has moved three times: it was `description: undefined`, then
+ # `description: cpuFallbackReason` when the CPU-fallback branch appeared, then the
+ # mmproj branch went in front of that. Each rewrite pinned a fresh spelling of an
+ # inline conditional, and the third one shipped a real bug that no spelling-based
+ # check could have caught: `mmproj ? ... : cpu ? ...` drops the CPU message when
+ # both are set, so a session that lost GPU acceleration AND vision reported only
+ # the vision loss.
+ #
+ # So this no longer describes the conditional at all. It requires the call site to
+ # delegate, and the composition itself is tested where it lives, in
+ # studio/frontend/tests/mmproj-fallback.test.ts, against both reasons together.
+ # Sliced to the end of the helper body, not to the first `};`. That earlier bound
+ # stopped at the `options` object literal, so anything declared after it -- the
+ # toast severity, which is the half that decides whether a degraded load looks
+ # like a plain success -- was silently outside the text being asserted on.
success_toast = auto_load.split("const showAutoLoadSuccess", 1)[1]
- success_toast = success_toast.split("};", 1)[0]
- assert "description: cpuFallbackReason" in success_toast
- assert ": undefined," in success_toast
+ success_toast = success_toast.split("if (autoLoadToastDismissed)", 1)[0]
+ assert "loadFallbackNotice(" in success_toast, (
+ "the auto-load success toast no longer builds its notice through "
+ "loadFallbackNotice. Inlining the conditional here is how the CPU-fallback "
+ "message got dropped when the mmproj branch was added.\n" + success_toast
+ )
+ assert "description: notice.description" in success_toast, success_toast
+ assert "notice.degraded ? toast.warning : toast.success" in success_toast, (
+ "a degraded load must not raise a plain success toast:\n" + success_toast
+ )
+ # And the reasons still reach the helper, or it composes nothing.
+ call = success_toast.split("loadFallbackNotice(", 1)[1].split(");", 1)[0]
+ for reason in ("cpuFallbackReason", "mmprojFallbackReason"):
+ assert reason in call, (
+ f"{reason} is no longer passed to loadFallbackNotice, so that half of the "
+ f"degradation is invisible:\n{call}"
+ )
assert "icon: undefined" in auto_load
assert "duration: 5000" in auto_load
assert "duration: 30000" not in auto_load
diff --git a/tests/studio/test_playwright_server_lifecycle.py b/tests/studio/test_playwright_server_lifecycle.py
index 62293eaa992..fabd06241b2 100644
--- a/tests/studio/test_playwright_server_lifecycle.py
+++ b/tests/studio/test_playwright_server_lifecycle.py
@@ -87,6 +87,32 @@ def test_start_vite_picks_the_platform_process_group(monkeypatch, no_signals, os
assert "creationflags" not in captured["kw"]
+def _require_playwright_page():
+ """
+ Skip unless `from playwright.sync_api import Page` would actually work.
+
+ Two weaker guards were tried and both let this through. Checking the
+ top-level package passes because "playwright" resolves as a namespace
+ directory on the Repo tests (CPU) runner; checking "playwright.sync_api"
+ passes too, because that resolves as a namespace package as well. Only the
+ symbol the harnesses import is a real test of whether the import below can
+ succeed, so that is what is checked, and it is checked the way the harness
+ does it. The failure mode is a skip condition reported as
+
+ ImportError: cannot import name 'Page' from 'playwright.sync_api'
+ (unknown location)
+
+ on every branch, which costs an investigation each time it is seen.
+ """
+ sync_api = pytest.importorskip("playwright.sync_api")
+ if not hasattr(sync_api, "Page"):
+ pytest.skip(
+ "playwright.sync_api resolved from "
+ f"{getattr(sync_api, '__file__', None) or list(getattr(sync_api, '__path__', []))} "
+ "but has no Page; playwright is not usably installed here"
+ )
+
+
def test_posix_teardown_signals_the_group_and_escalates(monkeypatch, posix_branch) -> None:
sent = []
monkeypatch.setattr(
@@ -168,7 +194,7 @@ def test_every_harness_picks_a_different_default_port() -> None:
def test_an_empty_smoke_base_url_means_unset(harness, monkeypatch) -> None:
"""Exported-but-empty is common in shell wrappers. `in os.environ` would call it external
and then drive "" as the base URL."""
- pytest.importorskip("playwright") # importing a harness pulls in playwright.sync_api
+ _require_playwright_page()
import importlib
monkeypatch.setenv("SMOKE_BASE_URL", "")
@@ -184,7 +210,7 @@ def test_an_empty_smoke_base_url_means_unset(harness, monkeypatch) -> None:
def test_an_external_smoke_base_url_is_still_honoured(harness, monkeypatch) -> None:
"""The documented pre-existing invocation. A harness that started its own server anyway
would fail on the busy-port check."""
- pytest.importorskip("playwright")
+ _require_playwright_page()
import importlib
monkeypatch.setenv("SMOKE_BASE_URL", "http://127.0.0.1:9999")