Skip to content

Studio: add an Audio API card to Settings and open it from Audio pages - #12821

Merged
danielhanchen merged 18 commits into
unslothai:mainfrom
Etherll:feat/studio-audio-api-settings
Oct 14, 2026
Merged

danielhanchen merged 18 commits into
unslothai:mainfrom
Etherll:feat/studio-audio-api-settings

Conversation

@Etherll

@Etherll Etherll commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Settings → API keys only had chat examples, so nothing showed how to call the audio routes from #12812. A new Audio API card under Usage examples has copy-ready curl (bash or PowerShell), Python and JavaScript calls for Speak, Clone, Transcribe and the /v1/audio/run workflows (Separate, Convert, Music, Edit). Each call uses this server's URL, the revealed key and a downloaded model that can run it. Each Audio page also gets a "Use via API" button that opens the card on that page's workflow and model.

Changes

  • /v1/models lists audio models only as text-to-speech or automatic-speech-recognition, so the card reads the Audio pages' audio.cpp catalog (and their family hints for repos it does not know) to find a model that can clone, convert, edit or make music. A loaded model comes first, then the Audio pages' default order.
  • Clone uploads me.wav to /v1/audio/inputs, saves it with /v1/audio/voices, then speaks with the saved voice id. The workflow examples upload their inputs and download every clip the run returns. Python uses httpx and JavaScript uses fetch for these Studio routes, since the OpenAI SDK has no method for them.
  • Transcribe asks for verbose_json with segment timestamps only on audio.cpp families that return them (Parakeet TDT, MOSS Transcribe Diarize, VibeVoice ASR, Kroko). Other models get plain text, since they answer a timestamp request with an error.
  • The Edit body comes from the EDIT_ADAPTERS builder the Edit page uses, so DotTTS, FireRedAudio and Vevo2 each get their own edit format.
  • A line under the snippet says when no downloaded model fits (the example then names a stand-in), and another says when Model auto-switch is off, because a request naming an unloaded model does not load it then.
  • Audio routes do not take keyless access, so without a revealed key the examples show sk-unsloth-YOUR_KEY.
  • The Secure HTTPS switch state moves from UsageExamples up to ApiKeysTab, so both cards use the same base URL. HighlightedCode is exported for reuse.
  • The chosen Audio API tab is kept as apiAudioExample in the settings panel prefs. The language and OS pills share the chat card's prefs.
  • "Use via API" sits left of the Library link and calls openAudioApi({ workflow, model }) on the settings dialog store, which opens API keys and scrolls to the card. The page's model is used only when the catalog says it can run that workflow, so a separator left loaded while Speak is open falls back to a downloaded speech model. The label shows only when the header has room beside the Create/Train pills; otherwise the button is an icon with a tooltip.
  • New strings in all 12 locales, and "Audio API" in the settings search index.

Testing

From studio/frontend:

npm test
npm run typecheck
npm run i18n:check
npm run build
  • npm test: 10589 of 10591 pass. The two failures (tests/color-themes.test.ts and tests/find-in-page.test.ts) are in files this PR does not touch; Frontend tests: read the composer shadow and palette seeds where #12800 left them #12810 fixes them on main.
  • typecheck, i18n:check and build pass.
  • New tests: tests/audio-api-snippets.test.ts (routes, escaping, PowerShell vs bash curl, Edit body per family, timestamp gating, model picks) and tests/audio-api-request.test.ts (Use via API opens the card; the request is dropped on leaving the tab), plus additions to tests/openai-model-catalog.test.ts and tests/settings-panel-prefs.test.ts.
  • All 41 generated snippets pass bash -n, py_compile, node --check and the PowerShell parser.
  • Live against a Studio built from this branch, with Model auto-switch on: Speak (curl and Python, Kokoro) wrote an mp3, Transcribe (curl and Python, Parakeet TDT) returned segments, Clone (curl, VoxCPM2) wrote an mp3, and Separate (curl and JavaScript, HTDemucs) saved 4 stems.
  • Checked the card and the header button with Playwright in light and dark, at 420, 700, 1400, 1700 and 1920 px wide.

Before / after

Built from main (c174a7db5) and from this branch after merging main (6be7d6313); the later commits only change the JavaScript transcription example and how often the card relists models, nothing in these frames.

Audio page header: "Use via API" sits left of Library.

Audio page header, before and after

Settings > API, opened by that button: the new Audio API card with the Speak / Clone / Transcribe / Workflows tabs and a ready-to-run /v1/audio/speech call. Before, the tab has only the chat usage examples.

Settings API tab, before and after

A script with an API key can now do what the Audio pages do, against /v1:

- /v1/audio/speech takes a saved voice (id or {"id"}), a built-in speaker
  of the model, or a reference clip to clone, and returns wav, mp3, flac,
  opus, aac or pcm. History keeps the WAV.
- /v1/audio/transcriptions gives OpenAI segments and words on audio.cpp
  models, plus diarized_json for models that tell speakers apart.
- /v1/audio/run takes a model and loads it, refusing one that cannot run
  the workflow before the resident model is evicted. API runs show in the
  API monitor.
- Audio inputs, saved voices and history clip files answer on /v1, with
  the upload streamed past the /v1 body cap. URLs returned on /v1 point
  at /v1.
- A timed /v1/audio/transcriptions upload past 30 minutes is refused with
  413, like the plain one, instead of being transcribed cut short.
- pcm speech is 24 kHz mono, the format OpenAI's clients play.
- The input sweep reaps a prepared upload a crash left behind.
A timed transcription can wait an hour on the aligner download before
audio.cpp reads its copy, so the sweep reaps a leftover copy after the
inputs' 24 h TTL, not the hour a temp file gets.
Settings → API keys only showed chat examples. The new Audio API card
shows copy-ready curl, Python and JavaScript calls for Speak, Clone,
Transcribe and the /v1/audio/run workflows (Separate, Convert, Music,
Edit), filled in with this server's URL, the revealed key and a
downloaded model that can run each one.

- Which model clones, converts, edits or makes music comes from the
  Audio pages' audio.cpp catalog, since /v1/models lists only a task.
- Transcribe asks for segment timestamps only on models that return
  them, and the Edit body is built by the same adapter the Edit page
  uses for that model family.
- The card says when no downloaded model fits, and when Model
  auto-switch is off, since a named model does not load then.
- The Secure HTTPS switch moves up to the tab so both cards share it.
Each Audio page gets a "Use via API" button in its header, left of the
Library link. It opens Settings → API keys at the Audio API card, on
that page's workflow and with the page's model filled in. The model is
used only when it can run the workflow, so a separator still loaded
while Speak is open falls back to a downloaded speech model.

The button shows its label only where the header has room beside the
Create/Train pills, and is icon-only with a tooltip otherwise.
@Etherll
Etherll requested a review from danielhanchen as a code owner October 6, 2026 04:27
@Etherll

Etherll commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

- Convert on RVC sends no target recording and picks a built-in voice
  instead, since RVC refuses a target.
- Music on Stable Audio's SFX build and ControlFoley asks for a sound
  effect, since they make no songs.
- An Audio page's model is used only when /v1/models lists it and it
  can run the workflow, so a resident chat model never ends up in a
  speech example.
- The JavaScript workflow examples wait for runs longer than 5 minutes
  instead of failing on fetch's default response timeout.
- With keyless access set to everything else, the examples use the
  keyless placeholder key, and the card no longer says a key is always
  needed.
- Picking a language in the Audio card keeps the chat card's stored
  variant of that language (Python + tools stays).
@Etherll

Etherll commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@Etherll

Etherll commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

Settings → API keys now has an Audio API card under Usage examples. It gives copy-ready curl, Python and JavaScript calls for Speak, Clone, Transcribe and the Separate, Convert, Music and Edit workflows, filled in with the server URL, the revealed key and a downloaded model that can run each one. Each Audio page's Use via API button opens the card on that page's workflow and model.

What changed

  • Some examples sent bodies their model refuses. Convert on RVC sent a target recording; it now sends only the recording with a built-in voice. Music on the SFX-only models asked for a song; those models now get a sound-effect request.
  • Use via API could put a loaded chat model into a speech example. The page's model is now used only when /v1/models lists it and it can run that workflow.
  • The JavaScript workflow examples gave up after 5 minutes, before long runs finished; they now keep waiting. With keyless access set to everything else, the examples now print the keyless key. Picking a language here no longer resets the chat card's "+ tools" choice.

Generated Speak, Transcribe, Clone and Separate calls ran against a Studio built from this branch and returned audio, timestamped segments and four stems. The fixed Convert and Music bodies return 200 from /v1/audio/run, and the JavaScript client waited through a 330 s response. Every snippet parses in bash, PowerShell, Python and Node. The frontend suite passes apart from three tests that also fail on the base commit.

Audio API card and Use via API, before and after

Before: merge base 7ccf3fcb2. After: fb9f5eceb. Both sides use the same /v1/models fixture.

@danielhanchen

Copy link
Copy Markdown
Member

Breakdown of the red checks here (the run was created at 05:31 UTC):

