Skip to content

fix(studio): add audio page with tts/stt create tab, train tab, and openai audio endpoints - #7984

Merged
danielhanchen merged 132 commits into
unslothai:mainfrom
mahiatlinux:feat/studio-audio-page
Aug 11, 2026
Merged

danielhanchen merged 132 commits into
unslothai:mainfrom
mahiatlinux:feat/studio-audio-page

Conversation

@mahiatlinux

Copy link
Copy Markdown
Contributor

Adds an Audio page to Studio in the same shape as Images: a Create tab for inference and a Train tab for LoRA fine-tuning, plus OpenAI-compatible audio endpoints.

What this does

Create tab. Two modes with a segmented switch in the settings rail: Speak (text to speech) and Transcribe (speech to text). A capability line under the model selector always states what the selected model does ("Text-to-speech · snac" / "Speech-to-text"), so TTS vs STT is never ambiguous. Picking a TTS model loads it into the main inference slot via /api/inference/load; picking an STT model drives the existing dictation sidecars (/audio/stt/*), so a TTS model and an STT model can be resident at the same time. Generated clips land in a persistent gallery with playback, download, and delete. Transcripts are deliberately not persisted (copy / download .txt only).

Train tab. A focused audio LoRA panel driving the generic /api/train/* API, which already carries the snac/csm/bicodec/dac/whisper trainer branches: curated base picker (Orpheus, Sesame CSM, Spark, Oute, Llasa, Whisper), HF dataset input with column-role overrides for _resolve_audio_columns, epochs/LR/rank plus batch and max-steps in Advanced, live loss and grad-norm charts from /api/train/status, and a deploy-to-create button that loads the finished checkpoint back into Speak.

OpenAI endpoints. POST /v1/audio/speech (CreateSpeech shape, raw WAV bytes out; voice/speed accepted and ignored since no backend has voice plumbing) and POST /v1/audio/transcriptions (multipart, json/text response formats, whisper-1 maps to the sidecar default). Both are dual-mounted at /api/inference like /v1/images/generations. The TTS core of /audio/generate is extracted into _generate_tts_wav so both routes share it and persist to the new gallery.

Gallery. core/inference/audio_gallery.py stores wav + json sidecar pairs (video_gallery's model: atomic staged rename, sidecar-ownership guards so a foreign wav can never be listed, served, or destroyed). Routes: GET/DELETE /api/inference/audio/gallery(/{id}/file).

Catalog. AUDIO_CATALOG in model-catalog.ts with a per-group task tag ("tts" | "stt") driving the mode interlock; the chat picker now reroutes text-to-speech / automatic-speech-recognition picks to /audio the same way diffusion picks route to /images.

Shell. Persistent keep-alive mount in __root (like Images/Video), /audio allowed on chat-only hosts (GGUF TTS and whisper.cpp are CPU-capable), sidebar row under "More" below Video, nav registry + backend personalization defaults extended, nav label added to all 12 locales.

Cross-cutting touches

  • llama_keepwarm: /audio/speech added to the inference suffixes so a generation holds the model.
  • main.py: multipart body cap for /v1/audio/transcriptions (upload headroom over STT_AUDIO_RAW_MAX_BYTES).
  • routes/settings.py: sidebarNav accepts and defaults the audio id (a missing id 422s the whole personalization PUT).

Tests

  • test_audio_gallery.py: round-trips, ordering, pagination, unsafe ids, orphan-pair skipping, unlink-order guarantees, atomic-save rollback.
  • test_openai_audio_speech_route.py / test_openai_audio_transcriptions_route.py: route wiring with a faked TTS/STT core: raw wav shape, gallery persist (and persist-failure tolerance), response_format validation, whisper-1 mapping, error status passthrough.
  • test_middleware.py: both /v1 paths on the body-protected surface, transcriptions cap assertion.
  • test_personalization_settings.py + sidebar-nav-backend-parity: audio id in the shipped layout fixtures.

All backend suites touched here pass locally (105 tests), plus the frontend checks: catalog:check, i18n strict parity, typecheck, node tests (463), and a production build.

Not verified (no GPU on the dev machine)

Real TTS generation, transcription, and training runs were not executed. Manual e2e on a GPU host:

  1. /audio → pick Orpheus GGUF → Speak → type a sentence → Generate; clip plays and appears in the gallery; leave the tab and return, state survives.
  2. Pick Whisper Large v3 Turbo → page flips to Transcribe → record a clip → transcript appears; chat dictation still works afterwards.
  3. curl -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{"input":"hello"}' http://localhost:PORT/v1/audio/speech -o out.wav then curl -H "Authorization: Bearer $KEY" -F [email protected] http://localhost:PORT/v1/audio/transcriptions.
  4. Train tab → Orpheus base + MrDragonFox/Elise → run starts, loss chart updates, deploy-to-create loads the adapter.

mahiatlinux and others added 2 commits August 6, 2026 15:59
…nai audio endpoints

new /audio page mirroring images: create tab with speak (tts via the main
inference slot) and transcribe (stt via the dictation sidecars) modes, an
always-visible capability line so the loaded model's task is never ambiguous,
and a train tab driving the generic /api/train/* audio branches.

backend: audio_gallery.py persists tts clips as wav + json sidecar pairs;
/v1/audio/speech (openai createSpeech shape, raw wav out) and
/v1/audio/transcriptions (multipart, json/text) on the dual-mounted router;
gallery list/file/delete/clear on the studio router; the tts core of
/audio/generate extracted into _generate_tts_wav so both routes share it and
persist clips; keep-warm suffix and transcriptions body cap wired.

frontend: AUDIO_CATALOG (orpheus, csm, spark, oute, llasa as tts; whisper and
qwen3-asr as stt) painted into the model selector with a per-group task tag,
chat-picker speech picks rerouting to /audio, persistent mount in __root,
sidebar row under more below video, nav registry + personalization defaults,
and the audio nav label in all 12 locales.

tests: audio gallery unit tests, speech/transcriptions route round-trips with
a faked tts/stt core, middleware body-cap and /v1 surface additions, and the
sidebar parity fixtures extended for the audio id.
@shimmyshimmer
shimmyshimmer marked this pull request as ready for review August 6, 2026 09:55

@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: f4ba3e0be6

ℹ️ 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 thread studio/backend/routes/inference.py Outdated
Comment on lines +19475 to +19476
records = await asyncio.to_thread(
audio_gallery.list_audio, limit + 1, offset, valid = _valid_gallery_audio

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Scope audio gallery records to the authenticated subject

On installations with more than one authenticated username, the gallery routes authenticate current_subject but never use it when listing records; the persisted metadata also contains no owner. As a result, one user can see every other user's TTS prompts and recordings, fetch their WAV files by ID, and use the unscoped delete or clear routes to remove them. Persist an owner and apply the subject filter consistently to list, serve, delete, and clear operations.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Not actionable under the supported-input bar: Studio has one bootstrap user and no user-creation path, so this requires manual database mutation.

…earchable train pickers

Detection: _AUDIO_TOKEN_PATTERNS is first-match-wins, and audio_vlm's generic
<|audio|> was tested before the codec fingerprints. Orpheus carries both that
token and 28k <custom_token_N> SNAC codes, so it typed as audio_vlm, leaving
is_audio False and the Audio page refusing a model that had loaded fine. Codec
patterns now go first; Orpheus reports snac.

Errors: safe_error_detail flattened "Text-to-speech is not supported on the MLX
backend yet" into "An internal error occurred", so a safetensors TTS load on
Apple Silicon failed with no reason. Capability answers are now a typed
AudioBackendUnsupportedError tagged by the worker and returned as 501 with the
message and the GGUF workaround.

Tests: /audio/generate persists every clip, so suites driving it with a fake TTS
core wrote silent wavs into the real gallery, where the page listed them. An
autouse conftest fixture redirects studio_root.

Picker: Recommended seeds curated rows in the order given, so a fixed order left
every STT row below the fold on Transcribe. The active mode's task now leads.
Adds Whisper Tiny/Base, which both sidecars already carry. Audio opts into
community models via includeCommunity: non-unsloth TTS/ASR appear in search and
trending ones below the unsloth rows, and Search Hub is restored for that case.

Train: base model and dataset are search-as-you-type over the Hub with curated
entries pinned; default dataset is Etherll/kaira (audio + text columns, no
overrides). Panel is sectioned model/data/parameters with a run preview and its
left edge tracks the header selector.
@shimmyshimmer

Copy link
Copy Markdown
Member

Merged main in and pushed some fixes on top. Conflict was just the doc comment in media-page-link.tsx, where main had widened it to cover the image-training link while this branch narrowed it to media pages. Kept main's wording and added Audio, since both callers exist on the merged tree.

Tested on Apple Silicon, which surfaced a few things worth flagging.

Orpheus was detected as the wrong audio type

_AUDIO_TOKEN_PATTERNS is first-match-wins, and audio_vlm was tested before the codec fingerprints. Orpheus carries a stray <|audio|> alongside its 28k <custom_token_N> SNAC codes, so it matched audio_vlm first. mlx_inference.py sets is_audio = audio_type != "audio_vlm", so is_audio came back False and the Audio page rejected a model that had loaded fine:

audio_type = 'audio_vlm'   is_audio = False   ->  "The loaded model is not a TTS audio model."
audio_type = 'snac'        is_audio = True    ->  "Text-to-speech - snac"

Codec patterns now go first. Neither Gemma carries a codebook so nothing shadows them, and I added cases for the mixed-signal repos.

Generation errors said nothing useful

With detection fixed, generating still failed, but with An internal error occurred. The real reason was Text-to-speech is not supported on the MLX backend yet from the worker, flattened by safe_error_detail. That is correct for a crash and wrong for a capability answer, where the reason is the entire reply.

Capability answers are now a typed AudioBackendUnsupportedError, tagged by the worker with a shared code so nothing matches on prose, and returned as 501:

HTTP=501
"Text-to-speech is not supported on the MLX backend yet. Load this model's GGUF
 build instead -- llama.cpp carries the snac/bicodec/dac decoders."

Worth knowing: the safetensors Orpheus cannot generate on Apple Silicon at all, since MLX has no TTS branch. The GGUF build works, verified end to end (114 KB WAV, 24 kHz mono, 2.4 s, persisted to the gallery).

Tests were writing into the real gallery

/audio/generate persists every clip, so the suites driving it with a fake TTS core wrote real pairs into studio_root()/audio. They showed up in the Audio page as silent clips named after fixtures like some/custom-tts. test_audio_gallery redirected studio_root itself, but nothing stopped the others. Added an autouse conftest fixture so no suite can leak. Gallery count held at 12 across a 106 test run.

Picker

Recommended seeds curated rows in the order it is handed them and the list scrolls, so with TTS fixed first every STT row sat below the fold on Transcribe, the one mode where they are the only loadable picks. Both unslothai/Qwen3-ASR models were in that group. The active mode's task now leads, so they come up at 1 and 2 on Transcribe. Also added Whisper Tiny and Base, which GGML_STT_REPOS and STT_MODEL_REPOS already carry and Voice settings already lists.

Audio now opts into community models through includeCommunity. Non-unsloth TTS/ASR repos appear after the unsloth ones in search, and trending ones continue below the unsloth rows instead of dead-ending. Opt-in per page, so Images and Video are unchanged. Community rows keep their owner/ prefix, otherwise they read as unsloth uploads. Search Hub is back for this case, since the picker is no longer self-contained.

One limitation: eligibility is judged on the HF pipeline tag, because the real test is the checkpoint's tokenizer and that needs the download first. ONNX, OpenVINO, TFLite and CoreML exports are dropped by name, but something like pyannote/speaker-diarization is tagged ASR and will still show up.

Train tab

Base model and dataset were a fixed Select of seven repos and a bare text input, so training anything else meant knowing the repo id by heart. Both are search-as-you-type over the Hub now, with curated entries pinned on top. Base search excludes GGUF since the trainer rejects it.

Default dataset is Etherll/kaira, which has audio and text columns and maps with no overrides. MrDragonFox/Elise stays pinned under it. Panel is grouped into model, data and parameters with a run preview line above the button, and its left edge now tracks the header selector via the page inset instead of a flat px-8.

Checks

Frontend typecheck, catalog:check, i18n strict across 12 locales, 476 node tests and a production build all pass. Backend is 684 passed on the audio, stt, whisper, middleware and personalization sweep.

Two failures there (test_whisper_plan_eligible_when_behind, test_mlx_vlm_renderer_audio_marker_contract) reproduce on a clean origin/main checkout, so they are not from this branch.

The train panel restyle and the alignment change were reasoned from the CSS rather than eyeballed, so those two are worth a look before merge.

pre-commit-ci Bot and others added 2 commits August 6, 2026 11:21
Audio fine-tuning was a second, thinner copy of a flow the Train page already
owns. Removes the panel and its charts and Hub comboboxes; the Train pill now
toasts that Unsloth trains TTS and STT there, given the right base and a dataset
with audio plus transcript columns, and navigates to /studio.

Also stops TTS picks dead-ending on Mac. Safetensors loads through MLX, which has
no TTS branch, so the model loaded and every generation 501'd. A TTS pick with a
GGUF build published now loads that instead and says why, since llama.cpp is the
only backend carrying the snac/bicodec/dac decoders. Picks with no GGUF still get
the 501, which now explains itself.
@shimmyshimmer

Copy link
Copy Markdown
Member

Dropped the audio Train panel. It was a second, thinner copy of a flow the Train page already owns, so the Train pill now toasts that Unsloth fine-tunes TTS and STT there, given the right base and a dataset with audio plus transcript columns, and navigates to /studio. Removed audio-train-panel.tsx, audio-charts.tsx and hub-comboboxes.tsx with it. The whole train/ directory was self-contained, so nothing else referenced them.

Also fixed the dead end behind the MLX error rather than just reporting it. On a Mac, a safetensors TTS pick loads through MLX, which has no TTS branch at all, so the model loaded and every generation 501'd. A TTS pick whose group publishes a GGUF build now loads that instead and says why in a toast, since llama.cpp is the only backend carrying the snac/bicodec/dac decoders.

Verified on the GGUF path after the change:

POST /api/inference/audio/generate -> 200
model=unsloth/orpheus-3b-0.1-ft-GGUF  format=wav  rate=24000

Picks with no GGUF published (csm-1b, for one) still get the 501, which at least explains itself now. STT is untouched since it runs on the sidecar rather than the main slot.

Checks: typecheck, catalog:check, i18n strict, 477 node tests and a production build pass. Backend is 684 passed on the audio, stt, whisper, middleware and personalization sweep, with the same two main failures as before.

@shimmyshimmer

Copy link
Copy Markdown
Member

@codex review

…page links

Generate audio and Transcribe now use the same heading block as the Images and
Video Create panes from unslothai#7986: text-xl with leading-none, an 18px icon on the
heading line, and a text-xs line under it.

Also drops the Images and Video links from the header. They belong between the
two visual pages; audio is a different kind of output, so the row was noise here.

@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: 2ede19497a

ℹ️ 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".

.filter((r) => !r.id.toLowerCase().startsWith("unsloth/"))
.filter((r) => isLoadableCommunityRepo(r.id))
.filter((r) => !above.has(r.id.toLowerCase()))
.filter(keep)

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 Allow non-GGUF community audio checkpoints in Recommended

When the Audio picker is opened with an empty search, every community safetensors TTS or ASR result fails this keep filter because task-scoped rows must be GGUF or an artifact in the curated catalog. Consequently, enabling community models still hides ordinary third-party Whisper and TTS checkpoints from the Recommended browser, even though the Audio runtime supports arbitrary publishers; these models appear only if the user already knows what to search for.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Intentional policy: Audio uses search-only community discovery, keeping curated models in Recommended while third-party checkpoints remain searchable.

…page links

History rows were a single button with no per-row actions, so deleting one clip
meant selecting it first and using the player's buttons. Each row now carries a
dots menu (use text again, copy text, download WAV, delete), revealed on hover,
focus or while open. The row becomes a shell div since the trigger is a button
and cannot nest inside one.

Downloading from a row fetches the clip bytes on demand: only the selected clip
has them cached.

Removes the Audio link from the Images and Video headers, matching the Audio
page dropping its links to them.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Community models in the picker introduced most of these.

- Route uncurated ASR picks to the STT sidecar. audioTaskFor returns null for a
  repo outside AUDIO_CATALOG, so community Whisper repos loaded into the TTS
  slot. Picks now carry their Hub pipeline tag and fall back to it.
- Let community safetensors into Recommended. The curated-artifact clause in
  keep() can never pass for a community row, so third-party TTS and ASR
  checkpoints were browse-invisible. Community rows use the rest of the gate.
- Feed the community listings into resultGgufIds, so a tag-only GGUF repo opens
  the variant expander instead of loading as safetensors.
- Stop recording when the page goes inactive. The page stays mounted, so the
  unmount cleanup never ran and the mic stayed hot after navigating away.
- Keep generated audio when the gallery write fails. Persistence is best-effort
  server-side and still returns the WAV; the page now plays it.
- Guard gallery pagination with an in-flight flag. Repeated scrolls reused one
  offset and appended the same page, duplicating clips and React keys.
- Select the mtmd engine for Qwen3-ASR in /v1/audio/transcriptions. Whisper ids
  are shared with the Transformers sidecar, so those keep the default.
- Persist TTS clips via asyncio.to_thread, matching the image gallery routes.
- Reword the MLX hint: only Orpheus publishes a GGUF build, so it now names the
  host as the general fix and GGUF as the conditional one.
@shimmyshimmer

Copy link
Copy Markdown
Member

Went through the Codex review. Nine of the thirteen findings hold up and are fixed; three are stale and one I am leaving deliberately. Notes on each below, since a few needed checking before I trusted them either way.

Fixed

Most of these trace back to letting community models into the audio picker.

Uncurated ASR picks loaded into the TTS slot (P1). Correct. audioTaskFor returns null for anything outside AUDIO_CATALOG, so a community Whisper repo fell through to the TTS branch. Picks now carry their Hub pipeline tag and the page falls back to it when the catalog has no entry.

Community safetensors were browse-invisible (P2). Correct, and worse than it reads: the keep gate ends in (!task || r.isGguf || artifactForRepoId(...)), and a community row can never satisfy the catalog clause, so every third-party safetensors TTS or ASR checkpoint was dropped from Recommended. Community rows now use the rest of the gate without that clause.

Tag-only GGUF repos misclassified (P2). Correct. resultGgufIds read only the two unsloth searches, so a community repo whose GGUF status comes from Hub metadata rather than a -GGUF suffix rendered as safetensors and loaded directly instead of opening the variant expander. Both community listings now feed it.

Recording continued after leaving the page (P1). Correct and the reasoning is exact: RootLayout keeps AudioPage mounted, so the unmount-only cleanup never fired and the mic stayed live after navigating away. Cleanup now also runs when active goes false.

Generated audio discarded when persistence fails (P2). Correct. The backend treats the gallery write as best-effort and still returns the WAV, but the page threw the response away and rendered from a gallery refresh. It now keeps the returned audio and plays it, labelled as unsaved.

Pagination race (P2). Correct. loadMore had no in-flight guard, so repeated scroll events near the bottom each read the same galleryCache.clips.length and appended the same page. Guarded with a ref.

Transcriptions ignored the engine (P2). Correct. /v1/audio/transcriptions passed no engine, so _resolve_stt_engine defaulted to Transformers and rejected Qwen3-ASR. I narrowed the fix from what was suggested: only the mtmd-only ids are forced. Whisper ids are shared with the Transformers sidecar and work there, so forcing those would have changed working behaviour for no reason. Verified live:

model=qwen3-asr-0.6b -> reaches the mtmd sidecar (409 not downloaded)
model=small          -> unchanged, still the default engine

Persistence on the event loop (P2). Correct, including the claim that the image gallery routes already use asyncio.to_thread. Both TTS routes now do too.

The MLX hint named a build that may not exist (P2). Correct. I checked the Hub: of the curated TTS families only Orpheus publishes a GGUF repo, so telling a CSM or Llasa user to load "this model's GGUF build" was a dead end. Reworded to lead with the host and treat GGUF as conditional:

Text-to-speech is not supported on the MLX backend yet. Run it on a non-MLX host,
or load a GGUF build of it if one is published -- llama.cpp carries the
snac/bicodec/dac decoders.

Stale

Three findings were written against commits before the audio Train panel was removed, and the code they point at no longer exists: deploying Whisper checkpoints as TTS, offering deploy for stopped runs, and the chat-only guard exposing a training workspace on /audio. The panel, its charts and its comboboxes are gone and the Train pill navigates to /studio. I did update two comments in __root.tsx that still mentioned training state.

Not fixing here

Scoping gallery records to the authenticated subject (P1). The concern is real, but it is not something this PR introduced: the image and video galleries have the same shape, with no owner in the persisted metadata and no subject filter on list, serve, delete or clear. Fixing it for audio alone would leave the three inconsistent, and doing it properly means a metadata schema change plus a migration across all three. Worth its own PR rather than being smuggled into this one.

Checks

Typecheck, catalog:check, i18n strict, 687 node tests and a production build pass. Backend is 691 passed on the audio, stt, whisper, middleware and personalization sweep, with the same three failures that reproduce on a clean main checkout.

Added audio-community-pick-routing.test.ts covering the ASR routing fallback and the curated-artifact gate, plus two cases in the transcriptions route tests for the engine selection.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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

search: { model: id, quant: meta.ggufFilename ?? undefined },

P2 Badge Preserve the audio task across the route handoff

For an uncatalogued ASR result selected from Chat, the fresh routing code now uses meta.pipelineTag to choose /audio, but this search payload forwards only the model and quant. The Audio route reconstructs metadata without the pipeline tag, so audioTaskFor(id) returns null and handleModelSelect treats the repository as TTS, loading it into the main inference slot instead of the STT sidecar. Forward the task in the route search or otherwise preserve it through the handoff.

ℹ️ 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".

Etherll pushed a commit to Etherll/unsloth that referenced this pull request Aug 7, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Went looking for duplication to consolidate rather than splitting. There is less of it than the line count suggests, which is itself the useful answer: this PR is large because it does a lot, not because it repeats itself.

What I measured first

  • The three STT sidecars. 21 methods share a name across all three, so a shared base looks tempting. Measuring the bodies: ggml and mtmd are >90 percent similar on 10 small methods, about 116 lines, and only ~26 lines are near-identical across all three. The big ones are not close at all: _run 0.39, transcribe 0.36, load 0.25. A base class would churn delicate concurrency code to save roughly 100 lines. Not worth it.
  • Redundant tests. Compared all 309 STT and audio test functions pairwise. Exactly one pair is >85 percent similar, and it is the same check written for two different engines (ggml and mtmd disconnect ownership), so it should stay.

What was worth consolidating

One alias resolver, not three. I had added core/inference/spark_tts_paths.py carrying its own copy of the Spark-TTS-0.5B/LLM to unsloth/Spark-TTS-0.5B mapping, while the capability probe and routes/training.py both already resolve it with load_scan_target. Three copies of one mapping is how they drift apart. The export path uses load_scan_target now and the module is deleted.

Worth noting why the duplicate existed: importing core.inference.inference pulls the whole Unsloth stack, so a dependency-light copy was easy to justify. The replacement test reads that file as text instead of importing it, which keeps the test light without a second implementation.

Test files named after review rounds. Four files were called test_stt_review_fixes, _2, _3, _4. That tells a reviewer when the tests were written and nothing about what they cover, and _3 alone was 811 lines.

test_stt_review_fixes_3 + _4  ->  test_stt_mtmd_sidecar   (43 tests; that sidecar had no file of its own)
test_stt_review_fixes         ->  merged into test_stt_ggml_sidecar
test_stt_review_fixes_2       ->  test_stt_install_and_snapshot_validation

105 tests before, 105 after, five files down to three. No test was dropped or rewritten, only moved, and I checked the count by parsing both the old and new files rather than trusting the merge.

Net -51 lines, which is not the point. The point is that test_stt_mtmd_sidecar.py tells you what it covers.

In 14392145a. 1009 passed across the STT, audio, Spark and capability suites.

Where the size actually comes from

If the goal is a smaller diff without splitting, the remaining levers are product decisions rather than cleanups:

area lines note
Audio page UI + policy 2,785 audio-page.tsx is 2,210 of it
Model picker / catalog / detection 1,657 partly extractable, two pieces already went to main as #8392 and #8393
STT sidecars + registry 1,327 three engines, genuinely different
Cancellation / lifecycle 1,247 the piece that touches every model type
OpenAI audio API + gallery 1,119 a separate feature that happens to ship here

43 percent of the added lines are tests, which I would not trade away.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added 2 commits August 11, 2026 08:20
Backend:
- audio_decode: pick the token belonging to the repository a URL points at,
  the way datasets.Audio.decode_example does. Concatenated or interleaved
  streaming splits carry one token per source repo, so taking an arbitrary
  value sent one repo's credential to another repo's host.
- stt_ggml_sidecar fallback: a GGUF pick downloads one .bin, so when the
  runtime turns out to be broken at inference time the Transformers engine it
  is redirected to has no snapshot and every retry raised
  SttModelNotDownloadedError. Fetch the equivalent snapshot in the background
  so the promised fallback is real; /audio/stt/status reports its progress.
- TTS budget: recheck the prompt against the context after an idle-evicted
  model is restored. With nothing loaded there is no context to measure, so
  the first request after an eviction reached generation over-context and came
  back as a one-token clip.
- mtmd unload: the under-lock recheck of _active_requests only guarded
  wait=False, so a blocking unload could reap llama-server underneath a
  transcription that started during the acquire. Drain outside the lock and
  retry, bounded by the same window (draining under the lock would block the
  request being waited on).
- TTS prompt estimate: count every non-ASCII character as a token. The cut at
  U+2E7F billed Arabic, Cyrillic, Hebrew and the Indic scripts at the Latin
  third-of-a-token rate, so a long prompt in any of them passed the guard and
  overflowed during generation.

Frontend:
- Cancel a deactivating load with the target it was actually started with, not
  the repo id, so a load keyed on a path or a gguf file is really cancelled.
- Replay a queued TTS pick only once the page is active again, and drain the
  queue on activation.
- Abort the TTS handoff when releasing the STT sidecar fails, instead of
  loading TTS on top of a resident sidecar.
- Gallery merge: a complete first page (has_more=false) is everything the
  server holds, so drop the cached tail rather than rendering clips another
  client deleted or the size cap pruned.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: d1e5ff7755

ℹ️ 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 and others added 3 commits August 11, 2026 08:52
The PR had gone unmergeable, which is what pre-commit.ci was reporting as
"error during mergeable check" rather than a lint failure. The only conflict
was in the GGUF variant expander call sites, where unslothai#8383 reworked the
surrounding props: both sides kept, since the audio branch only adds
pipelineTag and filenamePrefix there.
…Target

unslothai#8383 moved GGUF partition identity to the backend and removed
filenamePrefix from GgufVariantExpander, so the four call sites this branch
touches keep pipelineTag and drop the prop that no longer exists.

loadTarget was added to the pendingTtsLoad value but not to the ref's type,
which only the project build (tsc -b) catches.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Switching straight from Transcribe to Speak with a speech model already
resident needs no load, so the gate in the load path never ran and Generate
could allocate beside the dictation model. Generate now waits on the same
release, and a release that failed puts the page back in Transcribe instead of
showing Speak while the sidecar is still resident.

@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: d6724344b7

ℹ️ 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 +1367 to +1368
const releaseInFlight = pendingTranscribeRelease.current;
if (releaseInFlight && !(await releaseInFlight)) {

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 Mark generation busy before awaiting STT release

When a TTS model is already resident and the user switches from Transcribe to Speak, the Generate button becomes available while the STT unload promise is still pending. Fresh evidence in the revised handler is that this release is now awaited before busy is set, so multiple clicks during a slow unload all resume together and start separate generateAudio requests; generateAbort then tracks only the latest request, and either request's finally can clear the busy state while the other is still running. Claim an in-flight generation before this await and clear it only from the owning attempt.

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.

Correct, and it was introduced by the gate I added one round earlier: the button only disables on busy, so awaiting the release before claiming it let every click during a slow unload through, each resuming into its own generateAudio while generateAbort tracked only the last. The slot is now claimed synchronously before the await, and a release that failed hands it back on the way out.

danielhanchen and others added 4 commits August 11, 2026 09:41
unslothai#8381 added refreshInventoryIfOlderThan to the chat picker inventory hook at
the same call site this branch passes allowedHiddenModelIds through, so both
are kept.
Both drive a path that reaches `import torch` before the behaviour under test,
so on a bare cross-platform runner they failed for a missing wheel rather than
for anything they assert.
Without Transformers the helper returns None and the check is skipped, so the
request fell through to the download guard and the test asserted nothing on any
runner that lacks the dependency.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 3 commits August 11, 2026 10:46
The launcher looks for whisper-server.exe there, and the slim guard checks the
libraries the marker names verbatim, so fixtures that hardcoded whisper-server
and libggml.so.0 were invisible to both: six tests failed on a Windows runner
for the spelling rather than for anything they assert. The product code already
handled both platforms.
…med model

- Implicit loads on the transcribe routes went straight to the sidecar, and only
  the registry releases the other engines, so an API client alternating between
  Qwen3-ASR and Whisper through /v1/audio/transcriptions held both until their
  independent idle timers fired. Routed through the shared lifecycle, which is a
  no-op once the model is resident.
- Unload now takes the model the caller claims and compares it under the
  sidecar's own lock. Ownership is decided by the caller, so another surface can
  switch the same engine before a queued Eject or mode transition lands, and an
  unscoped release tore down a model the caller never owned. Threaded through the
  registry, the orchestrator, the route and the Audio page.
- A whisper.cpp pick on a host without whisper-server is served and loaded
  through Transformers, but the residency resolver read only the gguf block, so
  the refresh that completes the load found nothing and the Transcribe controls
  stayed disabled until the page was revisited. Same fallback sttEngineStatusFor
  already applies.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: e1d52a4c53

ℹ️ 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".

The Generate button only disables on busy, so awaiting the release first let
every click during a slow unload through: each resumed into its own
generateAudio while generateAbort tracked only the last, and either finally
cleared the busy state out from under the other.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 6675ca06f9

ℹ️ 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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants