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.

49.4 KB
Raw Blame
// 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 assert from "node:assert/strict";
import test from "node:test";

import {
  MINIMAX_MUSIC_DEFAULT_SECONDS,
  MINIMAX_MUSIC_FRAMES_PER_SECOND,
  MINIMAX_MUSIC_MAX_FRAMES,
  MINIMAX_MUSIC_MAX_SECONDS,
  audioEjectAvailable,
  audioGenerationPresentation,
  audioModelToReplace,
  canTransitionAudioMode,
  describeAudioSlot,
  exactGgufLoadSelector,
  expectedGgufDownloadBytes,
  fetchGalleryWindow,
  isGgufTtsTarget,
  isTtsAudioType,
  macTtsPickAction,
  mergeGalleryPage,
  minimaxMusicFramesForSeconds,
  nativeAudioInstructionsKind,
  persistedClipForGeneration,
  reconcileSttSelection,
  resolveSttLoadedModel,
  resolveSttResidency,
  selectAutoGgufVariant,
  settledDeleteMarkers,
  stagedTtsLoadIsOwned,
  sttEjectSucceeded,
  sttSelectionReady,
  audioLoadedSelection,
  deleteCoversRememberedModel,
  rememberedModelIsGone,
  rememberedModelUnavailable,
} from "../src/features/audio/audio-page-policy.ts";
import {
  sttEngineForRepoId,
  sttRepoIdForSidecarKey,
  sttSidecarKeyFor,
} from "../src/features/audio/stt-artifacts.ts";

import { readSrc } from "./helpers/kit.ts";
import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";

const audioPageSource = readAudioWorkspaceSource();
const audioSourceCard = readSrc("features/audio/hooks/use-audio-source.ts");
const audioSourceInput = readSrc("features/audio/components/audio-source-input.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);
  assert.equal(canTransitionAudioMode("generating", "generating"), true);
  assert.equal(canTransitionAudioMode("generating", "preparing"), false);
  assert.equal(canTransitionAudioMode("generating", "stopping"), false);
  assert.equal(canTransitionAudioMode("generating", "finishing"), false);
  assert.equal(canTransitionAudioMode("loading"), false);
  assert.equal(canTransitionAudioMode("unloading"), false);
  assert.equal(canTransitionAudioMode("transcribing"), false);
});

test("audio generation phases expose truthful indeterminate presentation", () => {
  assert.equal(audioGenerationPresentation(null), null);
  assert.deepEqual(audioGenerationPresentation("preparing"), {
    status: "Preparing audio…",
    actionLabel: "Preparing…",
    canStop: false,
  });
  assert.deepEqual(audioGenerationPresentation("generating"), {
    status: "Generating audio…",
    actionLabel: "Stop",
    canStop: true,
  });
  assert.deepEqual(audioGenerationPresentation("stopping"), {
    status: "Stopping audio…",
    actionLabel: "Stopping…",
    canStop: false,
  });
  assert.deepEqual(audioGenerationPresentation("finishing"), {
    status: "Finishing audio…",
    actionLabel: "Finishing…",
    canStop: false,
  });

  for (const phase of [
    "preparing",
    "generating",
    "stopping",
    "finishing",
  ] as const) {
    const presentation = audioGenerationPresentation(phase);
    assert.ok(presentation);
    assert.doesNotMatch(
      `${presentation.status} ${presentation.actionLabel}`,
      /%|percent|eta|remaining/i,
    );
  }
});

test("staged TTS completion requires the same Speak ownership generation", () => {
  assert.equal(stagedTtsLoadIsOwned(4, 4, "speak"), true);
  assert.equal(stagedTtsLoadIsOwned(4, 5, "speak"), false);
  assert.equal(stagedTtsLoadIsOwned(4, 4, "transcribe"), false);
  assert.equal(stagedTtsLoadIsOwned(null, 4, "speak"), false);
});

test("cached GGUF quant labels remain exact when no filename is present", () => {
  assert.equal(exactGgufLoadSelector({ ggufVariant: "Q4_K_M" }), "Q4_K_M");
  assert.equal(
    exactGgufLoadSelector({
      ggufVariant: "Q4_K_M",
      ggufFilename: "model-q4_k_m.gguf",
    }),
    "model-q4_k_m.gguf",
  );
});

test("TTS load context matches the advertised generation ceiling", () => {
  assert.match(audioPageSource, /const TTS_MAX_TOKENS = 8192/);
  assert.match(audioPageSource, /max_seq_length: TTS_MAX_TOKENS/);
  assert.match(audioPageSource, /label="Max tokens"[\s\S]*max=\{TTS_MAX_TOKENS\}/);
});

test("MiniMax duration converts seconds to the official frame budget", () => {
  assert.equal(MINIMAX_MUSIC_FRAMES_PER_SECOND, 25);
  assert.equal(MINIMAX_MUSIC_DEFAULT_SECONDS, 30);
  assert.equal(MINIMAX_MUSIC_MAX_FRAMES, 9000);
  assert.equal(MINIMAX_MUSIC_MAX_SECONDS, 360);
  assert.equal(
    minimaxMusicFramesForSeconds(MINIMAX_MUSIC_DEFAULT_SECONDS),
    750,
  );
  assert.equal(minimaxMusicFramesForSeconds(1.99), 49);
  assert.equal(minimaxMusicFramesForSeconds(1.16), 29);
  assert.equal(minimaxMusicFramesForSeconds(360), 9000);
  assert.equal(minimaxMusicFramesForSeconds(999), 9000);
  assert.equal(minimaxMusicFramesForSeconds(0), 1);
  for (let frames = 1; frames <= MINIMAX_MUSIC_MAX_FRAMES; frames += 1) {
    assert.equal(
      minimaxMusicFramesForSeconds(frames / MINIMAX_MUSIC_FRAMES_PER_SECOND),
      frames,
    );
  }
});

test("native audio instruction fields match the runtime payload contract", () => {
  assert.equal(nativeAudioInstructionsKind("higgs_tts2"), "scene");
  assert.equal(nativeAudioInstructionsKind("moss_tts_local"), "style");
  assert.equal(nativeAudioInstructionsKind("minimax_music3"), "music");
  assert.equal(nativeAudioInstructionsKind("higgs_tts3"), null);
  assert.equal(nativeAudioInstructionsKind("moss_tts_nano"), null);
  assert.equal(nativeAudioInstructionsKind(null), null);
});

test("Audio sends model-specific duration and instruction payloads", () => {
  assert.match(
    audioPageSource,
    /musicGeneration\s*\? minimaxMusicFramesForSeconds\(musicSeconds\)/,
  );
  assert.match(audioPageSource, /max=\{musicRange\.max\}/);
  assert.match(
    audioPageSource,
    /instructionsKind !== null && instructions[\s\S]*audio_instructions: instructions/,
  );
  assert.match(audioPageSource, /\? "Scene description"/);
});

test("Mac rejects safetensors-only TTS and redirects sibling families", () => {
  assert.equal(
    macTtsPickAction({ isMac: true, isGguf: false, ggufSibling: null }),
    "reject",
  );
  assert.equal(
    macTtsPickAction({
      isMac: true,
      isGguf: false,
      ggufSibling: "org/model-GGUF",
    }),
    "use-gguf-sibling",
  );
  assert.equal(
    macTtsPickAction({ isMac: true, isGguf: true, ggufSibling: null }),
    "allow",
  );
});