unslothai#12812 landed on main as a squash, so its backend files take main's
version. Keep the Use via API import and audioApiRequested beside
main's imports and requestedTab rename.
@danielhanchen danielhanchen self-assigned this Oct 7, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Review record for #12821, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#507.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror 1166515ed (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/frontend/src/features/settings/api/openai-model-catalog.ts (on the mirror)

@@ -15,6 +15,20 @@ type ApiOpenAIModelList = {
 
 const CHAT_TASKS = new Set(["text-generation"]);
 
+export type AudioApiTask = "text-to-speech" | "automatic-speech-recognition";
+
+export type AudioApiModel = {
+  id: string;
+  loaded: boolean;
+  // text-to-speech also covers music models, which /v1/audio/speech serves too.
+  task: AudioApiTask;
+};
+
+const AUDIO_TASKS = new Set<string>([
+  "text-to-speech",
+  "automatic-speech-recognition",
+]);

P1 Badge Preserve audio workflows from the model catalog

The backend's /v1/models rows already distinguish models with audio_workflows, but this parser drops that field and also excludes audio-to-audio. For example, downloaded MiniMaxAI/MiniMax-Music3 is reported as task: "text-to-speech" with audio_workflows: ["music"]; canRun consequently offers it for Speak and rejects it for Music. Separation models are discarded entirely, so the card falls back to HTDemucs even when a different separator is downloaded and suppresses the stand-in warning. Preserve and use the advertised workflows rather than inferring them from task and model-name heuristics.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 4616f01: the card now parses audio_workflows (and audio-to-audio separator rows) and lets them decide before the name hints.

chatgpt-codex-connector[bot] on studio/frontend/src/features/settings/components/audio-api-examples.tsx (on the mirror)

@@ -0,0 +1,344 @@
+// 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 { usePlatformStore } from "@/config/env";
+import { useT } from "@/i18n";
+import type { TranslationKey } from "@/i18n";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { Tick02Icon } from "@/lib/tick-icon";
+import { cn } from "@/lib/utils";
+import { Copy01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
+import type {
+  KeylessApiAccessExposure,
+  KeylessApiAccessScope,
+} from "../api/keyless-api-access";
+import { loadOpenAIAutoSwitchSettings } from "../api/openai-auto-switch";
+import {
+  type AudioApiModel,
+  listOpenAIAudioModels,
+} from "../api/openai-models";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+import { useSettingsPanelPrefsStore } from "../stores/settings-panel-prefs-store";
+import {
+  AUDIO_API_PLACEHOLDER_MODELS,
+  AUDIO_API_TABS,
+  AUDIO_RUN_WORKFLOWS,
+  type AudioApiExample,
+  type AudioApiLang,
+  type AudioApiOs,
+  type AudioApiTab,
+  type AudioRunWorkflow,
+  audioApiExampleFor,
+  audioApiKey,
+  audioApiModelFits,
+  audioLangToStore,
+  buildAudioApiSnippet,
+  langFromStored,
+  pickAudioApiModel,
+} from "./audio-api-snippets";
+import { HighlightedCode } from "./usage-examples";
+
+const LANGS: { id: AudioApiLang; label: string }[] = [
+  { id: "curl", label: "curl" },
+  { id: "python", label: "Python" },
+  { id: "javascript", label: "JavaScript" },
+];
+
+const TAB_LABEL: Record<AudioApiTab, TranslationKey> = {
+  speak: "settings.apiKeys.audioApi.speak",
+  clone: "settings.apiKeys.audioApi.clone",
+  transcribe: "settings.apiKeys.audioApi.transcribe",
+  workflows: "settings.apiKeys.audioApi.workflows",
+};
+
+const RUN_LABEL: Record<AudioRunWorkflow, TranslationKey> = {
+  separate: "settings.apiKeys.audioApi.separate",
+  convert: "settings.apiKeys.audioApi.convert",
+  music: "settings.apiKeys.audioApi.music",
+  edit: "settings.apiKeys.audioApi.edit",
+};
+
+function Pill({
+  active,
+  onClick,
+  children,
+}: {
+  active: boolean;
+  onClick: () => void;
+  children: ReactNode;
+}) {
+  return (
+    <button
+      type="button"
+      onClick={onClick}
+      aria-pressed={active}
+      className={cn(
+        "rounded-full px-2.5 py-1 text-ui-11 font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
+        active
+          ? "hub-tab-toggle-pill text-foreground"
+          : "text-muted-foreground hover:text-foreground",
+      )}
+    >
+      {children}
+    </button>
+  );
+}
+
+export function AudioApiExamples({
+  apiKey,
+  useTunnel,
+  keylessScope = "off",
+  keylessExposure = null,
+}: {
+  apiKey?: string | null;
+  useTunnel: boolean;
+  keylessScope?: KeylessApiAccessScope;
+  keylessExposure?: KeylessApiAccessExposure | null;
+}) {
+  const t = useT();
+  const deviceType = usePlatformStore((s) => s.deviceType);
+  const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
+  const serverUrl = usePlatformStore((s) => s.serverUrl);
+  const setStoredTab = useSettingsPanelPrefsStore((s) => s.setApiAudioExample);
+  const setStoredLang = useSettingsPanelPrefsStore((s) => s.setApiExampleLang);
+  const setStoredOs = useSettingsPanelPrefsStore((s) => s.setApiExampleOs);
+  const [storedPrefs] = useState(() => useSettingsPanelPrefsStore.getState());
+  const [tab, setTab] = useState<AudioApiTab>(
+    AUDIO_API_TABS.find((id) => id === storedPrefs.apiAudioExample) ?? "speak",
+  );
+  const [run, setRun] = useState<AudioRunWorkflow>("separate");
+  const [lang, setLang] = useState<AudioApiLang>(
+    langFromStored(storedPrefs.apiExampleLang),
+  );
+  const [os, setOs] = useState<AudioApiOs>(
+    storedPrefs.apiExampleOs ?? (deviceType === "windows" ? "windows" : "unix"),
+  );
+  // null until /v1/models answers, so a slow or failed listing never claims nothing is downloaded.
+  const [models, setModels] = useState<AudioApiModel[] | null>(null);
+  const [autoSwitch, setAutoSwitch] = useState<boolean | null>(null);
+  const [copied, setCopied] = useState(false);
+  const [pageModel, setPageModel] = useState<{
+    example: AudioApiExample;
+    model: string;
+  } | null>(null);
+  const sectionRef = useRef<HTMLElement | null>(null);
+  const audioApiRequested = useSettingsDialogStore((s) => s.audioApiRequested);
+  const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
+
+  useEffect(() => {
+    if (!audioApiRequested) return;
+    const next = audioApiExampleFor(audioApiRequested.workflow);
+    setTab(next.tab);
+    if (next.run) setRun(next.run);
+    setPageModel(
+      audioApiRequested.model
+        ? {
+            example:
+              next.tab === "workflows" ? (next.run ?? "separate") : next.tab,
+            model: audioApiRequested.model,
+          }
+        : null,
+    );
+    useSettingsDialogStore.getState().consumeAudioApiRequest();
+  }, [audioApiRequested]);
+
+  useEffect(() => {
+    if (scrollTarget !== "api-keys-audio-api") return;
+    const section = sectionRef.current;
+    if (!section) return;
+    // Consumed only after the user scrolls: clearing it re-runs this effect, whose cleanup stops the pinning.
+    const pin = () => section.scrollIntoView({ block: "start" });
+    const observer = new ResizeObserver(pin);
+    observer.observe(section.parentElement ?? section);
+    const release = () => {
+      observer.disconnect();
+      useSettingsDialogStore
+        .getState()
+        .consumeScrollTarget("api-keys-audio-api");
+    };
+    const timer = window.setTimeout(release, 1500);
+    const events = ["wheel", "touchmove", "keydown"] as const;
+    for (const name of events) {
+      window.addEventListener(name, release, { passive: true });
+    }
+    return () => {
+      observer.disconnect();
+      window.clearTimeout(timer);
+      for (const name of events) window.removeEventListener(name, release);
+    };
+  }, [scrollTarget]);
+
+  useEffect(() => {
+    let cancelled = false;
+    listOpenAIAudioModels().then(
+      (listed) => !cancelled && setModels(listed),
+      () => undefined,
+    );
+    loadOpenAIAutoSwitchSettings().then(
+      (settings) => !cancelled && setAutoSwitch(settings.enabled),
+      () => undefined,
+    );
+    return () => {
+      cancelled = true;
+    };
+  }, []);
+
+  const origin = typeof window !== "undefined" ? window.location.origin : "";
+  const base =
+    useTunnel && cloudflareUrl ? cloudflareUrl : (serverUrl ?? origin);
+  const key = audioApiKey(apiKey, {
+    base,
+    tunnel: useTunnel && !!cloudflareUrl,
+    scope: keylessScope,
+    exposure: keylessExposure,
+  });
+  const example: AudioApiExample = tab === "workflows" ? run : tab;
+  const picked =
+    pageModel?.example === example &&
+    audioApiModelFits(models, pageModel.model, example)
+      ? pageModel.model
+      : models
+        ? pickAudioApiModel(models, example)
+        : null;
+  const model = picked ?? AUDIO_API_PLACEHOLDER_MODELS[example];
+  const snippet = useMemo(
+    () =>
+      buildAudioApiSnippet(example, {
+        base,
+        apiKey: key,
+        model,
+        lang,
+        os,
+      }),
+    [base, example, key, lang, model, os],
+  );
+  // Separation models are not in /v1/models, so an unpicked one says nothing about the disk.
+  const placeholder = models !== null && !picked && example !== "separate";
+  const needsLoad =
+    !placeholder &&
+    autoSwitch === false &&
+    !models?.some((m) => m.id === model && m.loaded);

P2 Badge Wait for the model catalog before warning about loading

When /v1/models is still pending or fails while auto-switch is disabled, models remains null, so !models?.some(...) evaluates to true and the UI claims that the selected model must be loaded even if it is already resident. This contradicts the nearby intent not to infer download state from a missing catalog response and can become a permanent false warning after a catalog error; require a completed model listing before deriving needsLoad.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 4616f01: the auto-switch warning now needs a completed /v1/models listing.

Round 2: reviewed mirror f9be8f98d (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/frontend/src/features/settings/components/audio-api-snippets.ts (on the mirror)

@@ -0,0 +1,776 @@
+// 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 {
+  AUDIO_CPP_MODELS,
+  AUDIO_CPP_REPO,
+  type AudioCppWorkflow,
+  audioCppModelFor,
+  audioCppWorkflowsFor,
+  isAudioCppFolderId,
+  isCloneAndConvertFamilyId,
+  isCloneOnlyFamilyId,
+  isConvertOnlyFamilyId,
+  isSpeakAndCloneFamilyId,
+} from "../../audio/audio-cpp-catalog";
+import { EDIT_ADAPTERS } from "../../audio/edit-adapters";
+import type {
+  KeylessApiAccessExposure,
+  KeylessApiAccessScope,
+} from "../api/keyless-api-access";
+import type { AudioApiModel } from "../api/openai-model-catalog";
+import { psSingle, shSingle } from "./agent-command";
+import { keylessBaseEligible } from "./keyless-example-eligibility";
+
+export type AudioApiTab = "speak" | "clone" | "transcribe" | "workflows";
+export type AudioRunWorkflow = "separate" | "convert" | "music" | "edit";
+export type AudioApiLang = "curl" | "python" | "javascript";
+export type AudioApiOs = "unix" | "windows";
+export type AudioApiExample =
+  | Exclude<AudioApiTab, "workflows">
+  | AudioRunWorkflow;
+
+export const AUDIO_API_TABS: readonly AudioApiTab[] = [
+  "speak",
+  "clone",
+  "transcribe",
+  "workflows",
+];
+export const AUDIO_RUN_WORKFLOWS: readonly AudioRunWorkflow[] = [
+  "separate",
+  "convert",
+  "music",
+  "edit",
+];
+
+const KEY_PLACEHOLDER = "sk-unsloth-YOUR_KEY";
+const KEYLESS_KEY_PLACEHOLDER = "not-needed";
+
+export function audioApiKey(
+  apiKey: string | null | undefined,
+  server: {
+    base: string;
+    tunnel: boolean;
+    scope: KeylessApiAccessScope;
+    exposure: KeylessApiAccessExposure | null;
+  },
+): string {
+  if (apiKey) return apiKey;
+  // Keyless access admits the audio routes only at its "everything else" scope.
+  const keyless =
+    !server.tunnel &&
+    server.scope === "full" &&
+    keylessBaseEligible(server.base, server.scope, server.exposure);
+  return keyless ? KEYLESS_KEY_PLACEHOLDER : KEY_PLACEHOLDER;
+}
+
+// The chat examples store a variant ("pythonTools"); its language carries over.
+export function langFromStored(stored: string | null): AudioApiLang {
+  if (stored?.startsWith("python")) return "python";
+  if (stored?.startsWith("javascript")) return "javascript";
+  return "curl";
+}
+
+// null: the chat card's stored variant already carries this language.
+export function audioLangToStore(
+  stored: string | null,
+  lang: AudioApiLang,
+): string | null {
+  return stored && langFromStored(stored) === lang ? null : lang;
+}
+
+export function audioApiExampleFor(workflow: AudioCppWorkflow): {
+  tab: AudioApiTab;
+  run: AudioRunWorkflow | null;
+} {
+  return workflow === "speak" ||
+    workflow === "clone" ||
+    workflow === "transcribe"
+    ? { tab: workflow, run: null }
+    : { tab: "workflows", run: workflow };
+}
+
+const folder = (name: string) => `${AUDIO_CPP_REPO}/${name}`;
+
+export const AUDIO_API_PLACEHOLDER_MODELS: Record<AudioApiExample, string> = {
+  speak: folder("Kokoro-82M-GGUF"),
+  clone: folder("VoxCPM2-GGUF"),
+  transcribe: folder("Parakeet-TDT-0.6B-v3-GGUF"),
+  separate: folder("HTDemucs-GGUF"),
+  convert: folder("Chatterbox-GGUF"),
+  music: folder("ACE-Step1.5-GGUF"),
+  edit: folder("DotTTS-Edit-GGUF"),
+};
+
+// The page can hand over any resident model (a chat one too), so /v1/models must list it once it answers.
+export function audioApiModelFits(
+  models: readonly AudioApiModel[] | null,
+  id: string,
+  example: AudioApiExample,
+): boolean {
+  if (models === null) {
+    const known = audioCppModelFor(id);
+    return !!known && audioCppWorkflowsFor(known).includes(example);
+  }
+  const listed = models.find((model) => model.id === id);
+  if (listed) return canRun(listed, example);
+  // Only a resident separator is listed, so a downloaded one falls back to the catalog.
+  const known = example === "separate" ? audioCppModelFor(id) : null;
+  return !!known && audioCppWorkflowsFor(known).includes(example);
+}
+
+// /v1/models gives a task, not workflows: the audio.cpp catalog decides, family hints for unknown repos.
+function canRun(model: AudioApiModel, example: AudioApiExample): boolean {
+  if (model.workflows?.length) return model.workflows.includes(example);
+  if (example === "transcribe") {
+    return model.task === "automatic-speech-recognition";
+  }
+  if (model.task !== "text-to-speech" || example === "separate") return false;
+  const known = audioCppModelFor(model.id);
+  if (known) return audioCppWorkflowsFor(known).includes(example);
+  switch (example) {
+    case "speak":
+      return !isCloneOnlyFamilyId(model.id) && !isConvertOnlyFamilyId(model.id);
+    case "clone":
+      return isCloneOnlyFamilyId(model.id) || isSpeakAndCloneFamilyId(model.id);
+    case "convert":
+      return (
+        isCloneAndConvertFamilyId(model.id) || isConvertOnlyFamilyId(model.id)
+      );
+    default:
+      return false;
+  }
+}
+
+const CATALOG_ORDER = new Map(
+  AUDIO_CPP_MODELS.map((model, index) => [model.id.toLowerCase(), index]),
+);
+
+export function pickAudioApiModel(
+  models: readonly AudioApiModel[],
+  example: AudioApiExample,
+): string | null {
+  const rank = (model: AudioApiModel) => [
+    model.loaded ? 0 : 1,
+    example === "transcribe" && !transcribeWithTimestamps(model.id) ? 1 : 0,
+    CATALOG_ORDER.get(model.id.toLowerCase()) ?? AUDIO_CPP_MODELS.length,
+  ];
+  const fits = models
+    .filter((model) => canRun(model, example))
+    .map((model) => ({ id: model.id, rank: rank(model) }));
+  fits.sort(
+    (a, b) =>
+      a.rank[0] - b.rank[0] || a.rank[1] - b.rank[1] || a.rank[2] - b.rank[2],
+  );
+  return fits[0]?.id ?? null;
+}
+
+// Mirrors ALWAYS_TIMESTAMPED in studio/backend/core/inference/stt_details.py; other engines 400 on timestamps.
+const TIMESTAMPED_FAMILY_HINT =
+  /parakeet[-_]?tdt|moss[-_]?transcribe[-_]?diarize|vibevoice[-_]?asr|kroko/i;
+
+export function transcribeWithTimestamps(model: string): boolean {
+  return isAudioCppFolderId(model) && TIMESTAMPED_FAMILY_HINT.test(model);
+}
+
+export interface AudioApiSnippetInput {
+  base: string;
+  apiKey: string;
+  model: string;
+  lang: AudioApiLang;
+  os: AudioApiOs;
+}
+
+const SPEAK_TEXT = "Hello from Unsloth.";
+const CLONE_TEXT = "This is my voice, speaking text I never recorded.";
+const CLONE_TRANSCRIPT = "The words spoken in me.wav.";
+const EDIT_FROM = "The quick brown fox jumps over the lazy dog.";
+const EDIT_TO = "The quick red fox jumps over the lazy dog.";
+
+type Ref = { upload: string };
+type Json = string | number | boolean | Ref | Json[] | { [key: string]: Json };
+
+function isRef(value: Json): value is Ref {
+  return typeof value === "object" && value !== null && "upload" in value;
+}
+
+type Style = "json" | "python" | "jq" | "powershell";
+
+function refExpr(name: string, style: Style): string {
+  switch (style) {
+    case "python":
+      return `${name}["id"]`;
+    case "jq":
+      return `$${name}`;
+    case "powershell":
+      return `"$($${name}.id)"`;
+    default:
+      return `${name}.id`;
+  }
+}
+
+function scalar(value: string | number | boolean, style: Style): string {
+  if (typeof value === "boolean" && style === "python") {
+    return value ? "True" : "False";
+  }
+  const text = JSON.stringify(value);
+  // An expandable here-string reads ` and $ as escapes.
+  return style === "powershell" ? text.replace(/[`$]/g, "`$&") : text;
+}
+
+function render(value: Json, style: Style, indent = ""): string {
+  if (isRef(value)) return refExpr(value.upload, style);
+  if (typeof value !== "object") return scalar(value, style);
+  const inner = `${indent}${style === "python" ? "    " : "  "}`;
+  const entries = Array.isArray(value)
+    ? value.map((item) => `${inner}${render(item, style, inner)}`)
+    : Object.entries(value).map(
+        ([key, item]) =>
+          `${inner}${JSON.stringify(key)}: ${render(item, style, inner)}`,
+      );
+  const [open, close] = Array.isArray(value) ? ["[", "]"] : ["{", "}"];
+  return entries.length
+    ? `${open}\n${entries.join(",\n")}\n${indent}${close}`
+    : `${open}${close}`;
+}
+
+const j = (value: string) => JSON.stringify(value);
+
+// Mirrors the rvc family in audio_cpp_models.py: built-in voices only, a target recording is refused.
+const BUILTIN_VOICE_CONVERTER = /(^|[-_ /.])rvc([-_ /.]|$)/i;
+// Mirrors the music specs there: Stable Audio's SFX build and ControlFoley make no songs.
+const SFX_ONLY_MUSIC = /(^|[-_ /.])sfx([-_ /.]|$)|controlfoley/i;
+
+function editFamily(model: string): string {
+  if (/firered/i.test(model)) return "firered_audio";
+  if (/vevo[-_]?2/i.test(model)) return "vevo2";
+  return "dots_tts";
+}
+
+interface RunPlan {
+  uploads: { name: string; file: string }[];
+  body: { [key: string]: Json };
+}
+
+function runPlan(workflow: AudioRunWorkflow, model: string): RunPlan {
+  switch (workflow) {
+    case "separate":
+      return {
+        uploads: [{ name: "source", file: "song.wav" }],
+        body: {
+          workflow,
+          model,
+          inputs: { source: { input_id: { upload: "source" } } },
+        },
+      };
+    case "convert":
+      if (BUILTIN_VOICE_CONVERTER.test(model)) {
+        return {
+          uploads: [{ name: "source", file: "speech.wav" }],
+          body: {
+            workflow,
+            model,
+            inputs: { source: { input_id: { upload: "source" } } },
+            convert: { voice: "default" },
+          },
+        };
+      }
+      return {
+        uploads: [
+          { name: "source", file: "speech.wav" },
+          { name: "target", file: "voice.wav" },
+        ],
+        body: {
+          workflow,
+          model,
+          inputs: {
+            source: { input_id: { upload: "source" } },
+            target: { input_id: { upload: "target" } },
+          },
+        },
+      };
+    case "music":
+      if (SFX_ONLY_MUSIC.test(model)) {
+        return {
+          uploads: [],
+          body: {
+            workflow,
+            model,
+            mode: "sfx",
+            text: "Rain on a tin roof with distant thunder",
+          },
+        };
+      }
+      return {
+        uploads: [],
+        body: {
+          workflow,
+          model,
+          mode: "song",
+          text: "Upbeat synth pop with a catchy chorus",
+          lyrics:
+            "[verse]\nCity lights are calling me\n[chorus]\nWe dance until the morning",
+        },
+      };
+    default: {
+      const edit = Object.fromEntries(
+        Object.entries(
+          EDIT_ADAPTERS[editFamily(model)].buildEdit({
+            transcript: EDIT_FROM,
+            edited: EDIT_TO,
+            mode: "words",
+          }),
+        ),
+      );
+      return {
+        uploads: [{ name: "source", file: "speech.wav" }],
+        body: {
+          workflow,
+          model,
+          text: EDIT_TO,
+          inputs: {
+            source: { input_id: { upload: "source" } },
+            reference_text: EDIT_FROM,
+          },
+          edit,
+        },
+      };
+    }
+  }
+}
+
+function bashPreamble(base: string, apiKey: string): string {
+  return `BASE='${shSingle(base)}'\nKEY='${shSingle(apiKey)}'\n`;
+}
+
+function powershellPreamble(base: string, apiKey: string): string {
+  return `$base = '${psSingle(base)}'\n$key = '${psSingle(apiKey)}'\n`;
+}
+
+function bashUpload(name: string, file: string): string {
+  return `${name.toUpperCase()}=$(curl -s "$BASE/v1/audio/inputs?name=${file}" \\
+  -H "Authorization: Bearer $KEY" \\
+  --data-binary @${file} | jq -r .id)`;
+}
+
+function powershellUpload(name: string, file: string): string {
+  return `$${name} = curl.exe -s "$base/v1/audio/inputs?name=${file}" \`
+  -H "Authorization: Bearer $key" \`
+  --data-binary "@${file}" | ConvertFrom-Json`;
+}
+
+function bashBody(body: { [key: string]: Json }, refs: string[]): string {
+  if (refs.length === 0) return `'${shSingle(render(body, "json", "  "))}'`;
+  const args = refs
+    .map((ref) => `--arg ${ref} "$${ref.toUpperCase()}"`)
+    .join(" ");
+  return `"$(jq -n ${args} '${shSingle(render(body, "jq", "  "))}')"`;
+}
+
+function powershellBody(body: { [key: string]: Json }): string {
+  return `$body = @"\n${render(body, "powershell")}\n"@
+Set-Content -Path body.json -Value $body -Encoding ascii`;
+}
+
+interface ClientNeeds {
+  sdk: boolean;
+  studio: boolean;
+  upload: boolean;
+  longRuns: boolean;
+}
+
+const SDK_ONLY: ClientNeeds = {
+  sdk: true,
+  studio: false,
+  upload: false,
+  longRuns: false,
+};
+const SDK_AND_UPLOADS: ClientNeeds = {
+  sdk: true,
+  studio: true,
+  upload: true,
+  longRuns: false,
+};
+
+function pythonClient(
+  base: string,
+  apiKey: string,
+  { sdk, studio, upload }: ClientNeeds,
+): string {
+  const imports = [
+    ...(studio ? ["import httpx"] : []),
+    ...(sdk ? ["from openai import OpenAI"] : []),
+  ];
+  let out = `${imports.join("\n")}
+
+BASE = ${j(base)}
+KEY = ${j(apiKey)}
+`;
+  if (sdk) {
+    out += `
+client = OpenAI(base_url=f"{BASE}/v1", api_key=KEY)`;
+  }
+  if (studio) {
+    out += `${sdk ? "\n" : ""}
+# Uploads, saved voices and workflow runs are Studio routes the OpenAI SDK has no method for.
+studio = httpx.Client(base_url=BASE, headers={"Authorization": f"Bearer {KEY}"}, timeout=None)
+
+
+def post(path, **kwargs):
+    response = studio.post(path, **kwargs)
+    response.raise_for_status()
+    return response.json()`;
+  }
+  if (upload) {
+    out += `
+
+
+def upload(file):
+    with open(file, "rb") as audio:
+        return post("/v1/audio/inputs", params={"name": file}, content=audio.read())`;
+  }
+  return out;
+}
+
+function javascriptClient(
+  base: string,
+  apiKey: string,
+  { sdk, studio, upload, longRuns }: ClientNeeds,
+): string {
+  let out = `import fs from "node:fs";
+${sdk ? 'import OpenAI from "openai";\n' : ""}${longRuns ? 'import { Agent, setGlobalDispatcher } from "undici";\n' : ""}
+const BASE = ${j(base)};
+const KEY = ${j(apiKey)};`;
+  if (longRuns) {
+    out += `
+
+// fetch stops waiting for a response after 5 minutes; a long run takes longer than that.
+setGlobalDispatcher(new Agent({ headersTimeout: 0, bodyTimeout: 0 }));`;
+  }
+  if (sdk) {
+    out += `
+
+const client = new OpenAI({ baseURL: BASE + "/v1", apiKey: KEY });`;
+  }
+  if (studio) {
+    out += `
+
+// Uploads, saved voices and workflow runs are Studio routes the OpenAI SDK has no method for.
+async function studio(path, init = {}) {
+  const response = await fetch(BASE + path, {
+    ...init,
+    headers: { Authorization: "Bearer " + KEY, ...init.headers },
+  });
+  if (!response.ok) throw new Error(await response.text());
+  return response;
+}`;
+  }
+  if (upload) {
+    out += `
+
+async function upload(file) {
+  const response = await studio("/v1/audio/inputs?name=" + file, {
+    method: "POST",
+    body: fs.readFileSync(file),
+  });
+  return response.json();
+}`;
+  }
+  return out;
+}
+
+function speakSnippet({
+  base,
+  apiKey,
+  model,
+  lang,
+  os,
+}: AudioApiSnippetInput): string {
+  const body = {
+    model,
+    input: SPEAK_TEXT,
+    voice: "alloy",
+    response_format: "mp3",
+  };
+  const voiceNote =
+    "voice: a saved voice id or one of the model's own speakers. Other names, like alloy, keep its default voice.";
+  if (lang === "python") {
+    return `${pythonClient(base, apiKey, SDK_ONLY)}
+
+# ${voiceNote}
+with client.audio.speech.with_streaming_response.create(
+    model=${j(model)},
+    voice="alloy",
+    input=${j(SPEAK_TEXT)},
+    response_format="mp3",
+) as speech:
+    speech.stream_to_file("speech.mp3")`;
+  }
+  if (lang === "javascript") {
+    return `${javascriptClient(base, apiKey, SDK_ONLY)}
+
+// ${voiceNote}
+const speech = await client.audio.speech.create({
+  model: ${j(model)},
+  voice: "alloy",
+  input: ${j(SPEAK_TEXT)},
+  response_format: "mp3",
+});
+fs.writeFileSync("speech.mp3", Buffer.from(await speech.arrayBuffer()));`;
+  }
+  if (os === "windows") {
+    return `${powershellPreamble(base, apiKey)}# ${voiceNote}
+${powershellBody(body)}
+curl.exe "$base/v1/audio/speech" \`
+  -H "Authorization: Bearer $key" \`
+  -H "Content-Type: application/json" \`
+  -d "@body.json" -o speech.mp3`;
+  }
+  return `${bashPreamble(base, apiKey)}# ${voiceNote}
+curl "$BASE/v1/audio/speech" \\
+  -H "Authorization: Bearer $KEY" \\
+  -H "Content-Type: application/json" \\
+  -d ${bashBody(body, [])} \\
+  -o speech.mp3`;
+}
+
+function cloneSnippet({
+  base,
+  apiKey,
+  model,
+  lang,
+  os,
+}: AudioApiSnippetInput): string {
+  const voice: { [key: string]: Json } = {
+    name: "Me",
+    source: { input_id: { upload: "recording" } },
+    transcript: CLONE_TRANSCRIPT,
+  };
+  const speech: { [key: string]: Json } = {
+    model,
+    input: CLONE_TEXT,
+    voice: { upload: "voice" },
+    response_format: "mp3",
+  };
+  const steps =
+    "Upload a short recording of the voice, save it as a voice, then speak in it.";
+  const transcriptNote =
+    "transcript: what me.wav says. Some models need it to clone.";
+  if (lang === "python") {
+    return `${pythonClient(base, apiKey, SDK_AND_UPLOADS)}
+
+
+# ${steps}
+recording = upload("me.wav")
+# ${transcriptNote}
+voice = post("/v1/audio/voices", json=${render(voice, "python")})
+
+with client.audio.speech.with_streaming_response.create(
+    model=${j(model)},
+    voice=voice["id"],
+    input=${j(CLONE_TEXT)},
+    response_format="mp3",
+) as speech:
+    speech.stream_to_file("clone.mp3")`;
+  }
+  if (lang === "javascript") {
+    return `${javascriptClient(base, apiKey, SDK_AND_UPLOADS)}
+
+// ${steps}
+const recording = await upload("me.wav");
+// ${transcriptNote}
+const saved = await studio("/v1/audio/voices", {
+  method: "POST",
+  headers: { "Content-Type": "application/json" },
+  body: JSON.stringify(${render(voice, "json").replace(/\n/g, "\n  ")}),
+});
+const voice = await saved.json();
+
+const speech = await client.audio.speech.create({
+  model: ${j(model)},
+  voice: voice.id,
+  input: ${j(CLONE_TEXT)},
+  response_format: "mp3",
+});
+fs.writeFileSync("clone.mp3", Buffer.from(await speech.arrayBuffer()));`;
+  }
+  if (os === "windows") {
+    return `${powershellPreamble(base, apiKey)}# ${steps}
+${powershellUpload("recording", "me.wav")}
+# ${transcriptNote}
+${powershellBody(voice)}
+$voice = curl.exe -s "$base/v1/audio/voices" \`
+  -H "Authorization: Bearer $key" \`
+  -H "Content-Type: application/json" \`
+  -d "@body.json" | ConvertFrom-Json
+${powershellBody(speech)}
+curl.exe "$base/v1/audio/speech" \`
+  -H "Authorization: Bearer $key" \`
+  -H "Content-Type: application/json" \`
+  -d "@body.json" -o clone.mp3`;
+  }
+  return `${bashPreamble(base, apiKey)}# ${steps}
+${bashUpload("recording", "me.wav")}
+# ${transcriptNote}
+VOICE=$(curl -s "$BASE/v1/audio/voices" \\
+  -H "Authorization: Bearer $KEY" \\
+  -H "Content-Type: application/json" \\
+  -d ${bashBody(voice, ["recording"])} | jq -r .id)
+curl "$BASE/v1/audio/speech" \\
+  -H "Authorization: Bearer $KEY" \\
+  -H "Content-Type: application/json" \\
+  -d ${bashBody(speech, ["voice"])} \\
+  -o clone.mp3`;
+}
+
+function transcribeSnippet({
+  base,
+  apiKey,
+  model,
+  lang,
+  os,
+}: AudioApiSnippetInput): string {
+  const timed = transcribeWithTimestamps(model);
+  if (lang === "python") {
+    const options = timed
+      ? `
+    response_format="verbose_json",
+    timestamp_granularities=["segment"],
+    language="en",`
+      : "";
+    const output = timed
+      ? `for segment in transcript.segments:
+    print(f"[{segment.start:.1f}s - {segment.end:.1f}s] {segment.text}")`
+      : "print(transcript.text)";
+    return `${pythonClient(base, apiKey, SDK_ONLY)}
+
+with open("speech.wav", "rb") as audio:
+    transcript = client.audio.transcriptions.create(
+        model=${j(model)},
+        file=audio,${options.replace(/\n {4}/g, "\n        ")}
+    )
+${output}`;
+  }
+  if (lang === "javascript") {
+    const options = timed
+      ? `
+  response_format: "verbose_json",
+  timestamp_granularities: ["segment"],
+  language: "en",`
+      : "";
+    const output = timed
+      ? `for (const segment of transcript.segments ?? []) {
+  console.log(\`[\${segment.start.toFixed(1)}s - \${segment.end.toFixed(1)}s] \${segment.text}\`);
+}`
+      : "console.log(transcript.text);";
+    return `${javascriptClient(base, apiKey, SDK_ONLY)}
+
+const transcript = await client.audio.transcriptions.create({
+  model: ${j(model)},
+  file: fs.createReadStream("speech.wav"),${options}
+});
+${output}`;
+  }
+  const fields = [
+    "[email protected]",
+    `model=${model}`,
+    ...(timed
+      ? [
+          "response_format=verbose_json",
+          "timestamp_granularities[]=segment",
+          "language=en",
+        ]
+      : []),
+  ];
+  if (os === "windows") {
+    return `${powershellPreamble(base, apiKey)}curl.exe "$base/v1/audio/transcriptions" \`
+  -H "Authorization: Bearer $key" \`
+${fields.map((field) => `  -F '${psSingle(field)}'`).join(" `\n")}`;
+  }
+  return `${bashPreamble(base, apiKey)}curl "$BASE/v1/audio/transcriptions" \\
+  -H "Authorization: Bearer $KEY" \\
+${fields.map((field) => `  -F '${shSingle(field)}'`).join(" \\\n")}`;
+}
+
+function runSnippet(
+  workflow: AudioRunWorkflow,
+  { base, apiKey, model, lang, os }: AudioApiSnippetInput,
+): string {
+  const { uploads, body } = runPlan(workflow, model);
+  const refs = uploads.map((item) => item.name);
+  const needs = {
+    sdk: false,
+    studio: true,
+    upload: uploads.length > 0,
+    longRuns: true,
+  };
+  const save =
+    workflow === "separate"
+      ? "Saves each stem as <clip id>.wav."
+      : "Saves each clip the run made as <clip id>.wav.";
+  if (lang === "python") {
+    return `${pythonClient(base, apiKey, needs)}
+
+
+${uploads.map((item) => `${item.name} = upload(${j(item.file)})`).join("\n")}${uploads.length ? "\n" : ""}result = post("/v1/audio/run", json=${render(body, "python")})
+
+# ${save}
+for clip in result["clips"]:
+    audio = studio.get(clip["url"])
+    audio.raise_for_status()
+    with open(f"{clip['id']}.wav", "wb") as out:
+        out.write(audio.content)`;

P2 Badge Save the inline audio fallback from workflow runs

When gallery persistence fails (for example, because the media directory is full or unwritable), _audio_run_response deliberately returns a successful response with clips: [] and the generated WAV in audio.data. This loop therefore exits without creating any output file; the JavaScript and curl variants likewise process only clips, so every generated workflow example silently discards the only copy of the result in this recovery path. Decode and save result.audio when it is present.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing: the inline audio only comes back when the server cannot write its own media directory, a server fault the copy-ready examples do not try to cover; keeping each example short matters more here.

chatgpt-codex-connector[bot] on studio/frontend/src/features/settings/components/audio-api-examples.tsx (on the mirror)

@@ -0,0 +1,345 @@
+// 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 { usePlatformStore } from "@/config/env";
+import { useT } from "@/i18n";
+import type { TranslationKey } from "@/i18n";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { Tick02Icon } from "@/lib/tick-icon";
+import { cn } from "@/lib/utils";
+import { Copy01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
+import type {
+  KeylessApiAccessExposure,
+  KeylessApiAccessScope,
+} from "../api/keyless-api-access";
+import { loadOpenAIAutoSwitchSettings } from "../api/openai-auto-switch";
+import {
+  type AudioApiModel,
+  listOpenAIAudioModels,
+} from "../api/openai-models";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+import { useSettingsPanelPrefsStore } from "../stores/settings-panel-prefs-store";
+import {
+  AUDIO_API_PLACEHOLDER_MODELS,
+  AUDIO_API_TABS,
+  AUDIO_RUN_WORKFLOWS,
+  type AudioApiExample,
+  type AudioApiLang,
+  type AudioApiOs,
+  type AudioApiTab,
+  type AudioRunWorkflow,
+  audioApiExampleFor,
+  audioApiKey,
+  audioApiModelFits,
+  audioLangToStore,
+  buildAudioApiSnippet,
+  langFromStored,
+  pickAudioApiModel,
+} from "./audio-api-snippets";
+import { HighlightedCode } from "./usage-examples";
+
+const LANGS: { id: AudioApiLang; label: string }[] = [
+  { id: "curl", label: "curl" },
+  { id: "python", label: "Python" },
+  { id: "javascript", label: "JavaScript" },
+];
+
+const TAB_LABEL: Record<AudioApiTab, TranslationKey> = {
+  speak: "settings.apiKeys.audioApi.speak",
+  clone: "settings.apiKeys.audioApi.clone",
+  transcribe: "settings.apiKeys.audioApi.transcribe",
+  workflows: "settings.apiKeys.audioApi.workflows",
+};
+
+const RUN_LABEL: Record<AudioRunWorkflow, TranslationKey> = {
+  separate: "settings.apiKeys.audioApi.separate",
+  convert: "settings.apiKeys.audioApi.convert",
+  music: "settings.apiKeys.audioApi.music",
+  edit: "settings.apiKeys.audioApi.edit",
+};
+
+function Pill({
+  active,
+  onClick,
+  children,
+}: {
+  active: boolean;
+  onClick: () => void;
+  children: ReactNode;
+}) {
+  return (
+    <button
+      type="button"
+      onClick={onClick}
+      aria-pressed={active}
+      className={cn(
+        "rounded-full px-2.5 py-1 text-ui-11 font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
+        active
+          ? "hub-tab-toggle-pill text-foreground"
+          : "text-muted-foreground hover:text-foreground",
+      )}
+    >
+      {children}
+    </button>
+  );
+}
+
+export function AudioApiExamples({
+  apiKey,
+  useTunnel,
+  keylessScope = "off",
+  keylessExposure = null,
+}: {
+  apiKey?: string | null;
+  useTunnel: boolean;
+  keylessScope?: KeylessApiAccessScope;
+  keylessExposure?: KeylessApiAccessExposure | null;
+}) {
+  const t = useT();
+  const deviceType = usePlatformStore((s) => s.deviceType);
+  const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
+  const serverUrl = usePlatformStore((s) => s.serverUrl);
+  const setStoredTab = useSettingsPanelPrefsStore((s) => s.setApiAudioExample);
+  const setStoredLang = useSettingsPanelPrefsStore((s) => s.setApiExampleLang);
+  const setStoredOs = useSettingsPanelPrefsStore((s) => s.setApiExampleOs);
+  const [storedPrefs] = useState(() => useSettingsPanelPrefsStore.getState());
+  const [tab, setTab] = useState<AudioApiTab>(
+    AUDIO_API_TABS.find((id) => id === storedPrefs.apiAudioExample) ?? "speak",
+  );
+  const [run, setRun] = useState<AudioRunWorkflow>("separate");
+  const [lang, setLang] = useState<AudioApiLang>(
+    langFromStored(storedPrefs.apiExampleLang),
+  );
+  const [os, setOs] = useState<AudioApiOs>(
+    storedPrefs.apiExampleOs ?? (deviceType === "windows" ? "windows" : "unix"),
+  );
+  // null until /v1/models answers, so a slow or failed listing never claims nothing is downloaded.
+  const [models, setModels] = useState<AudioApiModel[] | null>(null);
+  const [autoSwitch, setAutoSwitch] = useState<boolean | null>(null);
+  const [copied, setCopied] = useState(false);
+  const [pageModel, setPageModel] = useState<{
+    example: AudioApiExample;
+    model: string;
+  } | null>(null);
+  const sectionRef = useRef<HTMLElement | null>(null);
+  const audioApiRequested = useSettingsDialogStore((s) => s.audioApiRequested);
+  const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
+
+  useEffect(() => {
+    if (!audioApiRequested) return;
+    const next = audioApiExampleFor(audioApiRequested.workflow);
+    setTab(next.tab);
+    if (next.run) setRun(next.run);
+    setPageModel(
+      audioApiRequested.model
+        ? {
+            example:
+              next.tab === "workflows" ? (next.run ?? "separate") : next.tab,
+            model: audioApiRequested.model,
+          }
+        : null,
+    );
+    useSettingsDialogStore.getState().consumeAudioApiRequest();
+  }, [audioApiRequested]);
+
+  useEffect(() => {
+    if (scrollTarget !== "api-keys-audio-api") return;
+    const section = sectionRef.current;
+    if (!section) return;
+    // Consumed only after the user scrolls: clearing it re-runs this effect, whose cleanup stops the pinning.
+    const pin = () => section.scrollIntoView({ block: "start" });
+    const observer = new ResizeObserver(pin);
+    observer.observe(section.parentElement ?? section);
+    const release = () => {
+      observer.disconnect();
+      useSettingsDialogStore
+        .getState()
+        .consumeScrollTarget("api-keys-audio-api");
+    };
+    const timer = window.setTimeout(release, 1500);
+    const events = ["wheel", "touchmove", "keydown"] as const;
+    for (const name of events) {
+      window.addEventListener(name, release, { passive: true });
+    }
+    return () => {
+      observer.disconnect();
+      window.clearTimeout(timer);
+      for (const name of events) window.removeEventListener(name, release);
+    };
+  }, [scrollTarget]);
+
+  useEffect(() => {
+    let cancelled = false;
+    listOpenAIAudioModels().then(
+      (listed) => !cancelled && setModels(listed),
+      () => undefined,
+    );
+    loadOpenAIAutoSwitchSettings().then(
+      (settings) => !cancelled && setAutoSwitch(settings.enabled),
+      () => undefined,
+    );
+    return () => {
+      cancelled = true;
+    };
+  }, []);
+
+  const origin = typeof window !== "undefined" ? window.location.origin : "";
+  const base =
+    useTunnel && cloudflareUrl ? cloudflareUrl : (serverUrl ?? origin);
+  const key = audioApiKey(apiKey, {
+    base,
+    tunnel: useTunnel && !!cloudflareUrl,
+    scope: keylessScope,
+    exposure: keylessExposure,
+  });
+  const example: AudioApiExample = tab === "workflows" ? run : tab;
+  const picked =
+    pageModel?.example === example &&
+    audioApiModelFits(models, pageModel.model, example)
+      ? pageModel.model
+      : models
+        ? pickAudioApiModel(models, example)
+        : null;
+  const model = picked ?? AUDIO_API_PLACEHOLDER_MODELS[example];
+  const snippet = useMemo(
+    () =>
+      buildAudioApiSnippet(example, {
+        base,
+        apiKey: key,
+        model,
+        lang,
+        os,
+      }),
+    [base, example, key, lang, model, os],
+  );
+  // Separation models are not in /v1/models, so an unpicked one says nothing about the disk.
+  const placeholder = models !== null && !picked && example !== "separate";

P2 Badge Warn when the separation snippet uses a stand-in model

When /v1/models completes without any downloaded separator and auto-switch is enabled, picked is null but this exception forces placeholder false, so the card presents HTDemucs as a runnable model with no warning even though the request will fail because it is not downloaded. Fresh evidence after the prior review is that audioModelsFromCatalog now retains audio-to-audio separator rows, making the comment's premise obsolete; separation can use the same models !== null && !picked check as every other workflow.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 6521364: separators are listed with audio_workflows now, so separation uses the same stand-in check as the other workflows.

Round 3: reviewed mirror 2826478ab (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/frontend/src/features/settings/components/audio-api-examples.tsx (on the mirror)

@@ -0,0 +1,344 @@
+// 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 { usePlatformStore } from "@/config/env";
+import { useT } from "@/i18n";
+import type { TranslationKey } from "@/i18n";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { Tick02Icon } from "@/lib/tick-icon";
+import { cn } from "@/lib/utils";
+import { Copy01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
+import type {
+  KeylessApiAccessExposure,
+  KeylessApiAccessScope,
+} from "../api/keyless-api-access";
+import { loadOpenAIAutoSwitchSettings } from "../api/openai-auto-switch";
+import {
+  type AudioApiModel,
+  listOpenAIAudioModels,
+} from "../api/openai-models";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+import { useSettingsPanelPrefsStore } from "../stores/settings-panel-prefs-store";
+import {
+  AUDIO_API_PLACEHOLDER_MODELS,
+  AUDIO_API_TABS,
+  AUDIO_RUN_WORKFLOWS,
+  type AudioApiExample,
+  type AudioApiLang,
+  type AudioApiOs,
+  type AudioApiTab,
+  type AudioRunWorkflow,
+  audioApiExampleFor,
+  audioApiKey,
+  audioApiModelFits,
+  audioLangToStore,
+  buildAudioApiSnippet,
+  langFromStored,
+  pickAudioApiModel,
+} from "./audio-api-snippets";
+import { HighlightedCode } from "./usage-examples";
+
+const LANGS: { id: AudioApiLang; label: string }[] = [
+  { id: "curl", label: "curl" },
+  { id: "python", label: "Python" },
+  { id: "javascript", label: "JavaScript" },
+];
+
+const TAB_LABEL: Record<AudioApiTab, TranslationKey> = {
+  speak: "settings.apiKeys.audioApi.speak",
+  clone: "settings.apiKeys.audioApi.clone",
+  transcribe: "settings.apiKeys.audioApi.transcribe",
+  workflows: "settings.apiKeys.audioApi.workflows",
+};
+
+const RUN_LABEL: Record<AudioRunWorkflow, TranslationKey> = {
+  separate: "settings.apiKeys.audioApi.separate",
+  convert: "settings.apiKeys.audioApi.convert",
+  music: "settings.apiKeys.audioApi.music",
+  edit: "settings.apiKeys.audioApi.edit",
+};
+
+function Pill({
+  active,
+  onClick,
+  children,
+}: {
+  active: boolean;
+  onClick: () => void;
+  children: ReactNode;
+}) {
+  return (
+    <button
+      type="button"
+      onClick={onClick}
+      aria-pressed={active}
+      className={cn(
+        "rounded-full px-2.5 py-1 text-ui-11 font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
+        active
+          ? "hub-tab-toggle-pill text-foreground"
+          : "text-muted-foreground hover:text-foreground",
+      )}
+    >
+      {children}
+    </button>
+  );
+}
+
+export function AudioApiExamples({
+  apiKey,
+  useTunnel,
+  keylessScope = "off",
+  keylessExposure = null,
+}: {
+  apiKey?: string | null;
+  useTunnel: boolean;
+  keylessScope?: KeylessApiAccessScope;
+  keylessExposure?: KeylessApiAccessExposure | null;
+}) {
+  const t = useT();
+  const deviceType = usePlatformStore((s) => s.deviceType);
+  const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
+  const serverUrl = usePlatformStore((s) => s.serverUrl);
+  const setStoredTab = useSettingsPanelPrefsStore((s) => s.setApiAudioExample);
+  const setStoredLang = useSettingsPanelPrefsStore((s) => s.setApiExampleLang);
+  const setStoredOs = useSettingsPanelPrefsStore((s) => s.setApiExampleOs);
+  const [storedPrefs] = useState(() => useSettingsPanelPrefsStore.getState());
+  const [tab, setTab] = useState<AudioApiTab>(
+    AUDIO_API_TABS.find((id) => id === storedPrefs.apiAudioExample) ?? "speak",
+  );
+  const [run, setRun] = useState<AudioRunWorkflow>("separate");
+  const [lang, setLang] = useState<AudioApiLang>(
+    langFromStored(storedPrefs.apiExampleLang),
+  );
+  const [os, setOs] = useState<AudioApiOs>(
+    storedPrefs.apiExampleOs ?? (deviceType === "windows" ? "windows" : "unix"),
+  );
+  // null until /v1/models answers, so a slow or failed listing never claims nothing is downloaded.
+  const [models, setModels] = useState<AudioApiModel[] | null>(null);
+  const [autoSwitch, setAutoSwitch] = useState<boolean | null>(null);
+  const [copied, setCopied] = useState(false);
+  const [pageModel, setPageModel] = useState<{
+    example: AudioApiExample;
+    model: string;
+  } | null>(null);
+  const sectionRef = useRef<HTMLElement | null>(null);
+  const audioApiRequested = useSettingsDialogStore((s) => s.audioApiRequested);
+  const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
+
+  useEffect(() => {
+    if (!audioApiRequested) return;
+    const next = audioApiExampleFor(audioApiRequested.workflow);
+    setTab(next.tab);
+    if (next.run) setRun(next.run);
+    setPageModel(
+      audioApiRequested.model
+        ? {
+            example:
+              next.tab === "workflows" ? (next.run ?? "separate") : next.tab,
+            model: audioApiRequested.model,
+          }
+        : null,
+    );
+    useSettingsDialogStore.getState().consumeAudioApiRequest();
+  }, [audioApiRequested]);
+
+  useEffect(() => {
+    if (scrollTarget !== "api-keys-audio-api") return;
+    const section = sectionRef.current;
+    if (!section) return;
+    // Consumed only after the user scrolls: clearing it re-runs this effect, whose cleanup stops the pinning.
+    const pin = () => section.scrollIntoView({ block: "start" });
+    const observer = new ResizeObserver(pin);
+    observer.observe(section.parentElement ?? section);
+    const release = () => {
+      observer.disconnect();
+      useSettingsDialogStore
+        .getState()
+        .consumeScrollTarget("api-keys-audio-api");
+    };
+    const timer = window.setTimeout(release, 1500);
+    const events = ["wheel", "touchmove", "keydown"] as const;
+    for (const name of events) {
+      window.addEventListener(name, release, { passive: true });
+    }
+    return () => {
+      observer.disconnect();
+      window.clearTimeout(timer);
+      for (const name of events) window.removeEventListener(name, release);
+    };
+  }, [scrollTarget]);
+
+  useEffect(() => {
+    let cancelled = false;
+    listOpenAIAudioModels().then(
+      (listed) => !cancelled && setModels(listed),
+      () => undefined,
+    );
+    loadOpenAIAutoSwitchSettings().then(
+      (settings) => !cancelled && setAutoSwitch(settings.enabled),
+      () => undefined,
+    );
+    return () => {
+      cancelled = true;
+    };
+  }, []);
+
+  const origin = typeof window !== "undefined" ? window.location.origin : "";
+  const base =
+    useTunnel && cloudflareUrl ? cloudflareUrl : (serverUrl ?? origin);
+  const key = audioApiKey(apiKey, {
+    base,
+    tunnel: useTunnel && !!cloudflareUrl,
+    scope: keylessScope,
+    exposure: keylessExposure,
+  });
+  const example: AudioApiExample = tab === "workflows" ? run : tab;
+  const picked =
+    pageModel?.example === example &&
+    audioApiModelFits(models, pageModel.model, example)
+      ? pageModel.model
+      : models
+        ? pickAudioApiModel(models, example)
+        : null;
+  const model = picked ?? AUDIO_API_PLACEHOLDER_MODELS[example];
+  const snippet = useMemo(
+    () =>
+      buildAudioApiSnippet(example, {
+        base,
+        apiKey: key,
+        model,
+        lang,
+        os,
+      }),
+    [base, example, key, lang, model, os],
+  );
+  const placeholder = models !== null && !picked;
+  const needsLoad =
+    !placeholder &&
+    autoSwitch === false &&
+    models !== null &&
+    !models.some((m) => m.id === model && m.loaded);

P2 Badge Exclude transcription from the auto-switch warning

When the Transcribe example selects a downloaded but currently unloaded STT model and general model auto-switch is disabled, this condition shows that the request cannot load the model. However, /v1/audio/transcriptions unconditionally performs its own implicit sidecar load through _stt_lifecycle().load_stt (studio/backend/routes/inference.py:25103-25122), independently of the general auto-switch setting. The generated transcription snippet is therefore runnable while the card incorrectly instructs the user to enable auto-switch or load the model manually.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in de7167a: Transcribe no longer shows the auto-switch line, since that route loads its model itself.

@danielhanchen

Copy link
Copy Markdown
Member

Review record for this PR, continued from the comment above (part 2 of 2).

Round 3: reviewed mirror 2826478ab (no equivalent commit found on this PR) (continued)

chatgpt-codex-connector[bot] on studio/frontend/src/features/settings/components/audio-api-examples.tsx (on the mirror)

@@ -0,0 +1,344 @@
+// 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 { usePlatformStore } from "@/config/env";
+import { useT } from "@/i18n";
+import type { TranslationKey } from "@/i18n";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { Tick02Icon } from "@/lib/tick-icon";
+import { cn } from "@/lib/utils";
+import { Copy01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
+import type {
+  KeylessApiAccessExposure,
+  KeylessApiAccessScope,
+} from "../api/keyless-api-access";
+import { loadOpenAIAutoSwitchSettings } from "../api/openai-auto-switch";
+import {
+  type AudioApiModel,
+  listOpenAIAudioModels,
+} from "../api/openai-models";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+import { useSettingsPanelPrefsStore } from "../stores/settings-panel-prefs-store";
+import {
+  AUDIO_API_PLACEHOLDER_MODELS,
+  AUDIO_API_TABS,
+  AUDIO_RUN_WORKFLOWS,
+  type AudioApiExample,
+  type AudioApiLang,
+  type AudioApiOs,
+  type AudioApiTab,
+  type AudioRunWorkflow,
+  audioApiExampleFor,
+  audioApiKey,
+  audioApiModelFits,
+  audioLangToStore,
+  buildAudioApiSnippet,
+  langFromStored,
+  pickAudioApiModel,
+} from "./audio-api-snippets";
+import { HighlightedCode } from "./usage-examples";
+
+const LANGS: { id: AudioApiLang; label: string }[] = [
+  { id: "curl", label: "curl" },
+  { id: "python", label: "Python" },
+  { id: "javascript", label: "JavaScript" },
+];
+
+const TAB_LABEL: Record<AudioApiTab, TranslationKey> = {
+  speak: "settings.apiKeys.audioApi.speak",
+  clone: "settings.apiKeys.audioApi.clone",
+  transcribe: "settings.apiKeys.audioApi.transcribe",
+  workflows: "settings.apiKeys.audioApi.workflows",
+};
+
+const RUN_LABEL: Record<AudioRunWorkflow, TranslationKey> = {
+  separate: "settings.apiKeys.audioApi.separate",
+  convert: "settings.apiKeys.audioApi.convert",
+  music: "settings.apiKeys.audioApi.music",
+  edit: "settings.apiKeys.audioApi.edit",
+};
+
+function Pill({
+  active,
+  onClick,
+  children,
+}: {
+  active: boolean;
+  onClick: () => void;
+  children: ReactNode;
+}) {
+  return (
+    <button
+      type="button"
+      onClick={onClick}
+      aria-pressed={active}
+      className={cn(
+        "rounded-full px-2.5 py-1 text-ui-11 font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
+        active
+          ? "hub-tab-toggle-pill text-foreground"
+          : "text-muted-foreground hover:text-foreground",
+      )}
+    >
+      {children}
+    </button>
+  );
+}
+
+export function AudioApiExamples({
+  apiKey,
+  useTunnel,
+  keylessScope = "off",
+  keylessExposure = null,
+}: {
+  apiKey?: string | null;
+  useTunnel: boolean;
+  keylessScope?: KeylessApiAccessScope;
+  keylessExposure?: KeylessApiAccessExposure | null;
+}) {
+  const t = useT();
+  const deviceType = usePlatformStore((s) => s.deviceType);
+  const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
+  const serverUrl = usePlatformStore((s) => s.serverUrl);
+  const setStoredTab = useSettingsPanelPrefsStore((s) => s.setApiAudioExample);
+  const setStoredLang = useSettingsPanelPrefsStore((s) => s.setApiExampleLang);
+  const setStoredOs = useSettingsPanelPrefsStore((s) => s.setApiExampleOs);
+  const [storedPrefs] = useState(() => useSettingsPanelPrefsStore.getState());
+  const [tab, setTab] = useState<AudioApiTab>(
+    AUDIO_API_TABS.find((id) => id === storedPrefs.apiAudioExample) ?? "speak",
+  );
+  const [run, setRun] = useState<AudioRunWorkflow>("separate");
+  const [lang, setLang] = useState<AudioApiLang>(
+    langFromStored(storedPrefs.apiExampleLang),
+  );
+  const [os, setOs] = useState<AudioApiOs>(
+    storedPrefs.apiExampleOs ?? (deviceType === "windows" ? "windows" : "unix"),
+  );
+  // null until /v1/models answers, so a slow or failed listing never claims nothing is downloaded.
+  const [models, setModels] = useState<AudioApiModel[] | null>(null);
+  const [autoSwitch, setAutoSwitch] = useState<boolean | null>(null);
+  const [copied, setCopied] = useState(false);
+  const [pageModel, setPageModel] = useState<{
+    example: AudioApiExample;
+    model: string;
+  } | null>(null);
+  const sectionRef = useRef<HTMLElement | null>(null);
+  const audioApiRequested = useSettingsDialogStore((s) => s.audioApiRequested);
+  const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
+
+  useEffect(() => {
+    if (!audioApiRequested) return;
+    const next = audioApiExampleFor(audioApiRequested.workflow);
+    setTab(next.tab);
+    if (next.run) setRun(next.run);
+    setPageModel(
+      audioApiRequested.model
+        ? {
+            example:
+              next.tab === "workflows" ? (next.run ?? "separate") : next.tab,
+            model: audioApiRequested.model,
+          }
+        : null,
+    );
+    useSettingsDialogStore.getState().consumeAudioApiRequest();
+  }, [audioApiRequested]);
+
+  useEffect(() => {
+    if (scrollTarget !== "api-keys-audio-api") return;
+    const section = sectionRef.current;
+    if (!section) return;
+    // Consumed only after the user scrolls: clearing it re-runs this effect, whose cleanup stops the pinning.
+    const pin = () => section.scrollIntoView({ block: "start" });
+    const observer = new ResizeObserver(pin);
+    observer.observe(section.parentElement ?? section);
+    const release = () => {
+      observer.disconnect();
+      useSettingsDialogStore
+        .getState()
+        .consumeScrollTarget("api-keys-audio-api");
+    };
+    const timer = window.setTimeout(release, 1500);
+    const events = ["wheel", "touchmove", "keydown"] as const;
+    for (const name of events) {
+      window.addEventListener(name, release, { passive: true });
+    }
+    return () => {
+      observer.disconnect();
+      window.clearTimeout(timer);
+      for (const name of events) window.removeEventListener(name, release);
+    };
+  }, [scrollTarget]);
+
+  useEffect(() => {
+    let cancelled = false;
+    listOpenAIAudioModels().then(
+      (listed) => !cancelled && setModels(listed),
+      () => undefined,
+    );
+    loadOpenAIAutoSwitchSettings().then(
+      (settings) => !cancelled && setAutoSwitch(settings.enabled),
+      () => undefined,
+    );

P2 Badge Refresh the warning when auto-switch is toggled

When an owner changes Model auto-switch in this same API Keys tab, ModelAutoSwitchSection saves the new value, but this one-shot effect never updates autoSwitch afterward. Consequently the Audio API card continues showing the old warning state until it is unmounted and reopened—for example, disabling auto-switch leaves an unloaded workflow model presented without the required warning. Share the updated setting or refetch/subscribe after changes.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in de7167a: the card subscribes to auto-switch settings answers, so the switch in the same tab updates it.

Round 4: reviewed mirror 563474083 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 5634740837

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 563474083 (no equivalent commit found on this PR).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 7, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 7, 2026
Share the Secure HTTPS switch through tunnel-preference so the MCP section follows it too.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-14T17:00:40.395300Z e6b6572 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6be7d63134

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

${uploads.map((item) => `${item.name} = upload(${j(item.file)})`).join("\n")}${uploads.length ? "\n" : ""}result = post("/v1/audio/run", json=${render(body, "python")})

# ${save}
for clip in result["clips"]:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Save the inline audio fallback from workflow runs

When /v1/audio/run succeeds but cannot persist the generated clip (for example with a full or read-only gallery), _audio_run_response deliberately returns clips: [] and the WAV as audio.data (studio/backend/routes/inference.py:23365-23368). This loop—and the JavaScript, PowerShell, and bash branches below—only handles clips, so every copied workflow example exits without saving the successfully generated output exactly when that fallback is used; decode and write the inline audio payload when it is present.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: the inline audio fallback only appears when _persist_tts_clip raises (a failed disk write on the server), so it is a degraded host state rather than a normal run, and the copy-ready examples stay focused on the normal clips path.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6be7d63134

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +182 to +185
loadOpenAIAutoSwitchSettings().then(
(settings) => !cancelled && setAutoSwitch(settings.enabled),
() => undefined,
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle owner-only auto-switch reads for managed users

For any managed non-owner, this call returns 403 because /openai-auto-switch is on _owner_settings_router (studio/backend/routes/settings.py:241,2314), yet AudioApiExamples mounts outside the owner guard (api-keys-tab.tsx:193-221). Its rejection is swallowed and leaves autoSwitch null, while needsLoad only warns for false; with default-off switching and only a downloaded/unloaded audio model, the card therefore offers a model-specific command the backend rejects as not loaded without the intended load warning. Read this global state through a route available to API users or treat this denial conservatively.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: this only affects managed non-owner accounts and only hides an advisory line; the generated request is the same and is correct whenever the owner has auto-switch on.

The OpenAI SDK sends fs.createReadStream as a chunked multipart body, which Studio refuses with 411 Content-Length required. toFile reads the clip so the request carries a length.
A model handed over while it was still downloading, or loaded and unloaded later, never reached the card, which read /v1/models once per mount. Relist on the chat examples' pace: 15 s until something is resident, 60 s after.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 14, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 14, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: e6b6572fdf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit d9214ae into unslothai:main Oct 14, 2026
danielhanchen added a commit that referenced this pull request Oct 14, 2026
…th since the last raise (#13752)

* Studio frontend: raise the startup bundle budget by the measured growth since the last raise

* Bundle budget: include #12821 and #13630, which merged while this was open
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants