Skip to content

Feature/voice conversation mode v2 - #6527

Closed
BardiaKoopah wants to merge 79 commits into
unslothai:mainfrom
BardiaKoopah:feature/voice-conversation-mode-v2
Closed

BardiaKoopah wants to merge 79 commits into
unslothai:mainfrom
BardiaKoopah:feature/voice-conversation-mode-v2

Conversation

@BardiaKoopah

Copy link
Copy Markdown
Contributor

Summary

Voice features for Unsloth Studio. Rebased on latest upstream main (composer redesign #5891, editable assistant messages #6397, queued prompts #6244, Hub redesign #6349, inference orchestrator simplification #6439). Architecture unchanged from the original PR.

  1. Voice conversation mode — ChatGPT-style continuous voice chat with your LLM. Open the plus menu, pick Voice, choose a voice, talk to your model and hear it respond.
  2. Listen button on trained TTS models — fixes the broken workflow where users fine-tune Orpheus/CSM/Spark/DAC models in Studio but can't hear them without leaving the app. Type text, click play, hear your trained voice.
  3. Two-slot architecture — LLM brain in the main slot, TTS voice in a temporary secondary slot. Voice slot only activates when voice mode is on, unloads when off. Normal chat is unchanged.

What's new

Backend

  • POST /api/audio/speech — wraps existing TTS infrastructure into an OpenAI-style endpoint returning raw WAV
  • POST /api/inference/voice/load / unload / GET status — independent second LlamaCppBackend instance for TTS, restricted to snac / bicodec / dac audio types
  • _owns_codec flag so main-slot unload doesn't kill the voice slot's codec
  • audio_type detection threaded through trained LoRA scanning (scan_loras)
  • CSP media-src 'self' blob: was needed in the original PR but upstream now ships a broader media-src directive that already allows blobs, so the edit was dropped

Frontend

  • Speaker button on every assistant message
  • Voice entry inside the plus menu (alongside Web search, Code, MCP, etc.) with three states: off / configuring / active
  • Voice model selector dropdown next to "Select Model" (only shows when voice mode is on)
  • Two-step toggle: clicking Voice enters configuring, dropdown pick activates the loop
  • Auto-speak responses + auto-listen loop with 1.5s silence auto-send
  • useTtsPlayer hook chooses backend TTS when a voice model is loaded, falls back to speechSynthesis otherwise
  • Listen button (headphones icon) on TTS-only LoRA rows in the Fine-tuned tab → modal with text input + play
  • Safari autoplay unlock via priming a persistent Audio element on the user gesture
  • Pre-download confirmation if a picked voice model is >100MB and not cached (per Mike's feedback)
  • Barge-in: user speech during TTS playback interrupts the model and captures the new prompt
  • Voice orb full-screen overlay during active state; toggling voice off fades it out and the chat history is preserved

How to test

  1. Load any LLM as your chat brain (e.g. Qwen3-0.6B)
  2. Open the plus menu, click Voice — Voice model dropdown appears next to Select Model
  3. Pick "Browser voice" → conversation runs with robot TTS
  4. Or pick a TTS model (e.g. Orpheus, downloads if not cached) → conversation runs with that voice
  5. For Listen button: open model picker, Fine-tuned tab, click headphones on any TTS LoRA

Known limitations

  • Mic picks up the model's own TTS through laptop speakers, which can cause feedback loops when barge-in is active (model voice triggers a barge-in on itself). Mitigation today: use earbuds. Proper fix would require either browser-level echo cancellation tuned for the speaker path or transcript-vs-TTS-text matching — both larger follow-ups outside this PR's scope.
  • Tested end-to-end in Safari; Chrome has a separate SpeechRecognition permission quirk on http://localhost that breaks the existing dictate button too (not introduced by this PR).
  • TTS inference speed is model- and hardware-bound — Orpheus 3B is slow on CPU-only Macs but fast with a GPU.
  • Text normalization (e.g. + → "plus") isn't done before sending to TTS yet — small follow-up.
  • Compare-mode (shared-composer.tsx) voice toggle was deferred during the rebase; upstream rewrote that file heavily and the main chat voice experience was the priority. Can land as a follow-up if reviewers want compare-mode parity.

…oRAs

Re-anchored on fresh upstream/main after composer redesign + orchestrator
simplification landed. Architecture unchanged from original PR:

- Second LlamaCppBackend instance as the voice slot (TTS only: snac/bicodec/dac)
- _owns_codec flag prevents main-slot unload from killing the voice slot's codec
- POST /api/inference/voice/load|unload, GET /api/inference/voice/status
- POST /api/audio/speech wraps existing TTS infra (voice slot > main llama > transformers fallback)
- audio_type detection threaded through LoRAInfo and scan_loras
- CSP edit dropped: upstream already allows blob: in media-src
Frontend port on top of upstream main (composer redesign, editable
assistant messages, queued prompts, Hub redesign). Architecture
unchanged from original PR.

- Speaker button on assistant messages (useTtsPlayer hook)
- Voice in plus menu — clicking enters configuring state, picking a
  voice from the new dropdown activates the conversation loop
- Voice model selector next to Select Model (only visible during
  voice mode); shows trained TTS LoRAs + cached TTS GGUFs
- Two-step toggle: configuring (dropdown visible, mic off) → active
  (loop running, orb overlay)
- Voice orb full-screen overlay during active state
- Barge-in: user speech during TTS playback interrupts and captures
- Listen button (headphones) on trained TTS LoRAs in Fine-tuned tab
- Pre-download confirmation for voice models > 100MB
- Safari autoplay unlock via primeAudio() on user gesture
- Compare-mode voice toggle deferred (shared-composer.tsx rewrite)
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@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: 0a9c05b7bc

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +6602 to 6604
if self._owns_codec and LlamaCppBackend._codec_mgr is not None:
LlamaCppBackend._codec_mgr.unload()
LlamaCppBackend._codec_mgr = None

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 Reference-count the shared audio codec owner

When both the main and voice LlamaCppBackend instances have loaded GGUF TTS models, both call init_audio_codec() and set _owns_codec = True while sharing the class-level _codec_mgr. Unloading either slot now enters this branch and sets the shared manager to None, so the other still-loaded slot later fails in generate_audio_response() when it calls LlamaCppBackend._codec_mgr.decode(...). The ownership guard needs to be reference-counted or tied to the active slot/model instead of a per-instance boolean.

Useful? React with 👍 / 👎.

Comment on lines +84 to +88
const blob = await response.blob();
const url = URL.createObjectURL(blob);
objectUrlRef.current = url;
const audio = audioRef.current ?? new Audio();
audioRef.current = 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.

P2 Badge Invalidate cancelled TTS requests before playback

If the user presses Stop or closes the listen modal while /api/audio/speech is still generating, stop() only clears the current audio element and does not cancel or mark this async request stale. When the response eventually resolves, this code still creates a blob URL and proceeds to play it, so cancelled speech can start later with no visible control and can update state after unmount. Track a request id or abort signal and check it before creating/playing the audio.

Useful? React with 👍 / 👎.

Comment on lines +2251 to +2255
const ttsModels = useMemo<LoraModelOption[]>(() => {
const fromLoras = loraModels.filter((m) =>
TTS_AUDIO_TYPES.has(m.audioType ?? ""),
);
return [...fromLoras, ...cachedGgufs];

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 Exclude non-GGUF adapters from voice-slot choices

The voice selector sends every option to /api/inference/voice/load, but that route rejects anything whose resolved config is not GGUF. _detect_lora_audio_type() adds audioType for LoRA/merged training outputs, so this filter makes non-GGUF TTS adapters appear as selectable voice models even though selecting them always fails with the GGUF-only backend error. Restrict this list to loadable GGUF voice models, or route non-GGUF adapters through the main-model TTS path instead.

Useful? React with 👍 / 👎.

Comment on lines +2572 to +2575
composer.stopDictation();
if (composer.getState().isEditing && composer.getState().text.trim()) {
composer.send();
}

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 Keep voice dictation alive after empty silence

When voice mode is active and the user is silent for the first 1.5s after dictation starts, this timeout stops dictation and only sends if the composer already has text; the no-text path never restarts the mic. That leaves the orb showing “listening” while speech recognition is actually off, so a user who pauses before speaking (or pauses after TTS resumes listening) cannot continue the conversation until they manually toggle voice mode again.

Useful? React with 👍 / 👎.

audio.onended = cleanup;
audio.onerror = cleanup;
audio.src = url;
audio.play();

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 rejected audio playback promises

HTMLMediaElement.play() returns a promise, and browsers can reject it for autoplay policy or decoder/output errors without firing onerror. In that case this hook has already set isSpeaking to true and never runs cleanup, so the Speak button/voice loop can stay stuck in the speaking state and never resume listening. Attach a .catch(cleanup) or await the play promise before considering playback started.

Useful? React with 👍 / 👎.

Comment thread studio/backend/routes/audio.py Outdated
Comment on lines +50 to +54
if voice_backend.is_loaded and getattr(voice_backend, "_is_audio", False):
gen = lambda: voice_backend.generate_audio_response(
text=text,
audio_type=voice_backend._audio_type,
)

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 Target Listen previews at the selected model

Because /api/audio/speech always prefers the voice slot, the Listen modal can preview the wrong model whenever voice conversation mode already has a voice model loaded: the modal loads the clicked adapter into the main slot, but its TTS request has no target and this branch routes the audio through the existing voice-slot backend instead. Add a way for Listen to bypass the voice slot or specify the intended model/backend.

Useful? React with 👍 / 👎.

Comment on lines +1789 to +1790
if model_type == "gguf":
return None

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 Surface local GGUF voice exports

Returning None for every GGUF training/export output means local GGUF TTS models exported by Studio never get an audioType, and the voice selector later filters local/exported models with TTS_AUDIO_TYPES.has(m.audioType). As a result, valid local Orpheus/Spark/Oute GGUF voice models are omitted from the selector even though /voice/load explicitly supports local GGUF paths; either detect the GGUF audio type or include GGUF exports and let the server validate them.

Useful? React with 👍 / 👎.

Comment on lines +1264 to +1265
const isCached = cachedGgufs.some((g) => g.id === id);
if (!isCached) {

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 Check the selected GGUF variant before skipping confirmation

This cache fast path only checks whether any GGUF from the repo exists locally, not whether the backend's default variant is already downloaded. If a user has a small/old quant cached but /voice/load auto-picks a different large default quant, this skips the size confirmation and starts a new HuggingFace download anyway; call gguf-variants and inspect the chosen variant's downloaded flag even when the repo appears in cachedGgufs.

Useful? React with 👍 / 👎.

Comment on lines +1328 to +1331
useEffect(() => {
if (voiceMode === "off" && selectedVoiceModelId) {
void authFetch("/api/inference/voice/unload", { method: "POST" });
}

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 Unload the voice slot when leaving chat

This effect only unloads the voice llama-server when voiceMode transitions to off; if the user navigates away from Chat while voice mode is still active, the component unmounts without changing voiceMode, so /api/inference/voice/unload is never called and the independent voice model can keep occupying VRAM until the backend is restarted or the user returns and turns it off. Add an unmount cleanup for active voice-slot loads.

Useful? React with 👍 / 👎.

Comment on lines +1302 to +1305
const res = await authFetch("/api/inference/voice/load", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model_path: id }),

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 Forward the saved HF token for voice loads

The voice-load API accepts hf_token, but this request body only sends model_path. For gated/private GGUF voice repos that the user previously cached or can otherwise select, the backend calls HuggingFace without the token and can reject the repo as non-GGUF or fail to download the selected quant, even though normal chat model loads succeed using the token stored in the runtime settings.

Useful? React with 👍 / 👎.

…ker without chat model

- Orb backdrop now intercepts pointer events when active so tooltips and
  hover-menus from the hidden chat history don't bleed through. Composer
  dock still bumps to z-40 and stays interactive.
- Voice model selector is greyed out (cursor-not-allowed, opacity-50)
  and blocked from opening when no chat model is loaded; trigger label
  becomes 'Select model first'. Prevents loading a TTS model with no
  brain to generate replies.

@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: 1395b6ce94

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +2772 to +2774
const voiceAvailable =
(typeof window !== "undefined" && "speechSynthesis" in window) ||
TTS_AUDIO_TYPES.has(voiceActiveAudioType ?? "");

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 Gate voice mode on speech recognition support

In browsers that have speechSynthesis but no Web Speech recognition support, this condition still exposes Voice and lets the UI enter configuring/active mode, but VoiceEngine starts listening only by clicking the Dictate control in activateLoop/resumeListen. In that environment the orb can show “listening” while no transcript can ever be produced, so gate this on SpeechRecognition/webkitSpeechRecognition as well as TTS availability or disable the item with an explanation.

Useful? React with 👍 / 👎.

Comment on lines +1073 to +1074
if audio_type == "snac":
continue

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 Detect local SNAC outputs before filtering

When a Studio training output is a merged/full-finetune Orpheus/SNAC model, _detect_lora_audio_type() calls this local tokenizer detector, and this branch suppresses exactly the SNAC pattern, so /api/models/loras returns audio_type=None. The Fine-tuned Listen button and voice model list both require audioType to be in TTS_AUDIO_TYPES, so valid local SNAC TTS outputs disappear from the new voice workflows.

Useful? React with 👍 / 👎.

Comment on lines +1313 to +1315
} else {
// Model loaded — activate the conversation loop.
useChatRuntimeStore.getState().setVoiceMode("active");

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 Ignore stale voice model load completions

If the user selects a second voice while the first /voice/load request is still in flight, the first response can still run this branch and mark voice mode active even though selectedVoiceModelId now points at the later choice. Because the backend serializes these loads, there is a window where the selector shows the new voice but the old one is loaded and the listening loop can start; track a request id or compare the completed id before activating.

Useful? React with 👍 / 👎.

Comment thread studio/backend/main.py
# ============ Register API Routes ============

# Register routers
app.include_router(audio_router, prefix = "/api/audio", tags = ["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.

P2 Badge Mount audio speech on the OpenAI prefix

The new speech route is described as OpenAI-compatible, but it is only mounted under /api/audio; the /v1 prefix below still includes only inference_router. External OpenAI-compatible clients calling the standard /v1/audio/speech path will get 404 even though the route exists, so include audio_router on the /v1/audio surface as well or avoid advertising it as compatible.

Useful? React with 👍 / 👎.

const voiceSlotLoaded = useChatRuntimeStore(
(s) => s.voiceMode === "active" && s.selectedVoiceModelId !== null,
);
const { isSpeaking, speak, stop } = useTtsPlayer(activeAudioType, undefined, voiceSlotLoaded);

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 Share TTS playback state across speak buttons

Each assistant message gets its own useTtsPlayer instance here, so clicking Speak on another message while one is already playing does not stop the first player; backend WAV playback can overlap in separate Audio elements, and browser speech can queue because the second hook does not own the first utterance. Keep playback state/global cancellation shared across message buttons so there is only one active speech stream.

Useful? React with 👍 / 👎.

Comment on lines +2251 to +2255
const ttsModels = useMemo<LoraModelOption[]>(() => {
const fromLoras = loraModels.filter((m) =>
TTS_AUDIO_TYPES.has(m.audioType ?? ""),
);
return [...fromLoras, ...cachedGgufs];

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 Include uncached voice models in the selector

On a fresh install with no trained/exported voices and no cached GGUF TTS repos, this list is empty because it only combines audio-tagged local models with /cached-gguf results. That makes the download-confirmation path in handleVoiceModelChange unreachable for remote voices, so users cannot pick/download an Orpheus/Spark/etc. voice from voice mode until they have somehow cached it elsewhere.

Useful? React with 👍 / 👎.

…ad switch

- resumeListen now polls hasDictation for up to ~250ms before clicking
  Dictate, absorbing the stale-state race that killed the loop after
  no-speech timeouts and silence-timer ends. Falls back to clicking
  anyway as a last resort so the loop never dies silently.
- Silence-timer empty-text path now re-arms via resumeListen instead
  of stopping dictation without restart.
- Thread switch (sidebar chat change) now exits voice mode entirely,
  hiding the orb and unloading the voice slot. Prevents voice state
  carrying over to the new conversation.
- Diagnostic logging removed.

@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: 2078bad76f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

useEffect(() => {
if (voiceMode === "off" || cachedGgufsFetchedRef.current) return;
cachedGgufsFetchedRef.current = true;
const TTS_REPO_KEYWORDS = ["orpheus", "kokoro", "csm", "spark", "bicodec", "dac", "tts"];

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 Hide unsupported cached CSM/Kokoro GGUFs

When the cached-GGUF list contains repos matching csm, kokoro, or the generic tts keyword, they are added to the voice selector even though /api/inference/voice/load only accepts GGUF models whose runtime codec is one of snac, bicodec, or dac. Selecting a cached CSM/Kokoro TTS repo therefore starts a voice-slot load and then rejects it as unsupported, so the selector should only include codecs the voice slot can actually load or route these models through a supported path.

Useful? React with 👍 / 👎.

`Download ${modelName} (~${sizeMb} MB)? This downloads from HuggingFace.`,
);
if (!confirmed) {
setSelectedVoiceModelId(null);

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 Restore the previous voice on cancelled downloads

If a voice model is already loaded and the user picks another uncached repo but cancels this confirmation, this branch clears the selected voice without unloading the existing voice slot or restoring the previous id. Because /api/audio/speech still prefers any loaded voice backend, subsequent speech can continue using the old server voice while the selector shows Browser voice, and turning voice off later will not unload it because selectedVoiceModelId is now null.

Useful? React with 👍 / 👎.

import { authFetch } from "@/features/auth";
import { useCallback, useEffect, useRef, useState } from "react";

export const TTS_AUDIO_TYPES = new Set(["snac", "csm", "bicodec", "dac"]);

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 Don't route unsupported GGUF CSM through speech API

For a loaded GGUF CSM model, the backend reports audio_type='csm' but keeps is_audio false because the llama.cpp decoder path only supports snac, bicodec, and dac. Including csm in this type-only gate makes useTtsPlayer call /api/audio/speech; that route skips GGUF CSM and falls through to the transformers backend, usually failing instead of using browser speech, so the hook needs the loaded isAudio/GGUF capability or CSM should be excluded for GGUF loads.

Useful? React with 👍 / 👎.

Comment thread studio/backend/routes/inference.py Outdated
raise HTTPException(status_code=500, detail=f"Failed to load voice model: {e}")

if not ok:
raise HTTPException(status_code=500, detail="Voice model failed to start.")

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 Unload the voice server when codec init fails

When LlamaCppBackend.load_model() returns False after the llama-server became healthy but audio codec initialization failed, this branch raises without unloading the voice backend. That leaves the failed voice-slot process occupying memory and visible to later status/speech handling even though the UI saw a failed load; mirror the unsupported-type cleanup before raising here.

Useful? React with 👍 / 👎.

_llama_cpp_backend = LlamaCppBackend()

# Voice slot — independent llama-server subprocess for GGUF TTS models only
_voice_llama_backend = LlamaCppBackend()

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 Give each llama slot its own pidfile

Adding a second LlamaCppBackend means two independent llama-server children now share the class-level pidfile used by _record_server_pid() and _clear_server_pid(). Loading or unloading either slot overwrites/removes the single record for the other slot, so after both main and voice models have been used an unclean Studio exit can leave one server unrecorded for orphan reaping and still occupying VRAM; the pidfile needs to be keyed per slot/process instead of shared globally.

Useful? React with 👍 / 👎.

BardiaKoopah and others added 10 commits June 22, 2026 12:25
- Drive isThreadRunning from runningByThreadId[activeThreadId] in the
  store instead of useAuiState(thread.isRunning). The store value
  survives the ThreadWelcome → ThreadComposerDock composer remount on
  first send, so the first turn's running transition is no longer lost.
- Promote prevRunningRef to module-scope _prevRunning alongside
  _voiceMode, so the true→false edge survives the same remount.
- Clear composer text explicitly after the silence-timer send to guard
  against the send-reset racing with thread-bind, which was leaking the
  first utterance as a prefix on turn 2.

Together these fix the first-turn UX: orb correctly transitions
green → yellow → blue, and the user's first message no longer bleeds
into subsequent turns.
…mode-v2

# Conflicts:
#	studio/backend/routes/inference.py
#	studio/frontend/src/components/assistant-ui/model-selector.tsx
#	studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx
#	studio/frontend/src/components/assistant-ui/thread.tsx
#	studio/frontend/src/features/chat/chat-page.tsx
- use-tts-player: catch a rejected audio.play() so an autoplay/decoder
  rejection can't leave the voice loop stuck in "speaking"; tag each
  /api/audio/speech request with an id so a cancelled or superseded speak
  can't start playback late or update state after unmount.
- inference voice/load: unload the half-started voice slot when
  load_model() returns False (e.g. codec init failed) so the llama-server
  process doesn't linger.
- chat-page: roll back to the prior voice when a download confirmation is
  cancelled; unload the voice slot on unmount so an active voice model
  can't keep holding VRAM after navigating away from Chat.
- main: also mount the speech route at /v1/audio/speech for OpenAI-
  compatible clients.
- audio: generate speech via asyncio.to_thread (drops the deprecated
  get_event_loop().run_in_executor call).
Speak the assistant response sentence-by-sentence with pipelined synthesis:
synthesize the next clip while the current one plays, serialized to one
in-flight request (the voice slot runs --parallel 1 and /api/audio/speech has
no lock). First audio now starts after the first sentence instead of after the
whole response. The speechSynthesis fallback is chunked the same way, which
also dodges Chrome's long-utterance cutoff.

Make the mic silence auto-send delay a tunable constant (VOICE_SILENCE_DEBOUNCE_MS)
and add a barge-in minimum-length guard (VOICE_BARGE_IN_MIN_CHARS) so the mic
picking up the model's own TTS through the speakers doesn't interrupt it.
Replace the immediate (min-char) barge with a short confirmation window: when
speech is heard during TTS, wait VOICE_BARGE_IN_DEBOUNCE_MS and only stop the
model if the transcript grew (sustained speech). A cough or stray blip produces
one fragment that doesn't grow, so it's ignored; a real interruption keeps
adding words and cuts the model off.
Add POST /api/audio/transcribe (also /v1/audio/transcribe) that decodes uploaded
audio with soundfile (no ffmpeg) and transcribes via a transformers Whisper
pipeline. New StudioWhisperDictationAdapter records the mic, does energy-VAD
end-of-utterance detection, and posts to the endpoint. A persisted sttEngine
store field + runtime-provider selection choose the adapter, and the voice
dropdown gets a 'Listen with: Browser / Whisper' toggle.

Backend STT lets voice dictation work where the browser Web Speech API can't
(Edge, Brave, the Tauri webview). Whisper needs torch, so on a SAC-enforcing
Windows host it is blocked until SAC is off (unslothai#6648); a torch-free whisper.cpp
path is a follow-up.
Stream audio as the TTS model generates instead of per-sentence synthesis.
Backend: decode_snac_window() does incremental SNAC decode over a sliding
4-frame window (click-free 2048-sample slice); generate_audio_response_stream()
streams tokens from llama-server and yields PCM16; new POST
/api/audio/speech/stream returns the PCM stream (SNAC only). Frontend:
useTtsPlayer prefers the streaming endpoint, scheduling PCM chunks back-to-back
via Web Audio, and falls back to sentence-chunked synthesis for non-SNAC voices
or when streaming is unavailable.

First audio starts before the reply finishes and prosody flows across sentence
boundaries. Untested end-to-end (SNAC decode needs a working torch/GPU host);
the sliding-window overlap and the SSE token-id parsing are the likely tune
points.
Detect a speech-LLM chat model (Orpheus/CSM/Spark...) from the loaded
checkpoint and disable the 'Speak with' TTS section with an explainer (the
model speaks with its own voice). Listening (Browser/Whisper STT) stays active.
…k Whisper STT

Picking any Listen/Speak option force-activated the voice ball
immediately, even just to browse settings; entering the ball is now an
explicit "Start voice mode" action so the text chat stays visible until
you actually want to talk.

Whisper transcription was 500ing on every request: transformers'
is_torchcodec_available() only checks that the torchcodec package is
importable, not that its DLLs load, and torchcodec has no ROCm decode
path so its bundled libtorchcodec_core*.dll never loads under
torch+rocm. We already hand the pipeline a pre-decoded numpy array, so
patch that check off instead of letting the crash happen.

@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: 5df71eb958

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +196 to +199
onClick={() => {
setOpen(false);
setVoiceMode("active");
}}

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 Load the selected voice before activating mode

When selectedVoiceModelId is restored from localStorage or after voice mode was turned off (the chat page unloads the voice slot but keeps the selection), this button only flips voiceMode to active and never reloads or status-checks the selected voice. The selector still displays that voice and useTtsPlayer treats selectedVoiceModelId !== null as a loaded backend voice, so the next TTS call goes to /api/audio/speech with an empty voice slot and can fail silently instead of speaking; start should load/verify the selected voice or clear the selection when unloading.

Useful? React with 👍 / 👎.

Comment on lines +233 to +237
if (ctx) {
const remainingMs = Math.max(0, (playHead - ctx.currentTime) * 1000);
await new Promise<void>((r) => setTimeout(r, remainingMs + 80));
}
return "played";

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 Fall back when streaming produces no audio

If /api/audio/speech/stream returns 200 but the generator closes before yielding any PCM (for example generate_audio_response_stream() raises and the route logs then ends the StreamingResponse), this path still returns "played". That skips the chunked /api/audio/speech fallback even though nothing was scheduled, so SNAC streaming failures or empty streams make the assistant resume after silence; return "fallback" when EOF arrives with scheduledAny === false.

Useful? React with 👍 / 👎.

Comment on lines +173 to +174
@router.post("/transcribe", response_model = TranscriptionResponse)
async def transcribe(

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 Expose transcriptions on the standard path

This router is also mounted under /v1/audio, but the transcription endpoint is registered as /transcribe, while the docstring says it mirrors the OpenAI /v1/audio/transcriptions interface. External OpenAI-compatible clients will call /v1/audio/transcriptions and get a 404 even though the backend can transcribe; add the standard route alias or avoid advertising it as compatible.

Useful? React with 👍 / 👎.

Comment thread studio/backend/main.py
_BODY_PROTECTED_PREFIXES = (
"/v1/chat/completions",
"/v1/completions",
"/api/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.

P2 Badge Cap request bodies on the /v1 audio mount

Only the Studio /api/audio prefix is added to the body-limit middleware, but the same router is now mounted under /v1/audio below. Requests to /v1/audio/transcribe therefore bypass the protected-prefix cap and transcribe() reads the upload into memory with await file.read(), so an OpenAI-compatible client can send an arbitrarily large body on that path; include /v1/audio in the protected prefixes as well.

Useful? React with 👍 / 👎.

Comment on lines +2815 to +2816
if (silenceTimerRef.current) clearTimeout(silenceTimerRef.current);
silenceTimerRef.current = setTimeout(() => {

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 Do not run the Web-Speech silence timer for Whisper

When the user selects the new Whisper STT engine, the adapter records audio and emits a transcript only after its own VAD/transcription completes, so dictationTranscript does not grow while the user is speaking. This generic 1.5s debounce is still armed from session start and can stop the Whisper session before the utterance is complete, then the immediate composer-text check sees no transcript yet and re-arms instead of sending the user's speech; skip this timer for Whisper or drive sending from the adapter's final result.

Useful? React with 👍 / 👎.

Comment on lines +2821 to +2822
if (composer.getState().isEditing && composer.getState().text.trim()) {
composer.send();

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 Avoid sending transcripts while TTS is still speaking

During assistant playback the code intentionally starts dictation for barge-in, but this branch sends any non-empty composer text even when isSpeakingRef.current is still true. If the microphone transcribes a short echo/noise fragment from the model voice that does not keep growing enough to trigger the barge-in stop(), the silence timer can submit that fragment as the next user message while TTS continues; gate auto-send until speech has actually been stopped or ignore transcripts collected during playback.

Useful? React with 👍 / 👎.

Comment on lines +57 to +60
if (!audioRef.current) {
audioRef.current = new Audio();
}
audioRef.current.play().then(() => audioRef.current?.pause()).catch(() => {});

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 Prime audio with a real source

In browsers with strict autoplay policies, this priming call is the only user-gesture unlock before backend WAV playback happens later from an async fetch, but it calls play() on a newly-created audio element with no source. That play rejects and the catch swallows it, leaving the element unprimed; later audio.play() in playBlob() can be rejected and treated as finished with no audible TTS. Use a tiny silent data URL/blob or otherwise unlock the actual playback path during the gesture.

Useful? React with 👍 / 👎.

onValueChange={(id) => void handleVoiceModelChange(id)}
loading={voiceSlotLoading}
disabled={!hasActiveModel}
voiceOwnedByModel={chatModelIsSpeechLLM}

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 Clear separate voices for speech-LLM chat models

When a separate voice model is already selected/loaded and the user switches the chat checkpoint to a speech-LLM, this flag only disables the selector UI; it does not clear selectedVoiceModelId or unload the voice slot. Because /api/audio/speech always prefers the voice slot, the model will still speak with the old separate voice even though the UI says the loaded model owns its voice, so clear/unload the voice slot when chatModelIsSpeechLLM becomes true.

Useful? React with 👍 / 👎.

Comment on lines +316 to +320
const finish = () => {
if (utteranceRef.current === null) return;
utteranceRef.current = null;
setIsSpeaking(false);
onPlaybackEndRef.current?.();

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 Ignore stale browser-speech completion events

In the browser speechSynthesis path, finish() only checks whether any utterance is currently recorded, not whether the event belongs to this speak() call. If the user stops/restarts quickly and a cancelled old utterance fires onend/onerror after a new utterance has been queued, this stale callback can clear the new playback state and run onPlaybackEnd early, resuming the voice loop while speech is still queued; tie finish() to the current request id or owning utterance.

Useful? React with 👍 / 👎.

BardiaKoopah and others added 11 commits July 1, 2026 14:04
Not a complete fix. VoiceEngine's activeThreadId subscription is
stale across the first-send composer remount, so prevThreadIdRef
never observes the null → __LOCALID_xxx transition. Prev stays null
and New Chat's __LOCALID_xxx → null change is treated as no-op.

Next step: move thread-switch reset out of VoiceEngine into a
component that doesn't remount (probably chat-page.tsx).
…watcher

VoiceEngine remounts across the ThreadWelcome → ThreadComposerDock
first-send boundary, so its activeThreadId subscription never
observed the null → __LOCALID_xxx transition. prevThreadIdRef stayed
stuck at null, and the later __LOCALID_xxx → null on New Chat was
treated as no-op — orb stayed visible with a dead loop.

Fix: move the reset out of VoiceEngine into the stable SingleContent
component in chat-page.tsx, which does not remount on first send.
The watcher drives requestVoiceToggle() via the module-level bridge,
gated on getVoiceMode() so a plain thread switch with voice off
can't accidentally toggle voice on.

Also skip the reset on thread birth (null → __LOCALID_xxx), which
is a new thread being created mid-conversation, not a real switch —
otherwise voice mode would die the moment the user's first message
saved a thread.

Ref advances on every branch so no transition is missed.
…isten guard

On first send, ComposerActionWrapper remounts across the
ThreadWelcome → ThreadComposerDock boundary, so composer.setText('')
called synchronously after send() lands on the outgoing composer
instance and has no effect. The utterance stays in the composer,
and turn 2's dictation appends onto it — sending the concatenation
'"hey hello" + "how about"' as one message.

Two fixes:

1. After the synchronous setText(''), schedule a deferred retry loop
   (up to 5 attempts, 50ms apart) that re-clears via a FRESH
   auiRef.current.composer() handle each time, not the captured
   soon-to-be-unmounted one. Aborts if voice leaves 'active' or the
   composer is empty.

2. resumeListen's clickDictate() now proactively clears any stale
   composer text via a fresh handle immediately before re-arming
   the Dictate button, covering the case where the user starts
   speaking turn 2 before the deferred retry finishes.

Non-destructive on turns 2+: the synchronous clear succeeds there,
so the retry finds it empty at attempt 1 and stops without
side effects.
… token streaming

- Add in-process SpeechT5 voice backend (transformers-native, no GGUF/extra dep,
  works on Python 3.13) wired into /voice/load|unload|status and /speech.
- Split the old combined voice dropdown into separate STT (Listen) and TTS
  (Speak) pickers, each greying out independently; restyle both to match the
  main model selector (pill rows, owner/name split, DotTag format/active badges).
- List on-device Whisper models in the STT picker and wire the selected model id
  into /api/audio/transcribe; keep TTS list GGUF + SpeechT5 only.
- Remove token-by-token TTS streaming end to end (frontend player, /speech/stream,
  generate_audio_response_stream, decode_snac_window); sentence chunking only.
- Show the audio player above the model's reply text instead of replacing it.
- Bypass transformers' torchcodec check in Whisper transcribe so STT works under
  ROCm torch on Windows; scan .pth weights so hub On Device sees more repos.
Brings in: first-turn text bleed fix (deferred clear + resumeListen guard),
reliable thread-switch reset via stable chat-page watcher, and WIP thread-switch
diagnostic/prev-ref fix. Merged into the SpeechT5/split-picker work, not rebased.

# Conflicts:
#	studio/frontend/src/features/chat/chat-page.tsx
…peak

First SpeechT5 synthesis paid ~25s of MIOpen conv-kernel tuning on ROCm, so the
first utterance arrived long after the reply (and felt broken). Run a tiny
warmup generate_speech during load_model, where the user is already waiting,
so the first real utterance is fast. Non-fatal if it fails.

Auto-speak previously skipped the new reply when a stale utterance was still
speaking or a slow synth was in flight, silently dead-ending the voice loop.
Newest reply now wins: speak() supersedes the old utterance via stop().
…oice picker

Add an in-process Qwen3-TTS backend (Qwen/Qwen3-TTS-12Hz-*) via the qwen-tts
package, installed --no-deps to keep the venv's transformers/accelerate (it
hard-pins both and drags in gradio); sox is the only extra dep (imported by the
unused 25Hz tokenizer path, never executed for 12Hz models). torchao is stubbed
with the shared Windows-ROCm stub before import, same as the RAG embedder.
CustomVoice checkpoints work out of the box (premade speakers, default Ryan,
env-overridable); Base is voice-cloning and requires UNSLOTH_QWEN_TTS_REF_AUDIO
/ _REF_TEXT. Warmup synth at load absorbs MIOpen kernel tuning.

Route /voice/load|unload|status and /api/audio/speech through the new backend
(3-way mutual exclusion with the GGUF and SpeechT5 slots). The voice dropdown
now offers the two canonical 0.6B Qwen3-TTS checkpoints (plus any cached
qwen3-tts repos) and no longer lists SpeechT5; the main hub is untouched.
…nstall check

_ensure_qwen_tts_installed() checked presence via 'import qwen_tts', which pulls
transformers AutoProcessor -> torchao and crashes on Windows ROCm unless the
torchao stub is already installed. That crash surfaces as an ImportError, so the
check misread an installed-but-not-yet-stubbed package as broken and raised,
500ing /voice/load (dead orb, no dictation, no speech). It only worked when some
other code path stubbed torchao first in the process -- hence the intermittency.

Use importlib.util.find_spec() to check presence without executing the import;
the real 'from qwen_tts import' still runs in load_model after the stub. Also
declare qwen-tts + sox in extras-no-deps.txt so a fresh install ships them
(--no-deps), making the runtime pip-install a dev-only fallback.
Whisper is batch STT (one final transcript per utterance, no interim
results), but the voice loop's send path was built for streaming Web
Speech: a 1.5s transcript-growth silence timer stopped the mic and
checked composer text synchronously, before Whisper's async transcript
ever landed, so nothing was ever sent. Skip that timer for the whisper
engine and add a requestVoiceSubmit bridge the adapter calls once it has
committed the final transcript, letting the run/speak/re-arm cycle run.
@danielhanchen

Copy link
Copy Markdown
Member

The direction is good and I confirmed none of this exists on main yet, but the branch also carries the Listen modal for trained TTS LoRAs and the whole studio/benchmarks/voice harness alongside the voice loop. Could you rebase off the conflicts and split the benchmark harness and the Listen modal into their own PRs so the voice conversation path can be reviewed on its own?

@donaldfilimon

Copy link
Copy Markdown
Contributor

@BardiaKoopah @LeoBorcherding — I spent a while with this branch because I wanted the
feature and it looked close. It is closer than the conflict count suggests, but the
framing of "needs a rebase" is what has it stuck, so here is what I found, in case it
saves you the same afternoon.

The merge base is 7dc0857 (2026-06-23) and main is 2,230 commits past it. In that
window main independently shipped most of what this branch builds:

  • POST /audio/speech and POST /audio/transcriptions, dual-mounted on the inference
    router (studio/backend/routes/inference.py:16919 and :17107)
  • a six-module STT sidecar family (stt_sidecar.py, stt_ggml_sidecar.py,
    stt_mtmd_sidecar.py, stt_registry.py, stt_download_worker.py,
    stt_transformers_worker.py)
  • LoRAInfo.audio_type with detect_audio_type_checked
  • features/audio/audio-page.tsx, which already lists trained TTS checkpoints and plays
    them (isTtsAudioType / trainedTtsCheckpointIsLoadable, audio-page.tsx:2356)
  • both StudioDictationAdapter and StudioSpeechSynthesisAdapter, plus
    studio-model-dictation-adapter.ts and studio-web-speech-dictation-adapter.ts

So a good chunk of the 6.3k lines here now has an equivalent upstream, and the conflicts
are mostly that overlap rather than genuine disagreement.

One consequence for the split @danielhanchen asked for: the Listen modal is already
done.
The Audio page covers it. The three-way split is really a two-way split, which is
less work than it sounds like.

A latent break worth knowing about before you rebase. LlamaCppBackend.load_model
now takes a single immutable GgufLoadIntent
(studio/backend/core/inference/llama_cpp.py:504, :18104). /voice/load still calls it
with seven keyword arguments, so the first request raises TypeError, which the route
catches and returns as a 500 Failed to load voice model: .... Easy fix once you know,
but it will not show up until you actually load a voice.

What is genuinely still missing from main, and is the real value of this PR:

  1. the speech-to-speech conversation loop itself. There is no voiceMode, orb, or
    barge-in anywhere upstream.
  2. a second llama-server slot for the voice. _generate_tts_wav only ever calls
    get_llama_cpp_backend(), so today you cannot hold a chat LLM and a TTS model
    resident at the same time. This is the structural piece and nothing upstream replaces
    it.
  3. streaming PCM TTS, Qwen3-TTS, and the benchmark harness.

On the Codex threads: the ones anchored in routes/audio.py go away with that file,
since the equivalent endpoints now live in routes/inference.py. The ones that still
apply on any rebase are the training guard on /voice/load, refcounting the shared audio
codec so unloading one slot cannot pull it out from under the other, per-slot pidfiles so
the orphan reaper sees both llama-servers, and refusing auto-send while TTS is audible
(otherwise the loop transcribes the model's own voice and sends it back as the user's
next turn).

I reconstructed the loop and the voice slot on top of current main locally while working
through this, so the frontend gates and lints pass there. Happy to open it as a PR you can
cherry-pick from, or to just hand you the branches, or to stay out of the way entirely if
you would rather rebase it yourselves. Whichever is most useful. It is your feature and
your credit either way.

@donaldfilimon donaldfilimon left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

...

@danielhanchen

Copy link
Copy Markdown
Member

The speech-to-speech loop and the second voice slot are still the parts main does not have, but the Listen modal is now covered by the Audio page and /audio/speech already lives in studio/backend/routes/inference.py, so a rebase should drop a lot of this; note LlamaCppBackend.load_model now takes a single GgufLoadIntent (studio/backend/core/inference/llama_cpp.py:18722), so /voice/load needs updating. Could you narrow this to the conversation loop plus the two-slot backend and move the benchmark harness to its own PR?

@danielhanchen

Copy link
Copy Markdown
Member

The speech-to-speech loop and the second TTS slot are still the genuinely new parts here, but LlamaCppBackend.load_model now takes a single GgufLoadIntent (studio/backend/core/inference/llama_cpp.py:20199) so /voice/load will raise on the first call, and the Audio page already covers the Listen modal. Could you rebase, drop the Listen modal, and move studio/benchmarks/voice/ into its own PR so the conversation path can be reviewed on its own?

@donaldfilimon donaldfilimon left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

opening @claude

@donaldfilimon donaldfilimon left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

... changes updating to main ...

donaldfilimon added a commit to donaldfilimon/unsloth that referenced this pull request Sep 29, 2026
…enchmark

Split out of PR unslothai#6527 so the voice conversation path can be reviewed on its own.

Orpheus synthesizes the input utterances (cached), fed through STT -> LLM -> TTS
against a running Studio backend. Records per-stage wall clock and a
length-normalized rate (STT/TTS real-time factor, LLM tok/s) so a longer
utterance isn't counted as slower, with first-audio latency as the headline. It
also gates on accuracy -- STT word error rate, topical coverage, LLM determinism
-- so a speedup that hurts the answers is caught rather than celebrated.
Reasoning-aware: times the first SPOKEN token, and --think measures what a chat
model's chain of thought costs first audio. Writes JSON reports and diffs against
a baseline. Tokens, reports and fixtures are gitignored.

Independent of the voice-slot branch: STT and TTS go through
/v1/audio/transcriptions and /v1/audio/speech, which main already serves, and the
/api/inference/voice/status probe degrades to empty when that route isn't there.

Co-authored-by: LeoBorcherding <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01TSaSnTn9AUf4wPbCaTTykW
donaldfilimon added a commit to donaldfilimon/unsloth that referenced this pull request Sep 29, 2026
Rebuilds PR unslothai#6527 on today's main. The branch was cut from 2026-06-23 and main
has since landed its own audio stack, so roughly two thirds of the original diff
is now duplicate work and is dropped rather than merged:

- routes/audio.py in full. /audio/speech, /audio/transcriptions and the STT
  sidecar family already exist on the inference router, dual-mounted under /v1,
  monitored and body-capped. Streaming is added there as /audio/speech/stream
  instead of on a second router, so it inherits all of that.
- audio_type on LoRAInfo, detect_audio_type_from_local, and the scan_loras
  threading: superseded by audio_type/audio_type_known and
  detect_audio_type_checked.
- the Listen modal for trained TTS LoRAs: the Audio page lists and plays them.
- the Whisper dictation adapter, STT engine toggle, STT model selector and mic
  picker: superseded by StudioDictationAdapter, StudioModelDictationAdapter and
  the voice-settings store.
- Qwen3-TTS: an independent optional backend with an on-demand pip install,
  deferred to its own PR.

What is left is the part main does not have: a speech-to-speech conversation
loop, and a second llama-server "voice slot" so a TTS model can stay resident
beside the chat LLM. _generate_tts_wav prefers that slot when it is loaded, and
AudioSpeechRequest.voice is now honoured for named-speaker codecs instead of
being accepted and ignored.

The frontend half lands as its own module, features/chat/voice/: the loop and its
composer control in voice-engine.tsx, the orb's priority order as a pure tested
function in orb-state.ts, and the cross-remount registry in voice-loop-bridge.ts.
thread.tsx keeps the two mount points and the plus-menu item, +53 lines against
main rather than +751, so this path can be read, reviewed and reverted on its own.

Review findings addressed:
- /voice/load now runs _guard_chat_load_against_training, so enabling a voice
  during training is refused rather than placing another model (P1). It runs it
  through _offline_guarded, the way /load does.
- the shared audio codec is reference-counted, so unloading one slot no longer
  frees the codec the other is still decoding through. A manager nobody claimed
  is still freed, so a load cancelled between constructing it and claiming it
  does not leak it.
- each llama-server slot writes its own pidfile and the reaper sweeps them all;
  previously the second slot overwrote the first's record. The slot key is read
  off the instance rather than passed in, so _record_server_pid keeps the exact
  signature it has always had.
  Restoring that signature is also what keeps this branch from touching a single
  upstream test: an earlier draft widened it and broke the neutralising stubs in
  the shared llama_cpp placement fixture, which 46 test files reach through.
- voice mode is gated on the streaming speech-recognition engine, not on TTS
  alone, so it cannot be entered where no transcript can ever be produced.
- the silence timer no longer auto-sends while TTS is audible, which was posting
  echo of the model's own voice as the user's next message.
- switching the chat model to a speech-LLM now clears and unloads the separate
  voice slot instead of only greying out the picker.
- audio priming plays a real silent source, so the first clip is not refused by
  autoplay policy.
- browser-speech completion is tied to its request id, so a cancelled utterance
  cannot end the new one early.
- when the backend produces no audio for a whole reply, it falls back to browser
  speech rather than going silent.

Found while porting: the streaming path bypassed neutralize_tts_prompt_text
(unslothai#7066) and chose a decode device without consulting holds_no_vram; both fixed.
The TTS player read the store's voiceSlotLoaded through a local shadow that
meant "a voice is selected", so the first synth of a turn could POST into a slot
that had not finished loading. The voice download path sized itself off
size_bytes where every other download path uses download_size_bytes ||
size_bytes, which under-reports a sharded GGUF. The PCM player assumed 24 kHz
instead of reading the X-Sample-Rate header the stream route already sends.

Not verified end to end: this needs a GPU, a llama-server, TTS weights and a
browser, none of which were available, so no claim is made that the loop
speaks. What did run, on macOS against the CI commands: ruff 0.15.12, compileall,
the four custom linters, tsc -b plus the test project, the strict i18n parity
check, the frontend unit suite (6,858 pass), vite build, the bundle budget, and
the backend pytest suite in both its parallel and serial passes. Every backend
failure left on this machine reproduces identically on origin/main.

Co-authored-by: Bardia Koopah <[email protected]>
Co-authored-by: LeoBorcherding <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01TSaSnTn9AUf4wPbCaTTykW
@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Closing as superseded, not rejected. The conversation loop, the second voice slot and the benchmark harness were rebuilt on current main in #12384, #12385 and #12386 (also consolidated in #12265), with the original commits credited. The Listen modal and /audio/speech parts landed separately through the Audio page. Thanks @BardiaKoopah for the original work.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 1, 2026
…f a truncated label (unslothai#12386)

* fix(studio/chat): keep an audio model's reply text beside its player

The non-streaming audio path renders only <audio-player> and drops
result.choices[0].message.content on the floor. The model returns both -- the
clip and the text it spoke -- and the text is the half that is searchable,
copyable, readable on a muted device, and available to a screen reader.

Show the player above it, which is how a message with an attachment already
reads elsewhere in the thread. A reply with no text renders exactly as before.

Extracted from PR unslothai#6527, where it was one hunk inside a much larger branch; it
is independent of the voice conversation mode and of every other part of it.

Co-authored-by: Bardia Koopah <[email protected]>
Co-authored-by: LeoBorcherding <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TSaSnTn9AUf4wPbCaTTykW

* fix(studio/chat): render the text an audio model spoke below its player

The adapter now keeps the reply text beside the player tag, but the Markdown
renderer short-circuited on the tag and returned only the AudioPlayer, so the
transcript was stored and never shown. The tag is split out before the text
reaches the Markdown pipeline (a React-free helper, so it is unit-testable) and
the player renders above the remaining text; a clip-only reply renders exactly
as before. The conversation export already replaced the tag in place and kept
the surrounding text, so it needed nothing.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(studio/audio): answer /audio/generate with the text the clip speaks, whole

choices[0].message.content was a diagnostic label, '[Generated audio from:
"<text[:100]>"]', which the chat now renders under the player and keeps in
history. It is the spoken text itself now. The adapter drops the old label if
an older backend still sends it, so it is never shown as something the
assistant said.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* test(studio/audio): pin the transcript reply, and drop an older backend's label

The previous commit changed /audio/generate to answer with the spoken text but
landed without its test or the adapter's guard. This adds both: the route test
asserts a 200-character prompt comes back whole, and spokenReplyText drops the
old '[Generated audio from: ...]' label if an older backend still sends it, so
diagnostic text is never rendered as the assistant's words.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Copy an audio reply's spoken text, not the base64 player tag

* Trim comments in the audio reply text change

* Drop a narrating test comment

* Drop the chat rendering of the spoken text: it repeats the user's own message

---------

Co-authored-by: donaldfilimon <[email protected]>
Co-authored-by: Bardia Koopah <[email protected]>
Co-authored-by: LeoBorcherding <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
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.

5 participants