test("Mac sibling resolution returns an exact managed-download file", () => {
  const variants = [
    {
      filename: "model-q4.gguf",
      quant: "Q4_K_M",
      size_bytes: 4_000,
      download_size_bytes: 3_500,
      downloaded: false,
    },
    {
      filename: "model-q8.gguf",
      quant: "Q8_0",
      size_bytes: 8_000,
      downloaded: true,
    },
  ];
  const cached = selectAutoGgufVariant(variants, "Q4_K_M");
  assert.equal(cached?.filename, "model-q8.gguf");

  const remote = selectAutoGgufVariant(
    variants.map((variant) => ({ ...variant, downloaded: false })),
    "Q4_K_M",
  );
  assert.equal(remote?.filename, "model-q4.gguf");
  assert.equal(remote && expectedGgufDownloadBytes(remote), 3_500);
});

test("only the generation's persisted gallery id is selected", () => {
  const refreshed = [{ id: "other-client" }, { id: "ours" }];
  assert.deepEqual(persistedClipForGeneration("ours", refreshed), {
    id: "ours",
  });
  assert.equal(persistedClipForGeneration(null, refreshed), null);
  assert.equal(persistedClipForGeneration("missing", refreshed), null);
});

test("Speak requires a supported TTS codec, not any audio model", () => {
  for (const codec of ["snac", "csm", "bicodec", "dac"])
    assert.equal(isTtsAudioType(codec), true);
  assert.equal(isTtsAudioType("csm", true), false);
  for (const codec of ["snac", "bicodec", "dac"])
    assert.equal(isTtsAudioType(codec, true), true);
  for (const codec of ["whisper", "audio_vlm", "", null])
    assert.equal(isTtsAudioType(codec), false);
});

test("STT controls require the selected sidecar to be resident", () => {
  const keyFor = (repo: string) => (repo === "org/asr" ? "asr" : repo);
  assert.equal(sttSelectionReady("org/asr", "asr", keyFor), true);
  assert.equal(sttSelectionReady("org/asr", null, keyFor), false);
  assert.equal(sttSelectionReady("org/asr", "other", keyFor), false);
  assert.equal(
    sttSelectionReady("org/asr", "asr", keyFor, "transformers", "gguf"),
    false,
  );
});

test("STT activation adopts resident sidecars and preserves only pending selections", () => {
  const sidecarKeyFor = (repo: string) =>
    repo === "org/asr-a" ? "asr-a" : repo === "org/asr-b" ? "asr-b" : repo;
  const repoIdForSidecarKey = (key: string) =>
    key === "asr-a" ? "org/asr-a" : key === "asr-b" ? "org/asr-b" : key;

  assert.equal(
    reconcileSttSelection({
      selectedRepo: null,
      loadedModel: "asr-b",
      preservePending: false,
      sidecarKeyFor,
      repoIdForSidecarKey,
    }),
    "org/asr-b",
  );
  assert.equal(
    reconcileSttSelection({
      selectedRepo: "org/asr-a",
      loadedModel: "asr-b",
      preservePending: false,
      sidecarKeyFor,
      repoIdForSidecarKey,
    }),
    "org/asr-b",
  );
  assert.equal(
    reconcileSttSelection({
      selectedRepo: "org/asr-a",
      loadedModel: null,
      preservePending: true,
      sidecarKeyFor,
      repoIdForSidecarKey,
    }),
    "org/asr-a",
  );
  assert.equal(
    reconcileSttSelection({
      selectedRepo: "org/asr-a",
      loadedModel: null,
      preservePending: false,
      sidecarKeyFor,
      repoIdForSidecarKey,
    }),
    null,
  );

  assert.equal(
    reconcileSttSelection({
      selectedRepo: "unsloth/whisper-small",
      loadedModel: "small",
      loadedEngine: "gguf",
      preservePending: false,
      sidecarKeyFor: () => "small",
      repoIdForSidecarKey: (_key, engine) =>
        engine === "gguf"
          ? "unslothai/whisper-small-GGUF"
          : "unsloth/whisper-small",
      engineForRepo: (repo) =>
        repo.endsWith("-GGUF") ? "gguf" : "transformers",
    }),
    "unslothai/whisper-small-GGUF",
  );
});

test("STT residency reads the selected engine instead of Transformers-only legacy fields", () => {
  const qwenStatus = {
    loaded_model: null,
    loading: false,
    transformers: { loaded_model: null, loading: false },
    gguf: { loaded_model: null, loading: false },
    mtmd: { loaded_model: "qwen3-asr-0.6b", loading: false },
  };
  assert.equal(
    resolveSttLoadedModel(qwenStatus, "mtmd", false),
    "qwen3-asr-0.6b",
  );

  const whisperStatus = {
    ...qwenStatus,
    mtmd: { loaded_model: null, loading: false },
    gguf: { loaded_model: "small", loading: false },
  };
  assert.equal(resolveSttLoadedModel(whisperStatus, null, false), "small");
  assert.deepEqual(resolveSttResidency(whisperStatus, "gguf", false), {
    model: "small",
    engine: "gguf",
  });
});

test("a pending engine selection is not replaced by an older resident sidecar", () => {
  const status = {
    loaded_model: "small",
    loading: false,
    transformers: { loaded_model: "small", loading: false },
    mtmd: { loaded_model: null, loading: false },
  };
  assert.equal(resolveSttLoadedModel(status, "mtmd", true), null);
  assert.equal(resolveSttLoadedModel(status, "mtmd", false), "small");
});

test("MediaRecorder setup failures release the acquired microphone stream", () => {
  assert.match(
    audioSourceCard,
    /recorder = createAudioRecorder\(stream\);\s*\} catch \{\s*stopStream\(\);/,
  );
});

