Skip to content

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

Studio: confirm an Audio model swap instead of dead-ending on the backend 409 (#9092)

Michael Han489caae23f9b
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index cff6afb32c1..06d25b84427 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -42,11 +42,15 @@ import { usePlatformStore } from "@/config/env";
import {
type InferenceStatusResponse,
ParamSlider,
+ cancelPreStreamRunReservations,
+ confirmStopRunningChatsIfNeeded,
getInferenceStatus,
listGgufVariants,
listLoras,
loadModel,
+ requestLocalPromptQueueStop,
unloadModel,
+ useChatRuntimeStore,
} from "@/features/chat";
import {
SttModelNotDownloadedError,
@@ -695,6 +699,39 @@ export function AudioPage({ active = true }: { active?: boolean }) {
pendingRoutedTtsPick.current = { repoId, ggufFilename, loadId };
return;
}
+ // A load stops every chat on the shared llama-server, so ask the way Chat does
+ // instead of dead-ending on the backend's 409. Claimed before the await: a routed
+ // pick arriving while the dialog is open must queue, not start a second load.
+ ttsLoadInFlight.current = true;
+ // Chat's gate, held across the question and the load. Without it a queue can
+ // materialize while the dialog is open, outside the snapshot the answer was given
+ // for, and a generation started in that window brings the 409 back.
+ const lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();
+ if (lifecycleLease === null) {
+ ttsLoadInFlight.current = false;
+ pendingRoutedTtsPick.current = null;
+ toast.info("Wait for the current model to finish loading.");
+ return;
+ }
+ const releaseLifecycle = () =>
+ useChatRuntimeStore.getState().endModelLoading(lifecycleLease);
+ const stopDecision = await confirmStopRunningChatsIfNeeded();
+ if (!stopDecision.proceed) {
+ releaseLifecycle();
+ ttsLoadInFlight.current = false;
+ // Declining refuses the swap, so a queued pick must not reopen the dialog.
+ pendingRoutedTtsPick.current = null;
+ return;
+ }
+ // The page can go away while the dialog is open. pendingTtsLoad is still null then,
+ // so the deactivation effect has nothing to abort and a hidden load would replace
+ // the model the now-visible page is using. Queue it for the activation replay.
+ if (!activeRef.current) {
+ releaseLifecycle();
+ ttsLoadInFlight.current = false;
+ pendingRoutedTtsPick.current = { repoId, ggufFilename, loadId };
+ return;
+ }
const generation = ++ttsLoadGeneration.current;
const controller = new AbortController();
const loadRequestId = crypto.randomUUID();
@@ -722,6 +759,7 @@ export function AudioPage({ active = true }: { active?: boolean }) {
{
model_path: loadId || repoId,
load_request_id: loadRequestId,
+ force_cancel_active: stopDecision.forceCancelActive,
hf_token: hfApiToken(getHfToken()) ?? null,
max_seq_length: TTS_MAX_TOKENS + TTS_PROMPT_CONTEXT_RESERVE,
load_in_4bit: false,
@@ -732,6 +770,13 @@ export function AudioPage({ active = true }: { active?: boolean }) {
signal: controller.signal,
onRequestStart: () => {
pending.requestStarted = true;
+ // Queued prompts would otherwise start on the model this load replaces.
+ // Only once /load is actually going out: loadModel returns without sending
+ // when a stored token is invalid and the user picks replace or dismisses
+ // the warning, and cancelling earlier threw away accepted sends and queued
+ // prompts for a swap that never happened.
+ cancelPreStreamRunReservations(stopDecision.preStreamRunTokens);
+ requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds);
},
},
);
@@ -758,6 +803,8 @@ export function AudioPage({ active = true }: { active?: boolean }) {
if (pendingTtsLoad.current?.generation === generation)
pendingTtsLoad.current = null;
ttsLoadInFlight.current = false;
+ // Before the replay below, which needs the gate for its own attempt.
+ releaseLifecycle();
busyRef.current = null;
setBusy(null);
if (activeRef.current) void refreshStatus();
@@ -1322,27 +1369,56 @@ export function AudioPage({ active = true }: { active?: boolean }) {
const activeModel = status?.active_model;
if (!activeModel) return;
- // An old managed completion must not immediately replace the model the
- // user just ejected. The global download may continue for later use.
- invalidatePendingStagedTts();
- stageTtsDownload([]);
+ // Chat's gate, taken before the question so a queue cannot materialize while the
+ // dialog is open and then be stopped by the blanket queue stop below.
+ const lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();
+ if (lifecycleLease === null) {
+ toast.info("Wait for the current model to finish loading.");
+ return;
+ }
+ // Busy before the dialog, so a second eject cannot start behind the first.
setBusy("unloading");
- const toastId = toast.loading("Unloading model…");
void (async () => {
try {
- // Non-forced unload is deliberate: the backend refuses rather than
- // killing an active Chat or API generation owned by another surface.
- await unloadModel({ model_path: activeModel });
- await refreshStatus();
- toast.success("Model unloaded", { id: toastId, duration: 1200 });
- } catch (error) {
- toast.error(
- error instanceof Error ? error.message : "Failed to unload model.",
- { id: toastId },
+ // Ejecting stops every chat on the shared llama-server. Unforced, the backend
+ // refused with a 409 the user could only read. Nothing is torn down until the
+ // answer is in, so declining leaves the page as it was.
+ const stopDecision = await confirmStopRunningChatsIfNeeded(
+ "Unloading the model",
+ "unload",
);
+ if (!stopDecision.proceed) {
+ setBusy(null);
+ return;
+ }
+
+ // An old managed completion must not immediately replace the model the
+ // user just ejected. The global download may continue for later use.
+ invalidatePendingStagedTts();
+ stageTtsDownload([]);
+
+ const toastId = toast.loading("Unloading model…");
+ try {
+ cancelPreStreamRunReservations(stopDecision.preStreamRunTokens);
+ requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds);
+ await unloadModel({
+ model_path: activeModel,
+ force_cancel_active: stopDecision.forceCancelActive,
+ });
+ requestLocalPromptQueueStop();
+ await refreshStatus();
+ toast.success("Model unloaded", { id: toastId, duration: 1200 });
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Failed to unload model.",
+ { id: toastId },
+ );
+ } finally {
+ setBusy(null);
+ }
} finally {
- setBusy(null);
+ useChatRuntimeStore.getState().endModelLoading(lifecycleLease);
}
})();
}, [
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 70cf8522c5d..4c4f01f48f2 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -112,6 +112,7 @@ export {
} from "./utils/prompt-queue-boundary";
export {
adoptPreStreamRunReservation,
+ cancelPreStreamRunReservations,
findPreStreamRunReservation,
hasPreStreamRunReservation,
preStreamRunThreadIdsForAdapter,
@@ -120,6 +121,11 @@ export {
releasePreStreamRunReservation,
reservePreStreamRun,
} from "./utils/pre-stream-run-reservation";
+// Audio swaps the same llama-server Chat decodes on, so it needs the same confirmation.
+export {
+ confirmStopRunningChatsIfNeeded,
+ type StopRunningChatsDecision,
+} from "./utils/confirm-stop-running-chats";
export {
promptQueueActiveItemChanged,
reorderPromptQueueItems,
diff --git a/studio/frontend/tests/audio-model-eject.test.ts b/studio/frontend/tests/audio-model-eject.test.ts
index 7094169cdd7..89d2e4024c3 100644
--- a/studio/frontend/tests/audio-model-eject.test.ts
+++ b/studio/frontend/tests/audio-model-eject.test.ts
@@ -32,7 +32,7 @@ test("Audio exposes the shared picker eject action only while idle", () => {
test("Speak eject unloads the live main model and cancels stale auto-load", () => {
assert.match(
source,
- /const activeModel = status\?\.active_model;[\s\S]*unloadModel\(\{ model_path: activeModel \}\)/,
+ /const activeModel = status\?\.active_model;[\s\S]*unloadModel\(\{\s*model_path: activeModel,\s*force_cancel_active: stopDecision\.forceCancelActive,\s*\}\)/,
);
assert.match(
source,
@@ -41,6 +41,98 @@ test("Speak eject unloads the live main model and cancels stale auto-load", () =
assert.match(source, /await unloadModel[\s\S]*await refreshStatus\(\)/);
});
+test("Speak eject asks about running chats before tearing anything down", () => {
+ // Unforced, the backend refused with a 409 the page could only print as a toast.
+ assert.match(
+ source,
+ /const activeModel = status\?\.active_model;[\s\S]*confirmStopRunningChatsIfNeeded\(\s*"Unloading the model",\s*"unload",\s*\)/,
+ );
+ // Declining leaves the page as it was: the staged download dies only past the check.
+ assert.match(
+ source,
+ /if \(!stopDecision\.proceed\) \{\s*setBusy\(null\);\s*return;\s*\}\s*\n\s*\/\/ An old managed completion[\s\S]*invalidatePendingStagedTts\(\);/,
+ );
+ // Queues would otherwise start a fresh run on the model this eject removes.
+ assert.match(
+ source,
+ /cancelPreStreamRunReservations\(stopDecision\.preStreamRunTokens\);\s*requestLocalPromptQueueStop\(stopDecision\.promptQueueThreadIds\);\s*await unloadModel/,
+ );
+});
+
+test("a Speak load asks the same question and forces from the answer", () => {
+ assert.match(
+ source,
+ /const stopDecision = await confirmStopRunningChatsIfNeeded\(\);/,
+ );
+ // The slot is claimed before the await, so a routed pick arriving mid-dialog queues.
+ assert.match(
+ source,
+ /if \(ttsLoadInFlight\.current\) \{\s*pendingRoutedTtsPick\.current = \{ repoId, ggufFilename, loadId \};\s*return;\s*\}[\s\S]{0,400}?ttsLoadInFlight\.current = true;/,
+ );
+ // Declining releases the slot and drops the queued pick, which would else re-ask.
+ assert.match(
+ source,
+ /if \(!stopDecision\.proceed\) \{\s*releaseLifecycle\(\);\s*ttsLoadInFlight\.current = false;[\s\S]*?pendingRoutedTtsPick\.current = null;\s*return;\s*\}/,
+ );
+ assert.match(
+ source,
+ /load_request_id: loadRequestId,\s*force_cancel_active: stopDecision\.forceCancelActive,/,
+ );
+});
+
+test("a Speak load stops local queues only once /load is going out", () => {
+ // loadModel prepares the stored HF token first and returns without sending when the
+ // token is invalid and the user picks replace or dismisses the warning. Cancelling
+ // before that call discarded accepted sends and queued prompts for a swap that never
+ // happened, leaving the old model resident and the work gone.
+ assert.match(
+ source,
+ /onRequestStart: \(\) => \{\s*pending\.requestStarted = true;[\s\S]{0,700}?cancelPreStreamRunReservations\(stopDecision\.preStreamRunTokens\);\s*requestLocalPromptQueueStop\(stopDecision\.promptQueueThreadIds\);\s*\},/,
+ );
+ assert.doesNotMatch(
+ source,
+ /cancelPreStreamRunReservations\(stopDecision\.preStreamRunTokens\);\s*requestLocalPromptQueueStop\(stopDecision\.promptQueueThreadIds\);\s*const res = await loadModel\(/,
+ );
+});
+
+test("a model swap holds Chat's lifecycle gate across the question", () => {
+ // Without the gate a queue can materialize while the dialog is open, so it is missing
+ // from the snapshot the answer was given for: the eject's blanket queue stop then hits
+ // work nobody confirmed stopping, and a load started in that window 409s again.
+ assert.match(
+ source,
+ /ttsLoadInFlight\.current = true;[\s\S]{0,400}?const lifecycleLease = useChatRuntimeStore\.getState\(\)\.beginModelLoading\(\);\s*if \(lifecycleLease === null\) \{[\s\S]*?return;\s*\}[\s\S]{0,200}?const stopDecision = await confirmStopRunningChatsIfNeeded\(\);/,
+ );
+ // Released before the queued replay, which needs the gate for its own attempt.
+ assert.match(
+ source,
+ /ttsLoadInFlight\.current = false;[\s\S]{0,120}?releaseLifecycle\(\);[\s\S]*?replayQueuedTtsPick\(\);/,
+ );
+ // Eject takes it before it goes busy, so it is held across its own question too.
+ assert.match(
+ source,
+ /const lifecycleLease = useChatRuntimeStore\.getState\(\)\.beginModelLoading\(\);[\s\S]{0,300}?setBusy\("unloading"\);[\s\S]{0,400}?confirmStopRunningChatsIfNeeded\(\s*"Unloading the model",/,
+ );
+ assert.match(
+ source,
+ /\} finally \{\s*useChatRuntimeStore\.getState\(\)\.endModelLoading\(lifecycleLease\);\s*\}/,
+ );
+});
+
+test("a load confirmed after Audio is hidden is deferred, not sent", () => {
+ // pendingTtsLoad is still null while the dialog is open, so the deactivation effect has
+ // nothing to abort. Sending anyway let a hidden page replace the visible page's model.
+ assert.match(
+ source,
+ /if \(!activeRef\.current\) \{\s*releaseLifecycle\(\);\s*ttsLoadInFlight\.current = false;\s*pendingRoutedTtsPick\.current = \{ repoId, ggufFilename, loadId \};\s*return;\s*\}/,
+ );
+ // The activation effect replays exactly that queue, so the pick is not lost.
+ assert.match(
+ source,
+ /if \(!active\) \{[\s\S]*?\n \}\s*\n\s*\/\/[\s\S]*?replayQueuedTtsPick\(\);/,
+ );
+});
+
test("Transcribe eject only unloads a sidecar owned by the current selection", () => {
assert.match(
source,