Skip to content

Unsloth Desktop: Voice Mode on the current audio stack (reconstruction of #6527, part A) - #10373

Closed
donaldfilimon wants to merge 23 commits into
unslothai:mainfrom
donaldfilimon:voice/pr-a-conversation-mode
Closed

donaldfilimon wants to merge 23 commits into
unslothai:mainfrom
donaldfilimon:voice/pr-a-conversation-mode

Conversation

@donaldfilimon

Copy link
Copy Markdown
Contributor

Summary

This is the conversation-loop half of #6527 by @BardiaKoopah and @LeoBorcherding, reconstructed on top of current main as offered in this comment. The feature and the credit are theirs; this PR exists so it can be cherry-picked or merged without the 2,230-commit rebase.

What main already had (/audio/speech, /audio/transcriptions, the STT sidecar family, the Audio page, both dictation adapters) is not duplicated here. What this adds is what main still lacks:

  • the speech-to-speech conversation loop itself (voiceMode, the orb, barge-in on the streaming engine)
  • a second llama-server slot so a chat LLM and a TTS model can be resident at once; _generate_tts_wav currently only ever calls get_llama_cpp_backend()
  • /voice/load rewritten onto GgufLoadIntent (the original 7-kwarg call would 500 on first use)
  • streaming PCM TTS on /audio/speech/stream, honouring AudioSpeechRequest.voice
  • the conversation loop running on the batch transcription engines too (meter-driven end-of-utterance; barge-in deliberately not wired for batch engines, since a transcript that arrives only at the end cannot be echo-checked)
  • carried from the Codex review threads on Feature/voice conversation mode v2 #6527: the training guard on /voice/load, refcounting the shared audio codec, per-slot pidfiles, and refusing auto-send while TTS is audible

Test plan

  • Lint tier: compileall, ruff 0.15.12, all four custom CI linters
  • Frontend: typecheck, i18n strict, 6851 unit tests, build, bundle:check
  • Backend: CI's own studio-backend invocation, 135 failed / 36,850 passed / 309 skipped; every one of the 135 also fails identically on the merge-base, so none is attributable to this branch (details in the linked comment)
  • CI's serial 11-file step: 0 failed
  • Not exercised here: a microphone and a browser. This typechecks, builds, and passes the unit suite; nothing in this PR claims the loop speaks until someone with hardware runs it

Co-authored with the original authors' work preserved in the commit trailers.

🤖 Generated with Claude Code

donaldfilimon and others added 2 commits September 4, 2026 04:57
Rebuilds PR #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
(#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
…ion engines

Voice mode was offered only when Settings -> Voice was set to the browser's Web
Speech engine, and hidden otherwise. Under Tauri the default is "model", so the
desktop app never showed Voice at all.

The reason was real: the loop's turn-taking watches the transcript grow, and a
batch engine ("model" or "custom") returns one transcript when the session ends,
so nothing grows and the 1.5s silence timer would close the mic and find an empty
composer every time. The loop now owns end-of-utterance for those engines
instead, from the microphone meter both adapters already publish through
startDictationLevelMeter. No change to any adapter.

- 900ms of quiet after real speech ends the turn: above the model adapter's own
  280ms segment cut, below the streaming engine's 1.5s. Quiet before the user has
  said anything is just the room, so an idle mic listens indefinitely.
- the same meter drives voiceHearing for BOTH engines, and closing the mic sets
  voiceTranscribing. Those two store fields had readers and orb states but no
  writer anywhere; this supplies them.
- submitTranscript, which was written for this path and unreferenced, is what
  sends the result, so a batch turn takes exactly the same send, coalesce and
  re-arm path as a streaming one.

Barge-in is deliberately NOT wired for the batch engines, and the mic is not
armed during playback for them either. Their session records continuously and
transcribes the whole recording on stop, so a mic open while the model speaks
would post the model's own words back as the user's next message, and a
transcript that only arrives at the end cannot be echo-checked after the fact.
The streaming engine survives this because its barge-in requires the transcript
to grow and its silence timer drops anything heard while audio is audible.
Doing it properly needs acoustic echo cancellation on the capture stream. Until
then the batch loop is listen, transcribe, generate, speak, listen again.

Unexercised: this needs a microphone and a browser. It typechecks, builds, and
the unit suite is green, and that is the whole of the claim.

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
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-06T15:51:09.011268Z 1c12d16 New commits
🔒 Security Review ✅ Completed 2026-09-06T15:53:19.905282Z 1c12d16 New commits
ℹ️ About Codex in GitHub

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

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

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3596149b30

ℹ️ 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 Resolved
Comment thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
donaldfilimon and others added 2 commits September 6, 2026 05:29
…e event loop

Review follow-ups on the voice slot (PR #10373):

- Training coordination now sees the voice slot. summarize_resident_chat()
  reports it under a new "voice" key and counts it toward "any"/"loading",
  and free_chat_models_for_training() unloads it in its own isolated block
  (voice:<name>), with the same CPU-only exemption as the chat slot. Without
  this a training start could unload the chat model and launch beside a
  second llama-server it never knew about. Covered by six new cases in
  test_training_vram_coexistence.py; _patch_backends grows a voice= stub.
- /voice/load resolves ModelConfig.from_identifier() via asyncio.to_thread
  under _hf_offline_if_unreachable_for, exactly as /load does, instead of
  scanning the HF cache on the event loop.
- /voice/unload and both /voice/load error-path teardowns run unload_model
  through asyncio.to_thread, as /unload does.
- /audio/speech/stream refuses IQ1/IQ2/Q2 Orpheus quants with a 400 before
  the monitor row opens: the spoken-name trim needs the whole clip, and the
  client already falls back to the blocking route on a non-OK response.
- The stream's read timeout stays flat, now documented and expressed via
  _GGUF_AUDIO_READ_TIMEOUT: httpx applies it per socket read, so on a
  token-by-token stream it bounds a stall between tokens, not the whole clip.

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

Review follow-ups on the conversation loop (PR #10373):

- A PCM stream that scheduled nothing (network failure, or a 200 that closed
  before its first chunk) now resolves as unplayed, so the caller falls back
  to the blob path and then the browser voice instead of advancing the loop
  in silence. A superseded request still reads as played, so a barge-in
  never triggers a fallback.
- speak() ends the turn (onPlaybackEnd) when normalization strips the whole
  reply, so an emoji-only answer no longer leaves voice mode with a dead mic.
- Browser-speech onend/onerror ignore events from a request that is no
  longer current, so a cancelled utterance's late error cannot cancel the
  replacement reply's queue.
- The coalesce timer re-arms while the barged-in run is still settling
  (bounded, ~10s) and only starts a run behind a trailing user bubble, so the
  appended bubbles get their reply once cancelRun() completes.
- A spoken utterance clears only the active thread's prompt queue via the
  new resetPromptQueuesForThread; resetPromptQueues is module-private again.
- useVoiceAvailable gates on listening alone: the picker always offers a
  local GGUF voice and the browser voice ends the turn cleanly without
  speechSynthesis, so the old TTS half hid the menu where the local voice
  was the only way to speak.
- Speech-LLM detection reads the model record's audioType first and falls
  back to the name pattern, so a renamed fine-tune still clears and unloads
  the voice slot. It lives in a dependency-free voice/speech-llm.ts with the
  codec sets moved to voice/tts-audio-types.ts (re-exported unchanged from
  use-tts-player), and has a node:test suite.

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

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All twelve findings were checked against the code; eleven are fixed in two commits on top of pre-commit.ci's f765200 (backend ffdd86d, frontend 5a41376), and one is answered below.

# Finding Result
1 Include the voice slot in training VRAM coordination (P1) Fixed in ffdd86d. summarize_resident_chat() reports a voice entry (counted in any and loading) and free_chat_models_for_training() unloads the voice llama-server too, with the same CPU-only exemption as the chat slot. This is the one change outside the PR's original footprint: the PR introduced the second GPU-resident server and already guarded the other direction in /voice/load, so completing the pair belongs here. Six tests added to test_training_vram_coexistence.py.
2 Fall back to one-shot audio for low-quant Orpheus Fixed in ffdd86d. /v1/audio/speech/stream now returns 400 when _orpheus_voice_prefix_ok() is false, before the monitor row opens; the client's existing non-OK path falls back to the blocking route, which trims the spoken prefix.
3 Keep local TTS selectable without browser speech synthesis Fixed in 5a41376. useVoiceAvailable gates on listening only. Speaking is always satisfiable: the picker always offers the local GGUF default, and the browser voice already ends the turn cleanly when speechSynthesis is absent.
4 Detect speech models from capabilities instead of names Fixed in 5a41376. Detection reads the model record's audioType first and falls back to the name pattern only for a checkpoint not yet in the inventory. Extracted to voice/speech-llm.ts with a node:test suite, and the three call sites in chat-page.tsx now share one value.
5 Report an empty or failed PCM stream as unplayed (P1) Fixed in 5a41376. The finally resolves `started
6 Resume listening when speech normalization removes all text Fixed in 5a41376. An empty normalized utterance now invokes onPlaybackEnd so the loop re-arms the microphone.
7 Guard stale browser-speech errors before cancelling playback (P1) Fixed in 5a41376. Both onend and onerror bail on a stale request id before touching playback state or the global queue.
8 Clear only the active thread's prompt queue (P1) Fixed in 5a41376. New resetPromptQueuesForThread(id) in thread.tsx (delete-only, via getPromptQueueRunsForThreadIds); resetPromptQueues is module-private again. Nothing is cleared when there is no active thread id.
9 Retry the coalesced run after cancellation settles (P1) Fixed in 5a41376. The coalesce timer re-arms every 650 ms for up to 15 tries while the old run is still marked running, and starts a run only behind a trailing user bubble so a reply that landed meanwhile is not regenerated over.
10 Resolve voice model metadata off the event loop Fixed in ffdd86d. /voice/load runs ModelConfig.from_identifier through asyncio.to_thread inside _hf_offline_if_unreachable_for, as /load does.
11 Move voice teardown off the event loop Fixed in ffdd86d. /voice/unload and both /voice/load error teardowns await asyncio.to_thread(unload_model).
12 Scale the streaming TTS timeout with the token budget Not changed, on purpose. httpx applies the read timeout per socket read, and this response is consumed token by token via client.stream + iter_lines(), so 300 s bounds the gap between two tokens (a stalled server), not the whole clip. The blocking path scales because its single post waits for the entire generation. Scaling the stream would only delay noticing a wedged server. The literal is now the named _GGUF_AUDIO_READ_TIMEOUT with a comment saying why it is flat.

Gates on the pushed head: frontend typecheck and test pass (the new detection suite included); [email protected] check passes on the touched backend files; test_training_vram_coexistence.py 54/54.

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

ℹ️ 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 Resolved
Comment thread studio/backend/routes/inference.py Resolved
donaldfilimon and others added 2 commits September 6, 2026 06:08
… voice n_ctx

Second review round on the voice slot (PR #10373):

- /audio/speech/stream joins _INFERENCE_SUFFIXES. The tuple is an endswith
  test and the route ends in /stream, so the /audio/speech entry never covered
  it: with the stream as the only inference in flight, an API-key training
  start saw other_inference_request_count() == 0, unloaded the voice backend
  and cut the live PCM clip off instead of returning 409. Now that the route
  is tracked, its generator's swallowed-error arm also flags the response
  failed (mark_current_response_failed), since it ends the stream cleanly at
  200 and the middleware would otherwise read a failed clip as a completion
  that claims a preview-owned chat slot.
- _VoiceLoadRequest.n_ctx takes the same MAX_REQUESTABLE_CONTEXT ceiling as
  LoadRequest.max_seq_length. The handler models the load as a chat
  LoadRequest for the training-coexistence guard, so an oversized value used to
  pass validation and then fail inside the handler as a 500, after the HF
  resolve, instead of a 422 up front.

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

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

ℹ️ 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 Resolved
Comment thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
donaldfilimon and others added 2 commits September 6, 2026 11:40
…pened

Two defects found uncommitted in the working tree.

The voice model selector expanded GGUF entries with `onDevice`, which
honors the global "Show all quantizations" setting (off by default) and
lists only quants already on disk. On a fresh install the uncached default
voice therefore expanded to "No GGUF variants found" and its first-use
download could never start. Every row downloads a missing quant on pick,
so the browse listing is the correct one here.

VoiceEngine called endStream unconditionally at run end, including for a
run that began before the user switched voice mode on — where no TTS
session was ever opened. Track whether the run-start branch actually
opened one and flush only then.

Verified with `npm run typecheck` in studio/frontend (exit 0). This is a
third-party upstream clone with no local gate of record; upstream CI
remains the real gate for the Python side.

Co-Authored-By: Claude Opus 5 <[email protected]>

@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: 1c12d16413

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

@donaldfilimon donaldfilimon left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@donaldfilimon donaldfilimon left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reviewed

@LeoBorcherding

LeoBorcherding commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

thank you @donaldfilimon this is a great amount of work you have done rebasing the prs. i will run this and review it so that we can get this feature merged

…p's half-duplex gaps

Running this branch in the desktop app, the loop cut its own reply about a word
in and left empty transcripts flickering through the composer. The causes were
all on the listen/speak boundary, so this brings back the #6527 frontend that
owned it and fixes what the port exposed.

Restored from #6527:

- StudioWhisperDictationAdapter, which owns a turn end to end: capture, energy
  VAD with two-threshold hysteresis, transcribe, commit, re-arm. Rebased onto
  the current stack, so it resolves models through the STT registry
  (loadSttModel / requestSttDownload / transcribeAudioBlob) instead of letting
  the backend pick, which was 400ing on an undownloaded 'small'.
- The streaming TTS player, whose replacement clipped audio between sentences.
- The STT model and microphone pickers, repointed at the current model-selector
  components and the renamed store fields.
- The sentence chunker, now in its own dependency-free module so it can be
  tested without pulling in React and auth. It keeps abbreviations, decimals,
  initials and closing quotes attached, and stripForSpeech no longer collapses
  the newlines the splitter needs, which had made a multi-paragraph reply one
  synth request. Nine tests cover it.

Fixed on top:

- resumeListen had no half-duplex guard. On a batch STT engine the mic re-armed
  during playback, heard the model through the speakers, and tripped the
  adapter's own barge-in ~220ms in. It now defers the re-arm (rather than
  dropping it, which would dead-end the loop) until generation and playback are
  done, and energy barge-in is ignored on batch engines, matching the rule
  already written into armDuringTts.
- An empty transcript went down the barge-in path and called stop() before the
  emptiness was checked, so a silent turn cut audio that was still playing.
- Streaming synthesis was strictly serial: each sentence waited for the previous
  one to finish *playing*, and voiceParallelN never reached that path at all, so
  a configured voice slot sat with an idle llama-server slot. Sentences now
  generate up to voiceParallelN ahead, gated so they still schedule in order,
  onto one shared playhead -- the jitter buffer is paid once per reply instead of
  at every sentence boundary. N=1 collapses to the old serial behaviour.

The blob fallback is gated on the same chain: a Q2 Orpheus quant is refused
streaming by the backend and 400s in milliseconds, so an ungated window would
start every sentence's fallback at once and stamp them over each other on the
shared audio element.

Not verified: the audible result on hardware is the reporter's to judge; there
is no mic or speaker in CI. Typecheck is clean and the frontend suite passes.
@LeoBorcherding

LeoBorcherding commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

thanks for picking this up, seriously. rebuilding it on the current audio stack and splitting it the way daniel asked was the right call and it's more work than the diff makes it look.

pushed 8d4141a on top of your head commit. i've had the branch running locally in the desktop app (q4 orpheus voice slot, qwen3-asr for listening) and ended up pulling a good chunk of the old #6527 frontend back in. not on principle, the turn-taking bugs i kept hitting all lived in the pieces that got rewritten. three real ones:

  • the mic re-arms while the model is still talking. on a batch stt engine it hears the reply through the speakers, decides someone is talking over it, and cuts its own sentence off about a word in. resumeListen now holds the re-arm until generation and playback are done, rather than dropping it, which would dead-end the loop.
  • a silent turn went down the barge-in path, so an empty transcript stopped audio that was still playing. the empty check happens first now.
  • sentences were synthesized strictly one at a time, each waiting for the previous one to finish playing before the next was even requested, and the parallel synthesis setting never reached that code at all. they now generate up to voiceParallelN ahead, gated so they still schedule in order, onto one shared playhead. the jitter buffer gets paid once per reply instead of at every sentence boundary. n=1 collapses back to the old behaviour.

that plus the old dictation adapter, tts player, stt/mic pickers and sentence chunker (with tests) is about 1400 lines, all frontend. typecheck clean, frontend suite green. no backend files touched.

left the main merge alone. conflicts are in llama_cpp.py, your _pid_slot against the new spawn locking, figured that one's yours to call.

@danielhanchen

Copy link
Copy Markdown
Member

Thanks for rebuilding this on the current audio stack and splitting it the way we asked. I read through the second-slot work and the parts that worry me are outside the voice path, namely the _record_server_pid and _reap_recorded_pid rework in llama_cpp.py and the new voice import inside summarize_resident_chat and free_chat_models_for_training. Could you resolve the _pid_slot conflict against main's spawn locking and confirm chat-only startup reaping and training auto-unload still behave as before, and let me know once you and Leo have settled whose head commit is the one to review?

donaldfilimon and others added 2 commits September 15, 2026 23:32
Resolves the five conflicts against upstream main. The one Daniel asked about
is `_pid_slot` against main's new spawn locking (#10592):

- `llama_cpp.py`: main's `_spawn_lock` / `_teardown_lock` and the locked spawn
  blocks are taken whole, with the PR's slot-aware `_record_own_server_pid`
  substituted for `_record_server_pid` at both call sites. Main never changed
  the pid-helper definitions, only moved the call sites under the lock, so the
  two changes compose rather than compete. The chat slot keeps the identical
  single-argument path and the identical pidfile path (`_slot_pidfile_path("")`
  returns the base path), so startup reaping is unchanged when no voice slot has
  ever been recorded.
- `audio_codecs.py`: main's `_load_snac(model_repo_path)` signature, plus the
  PR's `has_codec`.
- `routes/inference.py`: main's `requested_model` budgeting and `require_speech`
  switch are taken whole and wrapped in the PR's voice-slot guard, and the guard
  now also requires that no model was named. A caller that names a model keeps
  main's path exactly: the voice slot owns speech only for the resident-model
  form, which is what voice conversation mode sends.
- `check-bundle-budget.ts`: main's re-measured budget, not the PR's older raise.
- `thread.tsx`: main's dock inset and dictate-button sizing, with the PR's
  `voiceOrbActive` z-index and voice-mode wrapper.

Co-Authored-By: Claude Opus 5 <[email protected]>
…dent-model form

The main merge takes main's named-model switch in _generate_tts_wav and wraps
it in the voice-slot guard, and the guard now also requires that no model was
named. Nothing pinned that seam: the existing pre-switch-budget test runs with
no voice slot loaded, so it could not tell a bypass that ignores a named model
from one that honours it. The conversation loop sends {input, voice} with no
model, so it takes the voice slot; a named /v1/audio/speech request reaches the
switch even with the voice slot loaded.

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

@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: 160319f4c5

ℹ️ 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 Resolved
…stored frontend

Of the ten review threads left unresolved on #10373, six were already fixed at
the head (voice teardown and metadata off the event loop, /audio/speech/stream
tracked by llama_keepwarm, n_ctx bounded by MAX_REQUESTABLE_CONTEXT, the
coalesced run retried until cancelRun settles, the mid-run activation speaking
the finished reply, the default voice's variants offered as a browse listing).
The other four needed code, two of them because the #6527 frontend restoration
(8d4141a) rewrote the TTS player and dropped fixes that had landed in 5a41376:

- use-tts-player.ts: an emoji-only or markup-only reply ends the turn again
  through onPlaybackEnd instead of returning with the mic shut; the browser
  branch is the guarded speakWithBrowser again, so a cancelled utterance's
  late onend/onerror cannot cancel the replacement reply's queue.
- use-tts-player.ts: a sentence the backend fails to synthesize mid-reply is
  spoken in order with the browser voice (speakSentenceWithBrowser) at all four
  playback sites, instead of being dropped while the loop advances as though it
  had been spoken. stopSynth() cancels it on barge-in like any utterance.
- chat-page.tsx: /voice/load takes an attempt number; a download rollback, a
  failure, or a success that no longer holds the current number leaves the
  store alone, and loads are serialised on the in-flight request so the last
  pick is the last one llama-server sees.

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

Copy link
Copy Markdown
Contributor Author

Thanks both. Merged main into the branch (merge commit 8d61b69, not a rebase, so Leo's checkout stays valid), with a follow-up test at 160319f and the last four open Codex threads closed at 46b414c. Answering the three asks:

Whose head commit to review. Leo's 8d4141a is in the branch: I fast-forwarded onto it before merging, so the head to review is 46b414c, which contains his frontend restoration, the main merge, the test, and the review fixes. One head, no fork between us.

The _pid_slot conflict against the spawn locking (#10592). Main never changed the pid-helper definitions, only moved the two _record_server_pid call sites under _spawn_lock. So the resolution takes main's locked spawn blocks whole (including both stale-shutdown rechecks) and substitutes the slot-aware _record_own_server_pid at the same two sites. _pid_slot sits beside _spawn_lock/_teardown_lock as a class attribute for the same reason those are: teardown runs on backends built through __new__.

Chat-only startup reaping and training auto-unload are unchanged. Three things make that a measurement rather than a promise:

  • The chat slot (_pid_slot == "") calls _record_server_pid(pid) with the single argument it always took, and _slot_pidfile_path("") returns the base pidfile path, so an install with no voice slot ever recorded writes and reaps exactly the file it did before. _reap_recorded_pid globs the base plus -<slot> siblings, so with no voice pidfile present it reaps the one file.
  • summarize_resident_chat() and free_chat_models_for_training() each gained the voice slot as a third, independent try/except block after the two existing ones; a failing voice import logs and falls through, and the chat and HF blocks are what they were.
  • Tests on the merged tree: test_training_vram_coexistence.py 54 passed; test_mcp_training_start_guard.py 18 passed; test_openai_audio_speech_route.py, test_gguf_tts_audio_type.py, test_audio_tts_cancellation.py 93 passed (that includes main's named-model /v1/audio/speech cases); test_llama_cpp_wait_for_health.py's spawn-lock suite, including test_the_published_child_survives_post_spawn_setup, which stubs _record_server_pid and still sees the pid through the slot wrapper. Across the 47 llama_cpp/inference/audio test files that collect without torch, 2051 passed; the seven that fail on my Mac fail identically on upstream main in a clean worktree (Linux-only /proc asserts, missing torch, and test_a_started_shutdown_refuses_to_spawn, which is red on main here too).

One deliberate change in the resolution, called out so it is not a surprise: in _generate_tts_wav, main's requested_model budgeting and require_speech switch are taken whole, and the voice-slot bypass now also requires that the caller did not name a model. A /v1/audio/speech request with model set follows main's path exactly; the voice slot owns speech only for the resident-model form. That is what the conversation loop sends: use-tts-player.ts posts {input, voice} with no model to both /audio/speech and /audio/speech/stream, and /audio/generate sends none either. 160319f pins both halves (test_a_loaded_voice_slot_serves_only_the_resident_model_form).

Frontend on the merged tree: typecheck clean, 7733 tests pass, build and bundle:check pass under main's re-measured budget with 53.5 KB transfer / 158.5 KB raw to spare, so the PR's own earlier budget raise was dropped in favour of main's. The thread.tsx conflicts kept both sides: main's dock inset and dictate-button sizing inside the PR's voiceOrbActive z-index and voice-mode wrapper. pre-commit.ci's red was the merge conflict itself, not a hook; ruff and the kwarg formatter pass on every backend file the PR touches.

The ten Codex threads that were still unresolved are now answered inline and resolved. Six were already fixed at the head and only needed the thread closed; four needed code in 46b414c, two of them because the restoration in 8d4141a rewrote the TTS player and dropped fixes that had landed in 5a41376 (the empty-reply turn end and the stale-utterance guards), and two because they had never been done (the per-sentence browser fallback and the voice-load attempt fence). Typecheck, the 7733 frontend tests, build and bundle:check are green on 46b414c.

Drafted with Claude Code; the gates and measurements above were run locally on this head.

donaldfilimon and others added 3 commits September 16, 2026 00:11
… voice load

Picking the browser voice while a voice was still loading fired /voice/unload
at once, so the unload could race the load on the backend and the voice it was
loading came up under a store that says browser voice. The unload now waits for
the in-flight request and re-checks that browser voice is still the pick, the
same fence the load path already had.

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

Main's per-account isolation (#10588) gates /load and /validate on
account_access.require_model_access and replaces an absent hf_token with the
account's own before any resolution. /voice/load, written before that landed,
resolved the caller's identifier with the caller's token first, so in a
managed-account install the voice slot was a second door past both the grant
check and the ambient-credential rule. Same two calls, same order, up front.
Two tests: a denied grant is a 403 before ModelConfig.from_identifier runs, and
a permitted load resolves with the account token rather than the caller's.

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

@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: 9e78eda132

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

@donaldfilimon

Copy link
Copy Markdown
Contributor Author

@danielhanchen one correction, since settling the head was one of your three asks: my last comment named 46b414c, which was the head when I wrote it and was overtaken three commits later the same hour. The head to review is 9e78eda.

The two commits in between are not cosmetic:

  • 6c6ed0e (chat-page.tsx, 9 lines): picking the browser voice while a voice load was still in flight fired /voice/unload immediately, so the unload could race the load and the voice being loaded came up under a store reading "browser voice". The unload now waits on the in-flight request and re-checks the pick, the same fence the load path already had.
  • 873a7e8 (routes/inference.py +9, tests/test_openai_audio_speech_route.py +49): /voice/load predates main's per-account isolation (Studio: per-account isolation for shared installs and the desktop app #10588), so it resolved the caller's identifier with the caller's token before any grant check. In a managed-account install that made the voice slot a second door past both require_model_access and the ambient-credential rule. It now makes the same two calls in the same order as /load and /validate, with a test that a denied grant is a 403 before ModelConfig.from_identifier runs, and one that a permitted load resolves with the account token.

Then 9e78eda merges current main on top.

Relevant to your specific concern: neither commit touches llama_cpp.py, so the _pid_slot resolution and the chat-only reaping and training auto-unload behaviour are exactly as described in my previous comment. I have not re-run the full backend and frontend suites at this head, only at 46b414c, so treat those numbers as measured there; say the word and I will re-run them at 9e78eda before you start.

One head, still no fork between Leo's work and mine.

claude and others added 5 commits September 23, 2026 23:10
Resolves two conflicts against upstream main:
- llama_cpp.py: keep main's rule that the pidfile is cleared only once the
  child's exit is confirmed, and clear this backend's own slot pidfile
  (_clear_own_server_pid) rather than the chat slot's.
- thread.tsx: keep main's --ui-space-scale composer-dock inset and the
  branch's voice-orb z-index lift.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HdL6vCyq1LbkqH3WpH9mMz
…ast setting

Main's contrast-slider test now rejects fixed-alpha washes in chrome. The
voice and STT model selectors drew their separators with bg-black/[0.08]
and bg-white/[0.08]; they now use the gain-aware spelling the chat settings
sheet already uses for the same separator, which resolves to the same colour
at the default contrast.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HdL6vCyq1LbkqH3WpH9mMz
…live across chats

Browser speech is gone from the conversation loop. "Browser voice" and
"Browser" listen are removed from the header pickers, the loop always uses
a local transcription model and the voice slot, and the speechSynthesis
fallback in the player is gone: a sentence the slot cannot synthesize now
toasts once instead of switching to a system voice mid-reply. The Dictate
button's own browser engine in Settings is untouched; the no-speech hook
this PR had added to the web-speech adapter is reverted since nothing in
voice mode reaches it any more.

Opening voice with no chat model used to arm the mic and sit on
"Listening" with nothing to answer. The orb now has a "waiting" state
("Select a model"), the mic stays shut, and it arms itself when a model
loads. Starting a new chat no longer turns voice off: the thread-switch
reset cuts the old turn and re-arms on the new thread, the same way the
loaded model survives.

The microphone picker leaves the STT dropdown; the loop reads the device
chosen in Settings > Voice, adopts a pin made in the old picker on first
load, and falls back to the default input when a pinned mic is unplugged.
Parallel synthesis moves behind a gear in the "Speak with" header and
gets a row in Settings > Voice. Exported voices show their name instead
of a full filesystem path (loraOptionLabel). Opening voice seeds the last
used or default voice, since null no longer means "browser".

Header order is listen, speak, speaker name. The idle orb uses theme
tokens (--voice-orb-idle-*) in light and dark rather than a fixed grey;
the overlay fades in 200ms and stops animating while minimized. The two
STT sidecars spawn with the same hidden-window kwargs as llama-server so
whisper-server and the MTMD server no longer open console windows under
the desktop shell.
@LeoBorcherding LeoBorcherding changed the title Studio: voice conversation mode on the current audio stack (reconstruction of #6527, part A) Unsloth Desktop: Voice Mode on the current audio stack (reconstruction of #6527, part A) Sep 24, 2026
@donaldfilimon

Copy link
Copy Markdown
Contributor Author

This closed because its source fork was deleted, not because of review. The work, rebased on current main along with the fixes made since, continues in #12265, which consolidates #10373, #10374 and #11074 as separate --no-ff merges so each part can still be reviewed or reverted on its own.

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