test("leaving Audio clears an unresolved microphone permission wait", () => {
  assert.match(
    audioSourceCard,
    /\(\) => \(\) => \{\s*abortAll\(\);\s*for \(const track of streamRef\.current\?\.getTracks\(\) \?\? \[\]\) track\.stop\(\);/,
  );
});

test("routed picks wait in the URL until Audio is idle", () => {
  assert.match(
    audioPageSource,
    /if \(busyRef\.current !== null\) return;[\s\S]*handledRouteModel\.current = key;[\s\S]*handleModelSelect\(wanted/,
  );
  assert.match(audioPageSource, /\[\s*active,\s*busy,/);
});

test("picking a file cannot overlap a recording on the same card", () => {
  assert.match(audioSourceInput, /disabled=\{disabled \|\| recording\}/);
});

test("gallery refresh preserves fallback selection and pagination identity", () => {
  assert.match(
    audioPageSource,
    /const generation = \+\+galleryRefreshGeneration\.current;[\s\S]*listAudioGallery\(\s*0,[\s\S]*if \(generation !== galleryRefreshGeneration\.current\) return/,
  );
  assert.match(
    audioPageSource,
    /!fallbackClipRef\.current[\s\S]*merged\.length > 0/,
  );
  assert.match(
    audioPageSource,
    /listAudioGallery\([\s\S]*galleryCache\.nextCursor[\s\S]*galleryCache\.nextCursor = audioGalleryCursor\(page\)[\s\S]*new Set\(galleryCache\.clips\.map[\s\S]*filter\(\(clip\) => !known\.has\(clip\.id\)\)/,
  );
});

test("a refresh that overlaps a pin or move is dropped and rerun after it", () => {
  assert.match(
    audioPageSource,
    /const writeEpoch = orderWrites\.current\.epoch;[\s\S]*listAudioGallery\(\s*0,[\s\S]*orderWrites\.current\.inFlight > 0 \|\| orderWrites\.current\.epoch !== writeEpoch[\s\S]*orderWrites\.current\.deferred = true;\s*return page\.audio;/,
  );
  assert.match(
    audioPageSource,
    /writes\.inFlight === 0 && writes\.deferred\) \{\s*writes\.deferred = false;\s*void refreshGallery\(/,
  );
  assert.match(
    audioPageSource,
    /setAudioClipFlags\(id, \{ pinned \}\)\);\s*\/\/[^\n]*\n\s*if \(!pinned && galleryCache\.hasMore\) orderWrites\.current\.deferred = true;/,
  );
  for (const call of ["setAudioClipFlags(id, { pinned })", "moveAudioClip(id, afterId)"]) {
    const at = audioPageSource.indexOf(call);
    const before = audioPageSource.lastIndexOf("beginOrderWrite();", at);
    const after = audioPageSource.indexOf("endOrderWrite();", at);
    assert.ok(before > 0 && at - before < 400 && after > at, call);
  }
});

test("older STT status requests cannot overwrite newer residency", () => {
  assert.match(
    audioPageSource,
    /const generation = \+\+sttStatusRefreshGeneration\.current;[\s\S]*await fetchSttStatus[\s\S]*generation !== sttStatusRefreshGeneration\.current\) return;[\s\S]*catch \{[\s\S]*generation !== sttStatusRefreshGeneration\.current\) return;/,
  );
});

test("older TTS status requests cannot overwrite newer residency", () => {
  assert.match(
    audioPageSource,
    /const generation = \+\+ttsStatusRefreshGeneration\.current;[\s\S]*await getInferenceStatus\(\)[\s\S]*generation !== ttsStatusRefreshGeneration\.current\) return;[\s\S]*catch \{[\s\S]*generation !== ttsStatusRefreshGeneration\.current\) return;/,
  );
});

test("leaving Audio cancels an owned TTS load without touching a pre-request prompt", () => {
  assert.match(
    audioPageSource,
    /const loadRequestId = crypto\.randomUUID\(\);[\s\S]*load_request_id: loadRequestId/,
  );
  assert.match(
    audioPageSource,
    // Cancel under the target actually sent: a pinned directory does not map back from the display id.
    /const pending = pendingTtsLoad\.current;[\s\S]*pending\.controller\.abort\(\);[\s\S]*if \(pending\.requestStarted\)[\s\S]*unloadModel\(\{[\s\S]*model_path: pending\.loadTarget,[\s\S]*cancel_load_request_id: pending\.loadRequestId/,
  );
  assert.match(
    chatApiSource,
    /if \(options\?\.signal\?\.aborted\)[\s\S]*options\?\.onRequestStart\?\.\(\);[\s\S]*authFetch\("\/api\/inference\/load", \{[\s\S]*signal: options\?\.signal/,
  );
});

test("history-only downloads save the fetched blob without caching a URL", () => {
  assert.match(
    audioPageSource,
    /handleDownloadClipById[\s\S]*saveAudio\(\s*clipFileName\(clip\),\s*null,\s*\(\) => fetchClipBlob\(clip\.url\),/,
  );
  assert.doesNotMatch(
    audioPageSource,
    /handleDownloadClipById[\s\S]{0,500}galleryCache\.srcById\.set/,
  );
});

test("a gallery refresh keeps the loaded scrollback instead of collapsing it", () => {
  const page = [{ id: "e" }, { id: "d" }, { id: "c" }];
  const cached = [
    { id: "d" },
    { id: "c" },
    { id: "b" },
    { id: "a" },
  ];

  assert.deepEqual(mergeGalleryPage(page, cached), {
    clips: [{ id: "e" }, { id: "d" }, { id: "c" }, { id: "b" }, { id: "a" }],
    stitched: true,
  });
});

test("a clip this client deleted leaves the merged gallery", () => {
  const merged = mergeGalleryPage(
    [{ id: "c" }, { id: "a" }],
    [{ id: "b" }, { id: "a" }],
    "b",
  );
  assert.deepEqual(merged.clips, [{ id: "c" }, { id: "a" }]);
});

test("the selection only moves when its clip left the merged gallery", () => {
  assert.match(
    audioPageSource,
    /const \{ clips: merged, stitched \} =[\s\S]*mergeGalleryPage\([\s\S]*!merged\.some\(\(c\) => c\.id === galleryCache\.selectedId\)/,
  );
  assert.doesNotMatch(
    audioPageSource,
    /galleryCache\.clips = page\.audio/,
  );
});

test("a superseded refresh still reports the clips its own fetch saw", () => {
  assert.match(
    audioPageSource,
    /if \(generation !== galleryRefreshGeneration\.current\) return page\.audio;/,
  );
  assert.match(
    audioPageSource,
    /const refreshed = await refreshGallery\(\);[\s\S]*persistedClipForGeneration\(\s*generated\.clip_id,\s*refreshed,/,
  );
});

test("keeping the scrollback keeps the deeper pagination cursor", () => {
  assert.match(
    audioPageSource,
    /if \(!stitched\) \{[\s\S]*galleryCache\.hasMore = page\.has_more;[\s\S]*galleryCache\.nextCursor =/,
  );
  assert.match(audioPageSource, /setHasMore\(galleryCache\.hasMore\);/);
});

test("a cache with nothing in common with the page is dropped, not stitched", () => {
  const merged = mergeGalleryPage(
    [{ id: "z" }, { id: "y" }],
    [{ id: "c" }, { id: "b" }],
  );
  assert.deepEqual(merged, { clips: [{ id: "z" }, { id: "y" }], stitched: false });
});

test("a refresh resets when an external archive moves the page boundary", () => {
  const cached = Array.from({ length: 50 }, (_, i) => ({ id: `c${i}` }));
  const page = [...cached.slice(0, 5), ...cached.slice(6), { id: "c50" }];
  assert.deepEqual(mergeGalleryPage(page, cached, undefined, true), {
    clips: page,
    stitched: false,
  });
});

test("Record is offered only where the browser can capture audio", () => {
  // Safari has no MediaRecorder, and an http LAN origin has no navigator.mediaDevices.
  assert.match(
    audioSourceCard,
    /typeof navigator\.mediaDevices\?\.getUserMedia === "function"/,
  );
  assert.match(
    audioSourceInput,
    /\.\.\.\(recordingSupported\(\) \? \[\{ value: "record", label: "Record" \}\] : \[\]\)/,
  );
  assert.match(audioPageSource, /<AudioSourceInput/);
});

test("a Transcribe recording is stopped at the 30 minute limit the inputs route accepts", () => {
  // 30 minutes of 16 kHz PCM is ~58 MB, under the backend cap's 200 MB floor.
  assert.match(audioPageSource, /const RECORDING_MAX_SECONDS = 30 \* 60;/);
  assert.match(audioPageSource, /maxRecordSeconds=\{RECORDING_MAX_SECONDS\}/);
  assert.match(
    audioSourceCard,
    /window\.setTimeout\(\(\) => \{\s*if \(recorder\.state !== "inactive"\) recorder\.stop\(\);\s*\}, maxRecordSeconds \* 1000\);/,
  );
  assert.match(audioSourceCard, /window\.clearTimeout\(limit\);/);
});

test("the trained-model list applies the native-aware macOS policy", () => {
  assert.match(
    audioPageSource,
    /!isMac \|\|\s*trainedTtsCheckpointIsRunnableOnMac\(\s*lora\.audio_type,\s*lora\.export_type,?\s*\)/,
  );
});

test("the transcript download revokes its URL only after the click is consumed", () => {
  assert.match(readSrc("features/audio/transcript-download.ts"), /await downloadFile\(\s*text,/);
  assert.match(readSrc("lib/native-files.ts"), /anchor\.click\(\);[\s\S]*?window\.setTimeout\(\(\) => URL\.revokeObjectURL\(url\), 0\);/);
});

test("a complete first page drops cached rows the server no longer holds", () => {
  const merged = mergeGalleryPage(
    [{ id: "c" }, { id: "b" }],
    [{ id: "c" }, { id: "b" }, { id: "a" }],
    undefined,
    false,
  );
  assert.deepEqual(merged, { clips: [{ id: "c" }, { id: "b" }], stitched: false });

  const stitched = mergeGalleryPage(
    [{ id: "c" }, { id: "b" }],
    [{ id: "c" }, { id: "b" }, { id: "a" }],
    undefined,
    true,
  );
  assert.deepEqual(stitched.clips, [{ id: "c" }, { id: "b" }, { id: "a" }]);
  assert.equal(stitched.stitched, true);
});

test("the refresh passes the page's completeness into the merge", () => {
  assert.match(
    audioPageSource,
    /mergeGalleryPage\(\s*page\.audio,\s*galleryCache\.clips,\s*removedId,\s*page\.has_more,/,
  );
});

test("generating waits for the transcribe release the mode switch started", () => {
  assert.match(
    audioPageSource,
    /const handleGenerate = useCallback\(async \(\) => \{[\s\S]{0,1100}?const releaseInFlight = pendingTranscribeRelease\.current;[\s\S]{0,240}?if \(releaseInFlight && !\(await releaseInFlight\)\) \{[\s\S]{0,160}?setMode\("transcribe"\);/,
  );
});

test("a failed transcribe release puts the page back in Transcribe", () => {
  assert.match(
    audioPageSource,
    /void release\.then\(\(released\) => \{[\s\S]{0,600}?if \(!released && modeRef\.current === "speak"\) setMode\("transcribe"\);/,
  );
});

test("a gguf selection served by Transformers still reads as resident", () => {
  // Without whisper-server the backend loads the Transformers model, so residency is in that block.
  const status = {
    transformers: { loaded_model: "small", available: true },
    gguf: { loaded_model: null, available: false },
  };
  assert.deepEqual(resolveSttResidency(status, "gguf", true), {
    model: "small",
    engine: "gguf",
  });
  assert.equal(resolveSttLoadedModel(status, "gguf", true), "small");

  const live = {
    transformers: { loaded_model: "small", available: true },
    gguf: { loaded_model: "base", available: true },
  };
  assert.deepEqual(resolveSttResidency(live, "gguf", true), {
    model: "base",
    engine: "gguf",
  });
  assert.equal(resolveSttResidency({ gguf: { loaded_model: null } }, "gguf", true), null);
});

test("generation is claimed before the transcribe release is awaited", () => {
  assert.match(
    audioPageSource,
    /if \(busyRef\.current\) return;\s*busyRef\.current = "generating";\s*setBusy\("generating"\);\s*updateGenerationPhase\("preparing"\);\s*const releaseInFlight = pendingTranscribeRelease\.current;\s*if \(releaseInFlight/,
  );
  assert.match(
    audioPageSource,
    /if \(releaseInFlight && !\(await releaseInFlight\)\) \{\s*updateGenerationPhase\(null\);\s*busyRef\.current = null;\s*setBusy\(null\);\s*setMode\("transcribe"\);/,
  );
});

test("a restore refreshes the loaded window, not just the first page", () => {
  const shelf = Array.from({ length: 120 }, (_, i) => ({ id: `c${i}` }));
  const loaded = shelf.slice(0, 100);
  const restored = { id: "restored" };
  const afterRestore = [...shelf.slice(0, 70), restored, ...shelf.slice(70)];

  const firstPageOnly = mergeGalleryPage(afterRestore.slice(0, 50), loaded, undefined, true);
  assert.equal(
    firstPageOnly.clips.some((clip) => clip.id === "restored"),
    false,
  );

  const wholeWindow = mergeGalleryPage(
    afterRestore.slice(0, loaded.length),
    loaded,
    undefined,
    true,
  );
  assert.equal(
    wholeWindow.clips.some((clip) => clip.id === "restored"),
    true,
  );
  assert.deepEqual(wholeWindow.clips, [...afterRestore.slice(0, 100), shelf[99]]);
});

test("the gallery-changed subscription asks for the window that is loaded", () => {
  assert.match(
    audioPageSource,
    /subscribeGalleryChanged\("audio", \(\) => \{\s*void refreshGallery\(undefined, galleryCache\.clips\.length\);/,
  );
  assert.match(
    audioPageSource,
    /const wanted = Math\.max\(PAGE_SIZE, windowSize\);[\s\S]*?fetchGalleryWindow\([\s\S]*?wanted,\s*MAX_PAGE_SIZE,/,
  );
});

test("reactivating audio asks for the window that is loaded", () => {
  assert.match(
    audioPageSource,
    /if \(initialReadySent\.current\) \{\s*void refreshStatus\(\);\s*void refreshSttStatus\(\);\s*void refreshGallery\(undefined, galleryCache\.clips\.length\);\s*return;\s*\}/,
  );
});

test("returning to a visible audio tab refreshes the loaded window", () => {
  assert.match(
    audioPageSource,
    /const refreshWhenVisible = \(\) => \{\s*if \(document\.hidden\) return;\s*void refreshGallery\(undefined, galleryCache\.clips\.length\);\s*\};\s*window\.addEventListener\("focus", refreshWhenVisible\);\s*document\.addEventListener\("visibilitychange", refreshWhenVisible\);/,
  );
  assert.match(
    audioPageSource,
    /window\.removeEventListener\("focus", refreshWhenVisible\);\s*document\.removeEventListener\("visibilitychange", refreshWhenVisible\);/,
  );
});

type WindowClip = { id: string };
type WindowPage = { audio: WindowClip[]; has_more: boolean; next: number | null };
function windowShelf(size: number) {
  const shelf = Array.from({ length: size }, (_, n) => ({ id: `c${n}` }));
  const calls: { limit: number; cursor: number | null }[] = [];
  const fetchPage = async (limit: number, cursor: number | null): Promise<WindowPage> => {
    calls.push({ limit, cursor });
    const from = cursor ?? 0;
    const audio = shelf.slice(from, from + limit);
    const end = from + audio.length;
    return { audio, has_more: end < shelf.length, next: end < shelf.length ? end : null };
  };
  return { shelf, calls, fetchPage };
}

test("a window past the route cap is fetched in capped pages, not cut to the first one", async () => {
  const { shelf, calls, fetchPage } = windowShelf(303);
  const page = await fetchGalleryWindow(fetchPage, (p) => p.next, 250, 200);
  assert.deepEqual(calls, [{ limit: 200, cursor: null }, { limit: 50, cursor: 200 }]);
  assert.deepEqual(page.audio.map((c) => c.id), shelf.slice(0, 250).map((c) => c.id));
  assert.equal(page.has_more, true);
  assert.equal(page.next, 250);
});

test("a window fetch stops when the server runs out or the refresh is superseded", async () => {
  const short = windowShelf(230);
  const page = await fetchGalleryWindow(short.fetchPage, (p) => p.next, 400, 200);
  assert.equal(page.audio.length, 230);
  assert.equal(page.has_more, false);
  assert.equal(short.calls.length, 2);

  const one = windowShelf(30);
  const small = await fetchGalleryWindow(one.fetchPage, (p) => p.next, 50, 200);
  assert.equal(small.audio.length, 30);
  assert.equal(one.calls.length, 1);

  const big = windowShelf(600);
  const stopped = await fetchGalleryWindow(big.fetchPage, (p) => p.next, 500, 200, () => true);
  assert.equal(big.calls.length, 1);
  assert.equal(stopped.audio.length, 200);
});

test("the gallery refresh fetches its whole window before merging", () => {
  assert.match(
    audioPageSource,
    /const page = await fetchGalleryWindow\([\s\S]*?\);[\s\S]*?const \{ clips: merged, stitched \} = mergeGalleryPage\(\s*page\.audio,/,
  );
  assert.doesNotMatch(audioPageSource, /wanted > asked/);
});

test("a capped restore refresh invalidates a page fetched from the older cursor", () => {
  assert.match(
    audioPageSource,
    /const cursor = galleryCache\.nextCursor;\s*try\s*{\s*const page = await listAudioGallery\(\s*0,\s*PAGE_SIZE,\s*cursor,?\s*\);\s*if \(\s*refreshGeneration !== galleryRefreshGeneration\.current \|\|\s*cursor !== galleryCache\.nextCursor\s*\)\s*return;/,
  );
});

test("a direct .gguf pick is a GGUF target even without a variant filename", () => {
  assert.equal(
    isGgufTtsTarget({ repoId: "/models/orpheus-3b-Q4_K_M.gguf" }),
    true,
  );
  assert.equal(
    isGgufTtsTarget({ repoId: "Orpheus TTS", loadId: "/m/x.GGUF" }),
    true,
  );
  assert.equal(isGgufTtsTarget({ repoId: "unsloth/orpheus-3b-0.1-ft-GGUF" }), true);
  assert.equal(
    isGgufTtsTarget({ repoId: "unsloth/orpheus", ggufFilename: "x-Q4.gguf" }),
    true,
  );
});

test("the catalog's own answer outranks the name heuristics", () => {
  assert.equal(
    isGgufTtsTarget({ repoId: "acme/voicebox", isGguf: true }),
    true,
  );
  assert.equal(
    isGgufTtsTarget({ repoId: "acme/voicebox-GGUF", isGguf: false }),
    true,
  );
  assert.equal(
    isGgufTtsTarget({ repoId: "acme/voicebox", isGguf: null }),
    false,
  );
});

test("a safetensors pick is not a GGUF target", () => {
  assert.equal(isGgufTtsTarget({ repoId: "unsloth/orpheus-3b-0.1-ft" }), false);
  assert.equal(isGgufTtsTarget({ repoId: "bosonai/higgs-tts-2-3b-base" }), false);
  assert.equal(isGgufTtsTarget({ repoId: "acme/ggufology" }), false);
});

test("a CPU GGUF audio load declares speculation off", () => {
  // An absent speculative_type resolves to "auto", which can attach a GPU drafter.
  assert.match(
    audioPageSource,
    /gpu_memory_mode: "manual" as const,\s*gpu_layers: 0,\s*speculative_type: "off" as const,/,
  );
});

test("selecting CPU never ejects a resident MiniMax, which cannot load on CPU", () => {
  const handler = audioPageSource.slice(
    audioPageSource.indexOf('const next = value === "cpu" ? "cpu" : "auto";'),
  );
  const guard = handler.indexOf('status?.audio_type === "minimax_music3"');
  const eject = handler.indexOf("handleEject()");
  assert.ok(guard > -1, "no MiniMax guard on the placement control");
  assert.ok(guard < eject, "the guard must return before the eject");
  assert.match(handler.slice(guard, eject), /return;/);
});

test("history scrolling loads until the page gains a row, not one gallery page", () => {
  assert.match(audioPageSource, /loadMore: loadMoreVisible,/);
  assert.match(
    audioPageSource,
    /const loadMoreVisible = useCallback\(async \(\) => \{[\s\S]*?await loadGalleryUntil\(\{\s*has: \(\) => countVisible\(\) > before,/,
  );
});

test("paging for a visible row skips hidden edit originals, like the list does", () => {
  const gallery = readSrc("features/audio/hooks/use-audio-gallery.tsx");
  assert.match(
    gallery,
    /const countVisible = \(\) =>\s*galleryCache\.clips\.filter\(\s*\(clip\) => clipWorkflow\(clip\) === workflow && clip\.role !== "source",\s*\)\.length;/,
  );
});

test("trained speech checkpoints are offered only on Speak and Music", () => {
  const host = readSrc("features/audio/audio-page.tsx");
  assert.match(
    host,
    /ttsWorkflow !== "speak" && ttsWorkflow !== "music"\s*\?\s*\[\]\s*:\s*trainedTtsModels\.filter\(/,
  );
});

test("the audio picker marks the main slot's loaded model and quant, not the chat model", () => {
  assert.deepEqual(
    audioLoadedSelection({
      active_model: "audio-cpp/audio.cpp-gguf/Qwen3-TTS-12Hz-0.6B-Base-GGUF",
      model_identifier: "audio-cpp/audio.cpp-gguf/Qwen3-TTS-12Hz-0.6B-Base-GGUF",
      gguf_variant: "Q8_0",
    }),
    { id: "audio-cpp/audio.cpp-gguf/Qwen3-TTS-12Hz-0.6B-Base-GGUF", variant: "Q8_0" },
  );
  // llama-server names a custom-folder GGUF by its file stem; the picker row uses the path.
  assert.deepEqual(
    audioLoadedSelection({
      active_model: "orpheus-3b-q4_k_m",
      model_identifier: "/models/orpheus/orpheus-3b-q4_k_m.gguf",
      gguf_variant: "Q4_K_M",
    }),
    { id: "/models/orpheus/orpheus-3b-q4_k_m.gguf", variant: "Q4_K_M" },
  );
  // A Hub model loaded from a cache snapshot keeps the repo id its row uses.
  assert.deepEqual(
    audioLoadedSelection({
      active_model: "unsloth/orpheus-3b-0.1-ft-GGUF",
      model_identifier:
        "/data/hf/hub/models--unsloth--orpheus-3b-0.1-ft-GGUF/snapshots/abc123",
      gguf_variant: "Q4_K_M",
    }),
    { id: "unsloth/orpheus-3b-0.1-ft-GGUF", variant: "Q4_K_M" },
  );
  assert.deepEqual(audioLoadedSelection({ active_model: null, gguf_variant: "Q8_0" }), {
    id: null,
    variant: null,
  });
  assert.deepEqual(audioLoadedSelection(null), { id: null, variant: null });
  assert.match(audioPageSource, /const speakLoaded = audioLoadedSelection\(status, ggufQuantLabel\)/);
  assert.match(audioPageSource, /mode === "speak"\s*\? \(speakLoaded\.id \?\? ""\)/);
  assert.match(
    audioPageSource,
    /loadedGgufVariantOverride=\{\s*mode === "speak" \? speakLoaded\.variant : undefined\s*\}/,
  );
  assert.match(audioPageSource, /: \(speakLoaded\.id \?\? undefined\)/);
});

test("a deleted model is forgotten only once the settled inventory lacks it", () => {
  const available = new Set(["hexgrad/kokoro-82m", "audio-cpp/audio.cpp-gguf"]);
  const settled = { settled: true, error: false, available };
  assert.equal(rememberedModelIsGone("hexgrad/Kokoro-82M", settled), false);
  assert.equal(rememberedModelIsGone("unsloth/orpheus-3b-0.1-ft", settled), true);
  assert.equal(
    rememberedModelIsGone("unsloth/orpheus-3b-0.1-ft", { ...settled, settled: false }),
    false,
  );
  assert.equal(
    rememberedModelIsGone("unsloth/orpheus-3b-0.1-ft", { ...settled, error: true }),
    false,
  );
  // An inventory without folder rows cannot tell an audio.cpp folder is gone.
  const qwenTts = "audio-cpp/audio.cpp-gguf/Qwen3-TTS-12Hz-0.6B-Base-GGUF";
  assert.equal(rememberedModelIsGone(qwenTts, settled), false);
  const withFolders = new Set([...available, "audio-cpp/audio.cpp-gguf/kokoro-82m-gguf"]);
  assert.equal(rememberedModelIsGone(qwenTts, { ...settled, available: withFolders }), true);
  assert.equal(
    rememberedModelIsGone(qwenTts, {
      ...settled,
      available: new Set([...withFolders, qwenTts.toLowerCase()]),
    }),
    false,
  );
  // Only a delete puts a model up for forgetting, so a load racing the inventory keeps it.
  assert.match(
    audioPageSource,
    /subscribeModelDeleted\(\(repoId\) => \{\s*deletedModelsRef\.current\.set\(repoId\.toLowerCase\(\), Date\.now\(\)\);/,
  );
  assert.match(audioPageSource, /if \(rememberedModelIsGone\(id, inventory\)\) forgetModel\(id\);/);
});

test("a delete marker is spent once a settled listing fetched after the delete was judged", () => {
  // A kept package marker forgot a folder downloaded again later, before its listing arrived.
  const deletedAt = 1_000;
  const markers = new Map([["audio-cpp/audio.cpp-gguf", deletedAt]]);
  const settled = { settled: true, error: false };
  assert.deepEqual(settledDeleteMarkers(markers, { ...settled, refreshStartedAt: deletedAt - 1 }), []);
  assert.deepEqual(settledDeleteMarkers(markers, { ...settled, refreshStartedAt: null }), []);
  assert.deepEqual(
    settledDeleteMarkers(markers, { settled: false, error: false, refreshStartedAt: deletedAt + 1 }),
    [],
  );
  assert.deepEqual(
    settledDeleteMarkers(markers, { settled: true, error: true, refreshStartedAt: deletedAt + 1 }),
    [],
  );
  // A fetch sent in the delete's own millisecond may still have read the old cache.
  assert.deepEqual(settledDeleteMarkers(markers, { ...settled, refreshStartedAt: deletedAt }), []);
  assert.deepEqual(settledDeleteMarkers(markers, { ...settled, refreshStartedAt: deletedAt + 1 }), [
    "audio-cpp/audio.cpp-gguf",
  ]);
  assert.match(
    audioPageSource,
    /for \(const repoId of settledDeleteMarkers\(deleted, inventory\)\) \{\s*deleted\.delete\(repoId\);/,
  );
  assert.match(audioPageSource, /refreshStartedAt: modelInventory\.hubCacheRefreshStartedAt,/);
  assert.match(
    audioPageSource,
    /useHubInventory\(\{\s*kind: "models",\s*includeUmbrellaFolders: true,\s*\}\)/,
  );
});

function deleteForgetReplay(remembered: Record<string, string>, available: Set<string>) {
  const markers = new Map<string, number>();
  const forgotten: string[] = [];
  let now = 1_000;
  let listing = { available, refreshStartedAt: 0 as number | null };
  const effect = () => {
    const inventory = { settled: true, error: false, ...listing };
    for (const id of new Set(Object.values(remembered))) {
      if (![...markers.keys()].some((repoId) => deleteCoversRememberedModel(repoId, id))) continue;
      if (!rememberedModelIsGone(id, inventory)) continue;
      forgotten.push(id);
      for (const [workflow, value] of Object.entries(remembered)) {
        if (value === id) delete remembered[workflow];
      }
    }
    for (const repoId of settledDeleteMarkers(markers, inventory)) markers.delete(repoId);
  };
  return {
    forgotten,
    markers,
    remembered,
    deleteModel(repoId: string) {
      now += 10;
      markers.set(repoId.toLowerCase(), now);
      effect();
    },
    render(next: Set<string>, refresh: "local" | "hub-cache" | "stale-hub-cache") {
      now += 10;
      listing = {
        available: next,
        refreshStartedAt:
          refresh === "hub-cache"
            ? now
            : refresh === "stale-hub-cache"
              ? now - 100
              : listing.refreshStartedAt,
      };
      effect();
    },
  };
}

test("the local listing landing first keeps a delete marker until the Hub cache fetch lands", () => {
  const gguf = "unsloth/orpheus-3b-0.1-ft-GGUF";
  const local = "/models/other";
  const replay = deleteForgetReplay({ speak: gguf }, new Set([gguf.toLowerCase(), local]));
  replay.deleteModel(gguf);
  // localModels is not debounced, so its fresh rows land beside the old Hub cache rows.
  replay.render(new Set([gguf.toLowerCase(), local]), "local");
  assert.equal(replay.markers.size, 1);
  replay.render(new Set([local]), "hub-cache");
  assert.deepEqual(replay.forgotten, [gguf]);
  assert.equal(replay.markers.size, 0);
});

test("a Hub cache fetch sent before the delete does not spend its marker", () => {
  const pkg = "audio-cpp/audio.cpp-gguf";
  const folder = `${pkg}/Kokoro-82M-GGUF`;
  const replay = deleteForgetReplay({ speak: folder }, new Set([pkg, folder.toLowerCase()]));
  replay.deleteModel(pkg);
  replay.render(new Set([pkg, folder.toLowerCase()]), "stale-hub-cache");
  assert.equal(replay.markers.size, 1);
  replay.render(new Set(), "hub-cache");
  assert.deepEqual(replay.forgotten, [folder]);
});

test("deleting one audio.cpp folder forgets it while its package keeps other folders", () => {
  const pkg = "audio-cpp/audio.cpp-gguf";
  const kokoro = `${pkg}/Kokoro-82M-GGUF`;
  const qwen = `${pkg}/Qwen3-TTS-12Hz-0.6B-Base-GGUF`;
  const replay = deleteForgetReplay(
    { speak: kokoro, clone: qwen },
    new Set([pkg, kokoro.toLowerCase(), qwen.toLowerCase()]),
  );
  replay.deleteModel(kokoro);
  replay.render(new Set([pkg, qwen.toLowerCase()]), "hub-cache");
  assert.deepEqual(replay.forgotten, [kokoro]);
  assert.deepEqual(replay.remembered, { clone: qwen });
});

test("pages a loaded model cannot run point at the page it does run, not always Speak", () => {
  assert.doesNotMatch(audioPageSource, /label: "open Speak"/);
  assert.match(
    audioPageSource,
    /const loadedModelHome = workflowForLoadedModel\(\{\s*current: "speak",\s*audioWorkflows: status\?\.audio_workflows,/,
  );
  assert.equal(audioPageSource.match(/openLoadedModelHome,/g)?.length, 3);
});

test("a remembered Hub repo the inventory no longer lists is not offered, but kept", () => {
  const settled = { settled: true, error: false, available: new Set(["hexgrad/kokoro-82m"]) };
  assert.equal(rememberedModelUnavailable("hexgrad/Kokoro-82M", settled), false);
  // Deleted from the Hub while the Audio page was closed.
  assert.equal(rememberedModelUnavailable("unsloth/orpheus-3b-0.1-ft", settled), true);
  assert.equal(
    rememberedModelUnavailable("unsloth/orpheus-3b-0.1-ft", { ...settled, settled: false }),
    false,
  );
  // Trained checkpoints and local folders are not listed by repo id.
  assert.equal(rememberedModelUnavailable("/home/me/outputs/tts-checkpoint", settled), false);
  assert.equal(
    rememberedModelUnavailable("audio-cpp/audio.cpp-gguf/Qwen3-TTS-12Hz-0.6B-Base-GGUF", settled),
    false,
  );
  assert.match(
    audioPageSource,
    /rememberedPageModel &&\s*!rememberedModelUnavailable\(rememberedPageModel, \{/,
  );
});

test("deleting the audio.cpp package forgets the folders remembered from it", () => {
  const qwenTts = "audio-cpp/audio.cpp-gguf/Qwen3-TTS-12Hz-0.6B-Base-GGUF";
  assert.equal(deleteCoversRememberedModel("audio-cpp/audio.cpp-gguf", qwenTts), true);
  assert.equal(deleteCoversRememberedModel(qwenTts, qwenTts.toUpperCase()), true);
  assert.equal(deleteCoversRememberedModel("hexgrad/Kokoro-82M", "hexgrad/Kokoro-82M"), true);
  assert.equal(deleteCoversRememberedModel("hexgrad/Kokoro", "hexgrad/Kokoro-82M"), false);
  assert.equal(deleteCoversRememberedModel("audio-cpp/audio.cpp-gguf", "unsloth/orpheus"), false);
  const settled = { settled: true, error: false };
  // The package repo is gone, so is every folder in it.
  assert.equal(
    rememberedModelIsGone(qwenTts, { ...settled, available: new Set(["hexgrad/kokoro-82m"]) }),
    true,
  );
  assert.equal(
    rememberedModelIsGone(qwenTts, {
      ...settled,
      available: new Set(["audio-cpp/audio.cpp-gguf"]),
    }),
    false,
  );
  assert.match(
    audioPageSource,
    /\[\.\.\.deleted\.keys\(\)\]\.some\(\(repoId\) =>\s*deleteCoversRememberedModel\(repoId, id\),?\s*\)/,
  );
});


test("Eject is offered only for a resident Transcribe model, and never while loading or unloading", () => {
  const idle = { busy: null, hasValue: true, showLastPageModel: false } as const;
  assert.equal(audioEjectAvailable({ ...idle, mode: "transcribe", sttReady: true }), true);
  // After an unload the selector still shows the last model; Eject there released nothing.
  assert.equal(audioEjectAvailable({ ...idle, mode: "transcribe", sttReady: false }), false);
  assert.equal(audioEjectAvailable({ ...idle, mode: "speak", sttReady: false }), true);
  assert.equal(
    audioEjectAvailable({ ...idle, mode: "speak", sttReady: false, busy: "loading" }),
    false,
  );
  assert.equal(
    audioEjectAvailable({ ...idle, mode: "transcribe", sttReady: true, busy: "unloading" }),
    false,
  );
  assert.equal(
    audioEjectAvailable({ ...idle, mode: "speak", sttReady: false, busy: "generating" }),
    true,
  );
  assert.equal(
    audioEjectAvailable({ ...idle, mode: "transcribe", sttReady: true, busy: "transcribing" }),
    true,
  );
  assert.equal(
    audioEjectAvailable({ ...idle, mode: "speak", sttReady: false, hasValue: false }),
    false,
  );
  assert.equal(
    audioEjectAvailable({ ...idle, mode: "speak", sttReady: false, showLastPageModel: true }),
    false,
  );
});

test("a legacy dictation key or other casing still marks the Transcribe row ready", () => {
  const row = "audio-cpp/audio.cpp-gguf/Qwen3-ASR-0.6B-GGUF";
  const ready = (loaded: string, selected = row) =>
    sttSelectionReady(
      selected,
      loaded,
      sttSidecarKeyFor,
      "audiocpp",
      "audiocpp",
      sttRepoIdForSidecarKey,
    );
  assert.equal(ready("audiocpp-qwen3-asr-0.6b"), true);
  assert.equal(ready(row.toLowerCase()), true);
  assert.equal(ready(row), true);
  assert.equal(ready("audio-cpp/audio.cpp-gguf/Qwen3-ASR-1.7B-GGUF"), false);
  assert.equal(ready("audiocpp-qwen3-asr-1.7b"), false);
  // Without the mapping (older callers) only the exact key matches.
  assert.equal(
    sttSelectionReady(row, "audiocpp-qwen3-asr-0.6b", sttSidecarKeyFor, "audiocpp", "audiocpp"),
    false,
  );
  // An engine mismatch is still not ready.
  assert.equal(
    sttSelectionReady(
      row,
      "audiocpp-qwen3-asr-0.6b",
      sttSidecarKeyFor,
      "transformers",
      "audiocpp",
      sttRepoIdForSidecarKey,
    ),
    false,
  );
  // Reconcile keeps the picked row instead of swapping it for the legacy key's id.
  assert.equal(
    reconcileSttSelection({
      selectedRepo: row,
      loadedModel: "audiocpp-qwen3-asr-0.6b",
      loadedEngine: "audiocpp",
      preservePending: false,
      sidecarKeyFor: sttSidecarKeyFor,
      repoIdForSidecarKey: sttRepoIdForSidecarKey,
      engineForRepo: sttEngineForRepoId,
    }),
    row,
  );
});

test("a GGUF repo without a -GGUF suffix keeps the engine it was picked with", () => {
  const repo = "someorg/whisper-quant";
  // Re-derived from the id alone it resolves to Transformers, so it never showed ready.
  assert.equal(sttEngineForRepoId(repo), "transformers");
  const engines = new Map([[repo, sttEngineForRepoId(repo, true)]]);
  const engineFor = (id: string) => engines.get(id) ?? sttEngineForRepoId(id);
  assert.equal(engineFor(repo), "audiocpp");
  assert.equal(
    sttSelectionReady(repo, repo, sttSidecarKeyFor, engineFor(repo), "audiocpp"),
    true,
  );
  assert.equal(
    reconcileSttSelection({
      selectedRepo: repo,
      loadedModel: repo,
      loadedEngine: "audiocpp",
      preservePending: false,
      sidecarKeyFor: sttSidecarKeyFor,
      repoIdForSidecarKey: sttRepoIdForSidecarKey,
      engineForRepo: engineFor,
    }),
    repo,
  );
});

test("an eject counts as done unless the backend says it kept the model", () => {
  assert.equal(sttEjectSucceeded(true), true);
  assert.equal(sttEjectSucceeded(undefined), true);
  assert.equal(sttEjectSucceeded(false), false);
});

test("reconcile keeps the same repo id when only the resident engine changed", () => {
  // The hook therefore has to adopt the engine without waiting for the id to change.
  const repo = "someorg/whisper-quant";
  assert.equal(
    reconcileSttSelection({
      selectedRepo: repo,
      loadedModel: repo,
      loadedEngine: "audiocpp",
      preservePending: false,
      sidecarKeyFor: sttSidecarKeyFor,
      repoIdForSidecarKey: sttRepoIdForSidecarKey,
      engineForRepo: () => "transformers",
    }),
    repo,
  );
});

// The Audio page with a speech model loaded beside the chat model: it shows, generates with and
// ejects the speech model, never the chat model.
const chatPrimary = {
  active_model: "unsloth/Qwen3-1.7B-GGUF",
  model_identifier: "unsloth/Qwen3-1.7B-GGUF",
  gguf_variant: "UD-Q4_K_XL",
  is_audio: false,
  loading: [],
  loaded: ["unsloth/Qwen3-1.7B-GGUF"],
  serving: ["unsloth/Qwen3-1.7B-GGUF", "audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF"],
  serving_checkpoints: ["unsloth/Qwen3-1.7B-GGUF", ""],
} as unknown as import("../src/features/chat/types/api.ts").InferenceStatusResponse;
const kokoroSlot = {
  ...chatPrimary,
  active_model: "audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF",
  model_identifier: "audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF",
  is_audio: true,
  audio_type: "audiocpp_tts",
};

test("the Audio page finds its speech model beside the chat model", async () => {
  const probed: string[] = [];
  const view = await describeAudioSlot(chatPrimary, async (id) => {
    probed.push(id);
    return kokoroSlot;
  });
  assert.deepEqual(probed, ["audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF"]);
  assert.equal(view.status.active_model, "audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF");
  assert.equal(view.slotModel, "audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF");
});

test("a primary speech model is used as is, without probing", async () => {
  const view = await describeAudioSlot(kokoroSlot, async () => {
    throw new Error("must not probe");
  });
  assert.equal(view.status, kokoroSlot);
  assert.equal(view.slotModel, null);
});

test("with only the chat model loaded, the Audio page shows no model to eject", async () => {
  // An id not in a slot answers with the primary; a failed probe counts as nothing.
  for (const probe of [async () => chatPrimary, async () => Promise.reject(new Error("x"))]) {
    const view = await describeAudioSlot(chatPrimary, probe);
    assert.equal(view.status.active_model, null);
    assert.equal(view.status.is_audio, false);
    assert.equal(view.status.gguf_variant, null);
    assert.equal(view.slotModel, null);
    // The rest of the status (memory mode, serving list) stays.
    assert.deepEqual(view.status.serving, chatPrimary.serving);
  }
});

test("a new speech load replaces only another speech model", () => {
  assert.equal(audioModelToReplace(kokoroSlot, "pocket"), kokoroSlot.active_model);
  assert.equal(audioModelToReplace(kokoroSlot, kokoroSlot.active_model as string), null);
  assert.equal(audioModelToReplace(chatPrimary, "pocket"), null);
  assert.equal(audioModelToReplace(null, "pocket"), null);
});

test("a speech model kept after the chat model was ejected is still found", async () => {
  // A kept model is never promoted, so the primary is empty and only the slot serves.
  const emptyPrimary = {
    ...chatPrimary,
    active_model: null,
    model_identifier: null,
    gguf_variant: null,
    loaded: [],
    serving: ["audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF"],
    serving_checkpoints: [""],
  };
  const probed: string[] = [];
  const view = await describeAudioSlot(emptyPrimary, async (id) => {
    probed.push(id);
    return kokoroSlot;
  });
  assert.deepEqual(probed, ["audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF"]);
  assert.equal(view.slotModel, "audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF");
  assert.equal(audioModelToReplace(view.status, "pocket"), kokoroSlot.active_model);
});

test("a kept local speech model is routed by its path, not its short name", async () => {
  // The status names a custom-folder GGUF by its file stem; serving_checkpoints has the path.
  const primary = {
    ...chatPrimary,
    serving: ["unsloth/Qwen3-1.7B-GGUF", "MyVoice"],
    serving_checkpoints: ["unsloth/Qwen3-1.7B-GGUF", "/models/custom/MyVoice.gguf"],
  };
  const view = await describeAudioSlot(primary, async () => ({
    ...kokoroSlot,
    active_model: "MyVoice",
  }));
  assert.equal(view.slotModel, "/models/custom/MyVoice.gguf");
  assert.equal(view.slotLabel, "MyVoice");
  assert.equal(view.status.active_model, "MyVoice");
});

test("a local speech model is replaced by its path, not its short name", () => {
  // Loaded first with the chat model kept beside it, it is the active model: its status shows the
  // file stem and model_identifier holds the path the unload needs.
  const local = {
    ...kokoroSlot,
    active_model: "MyVoice",
    model_identifier: "/models/custom/MyVoice.gguf",
  };
  assert.equal(audioModelToReplace(local, "pocket"), "/models/custom/MyVoice.gguf");
  assert.equal(audioModelToReplace(local, "/models/custom/MyVoice.gguf"), null);
  assert.equal(audioModelToReplace(local, "MyVoice"), null);
});

test("a kept speech model sharing the chat model's short name is still found", async () => {
  // Two local GGUFs with one file stem: the server keeps them apart by checkpoint.
  const primary = {
    ...chatPrimary,
    active_model: "Voice",
    model_identifier: "/models/chat/Voice.gguf",
    serving: ["Voice", "Voice"],
    serving_checkpoints: ["/models/chat/Voice.gguf", "/models/tts/Voice.gguf"],
  };
  const probed: string[] = [];
  const view = await describeAudioSlot(primary, async (id) => {
    probed.push(id);
    return { ...kokoroSlot, active_model: "Voice", model_identifier: id };
  });
  assert.deepEqual(probed, ["/models/tts/Voice.gguf"]);
  assert.equal(view.slotModel, "/models/tts/Voice.gguf");
});