The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(stt): live transcription while you speak on CLI, TUI and Desktop (stt.streaming)
Teknium00adf69d925f
diff --git a/agent/transcription_provider.py b/agent/transcription_provider.pyindex 647dbe644d6..fa34d6ee583 100644--- a/agent/transcription_provider.py+++ b/agent/transcription_provider.py@@ -34,3 +34,33 @@ class TranscriptionProvider(CatalogProviderBase):``prompt`` (from ``stt.prompt`` or a ``pre_transcription`` hook) as a vocabulary hint;unknown keys must be ignored."""++ @property+ def streaming_capable(self) -> bool:+ """True when :meth:`open_stream_session` can transcribe live 16 kHz mono s16le PCM+ (``stt.streaming``). Default False: only the file-based :meth:`transcribe` is used."""+ return False++ def open_stream_session(+ self, *, language: Optional[str] = None, prompt: Optional[str] = None,+ ) -> "TranscriptionStreamSession":+ """A single-use live session for one utterance (streaming-capable providers only)."""+ raise NotImplementedError(f"{self.name} does not support live streaming transcription")+++class TranscriptionStreamSession(abc.ABC):+ """Live audio -> transcript for one utterance. ``push_audio`` receives 16 kHz mono s16le PCM in+ any chunk size from one feeder thread; ``finalize`` flushes and returns the standard envelope+ (``success``/``transcript``/``provider``/``error``) and must not raise."""++ @abc.abstractmethod+ def push_audio(self, chunk: bytes) -> None:+ """Feed one chunk of 16 kHz mono s16le PCM."""++ @abc.abstractmethod+ def finalize(self) -> Dict[str, Any]:+ """End the session and return the transcription envelope (blocks until final)."""++ def partial_transcript(self) -> str:+ """Latest non-final text, polled for live captions. Default: none."""+ return ""diff --git a/apps/desktop/src/app/chat/composer/hooks/use-mic-recorder.ts b/apps/desktop/src/app/chat/composer/hooks/use-mic-recorder.tsindex 19d85469dbe..9ad6b38c54f 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-mic-recorder.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-mic-recorder.ts@@ -14,6 +14,10 @@ export interface MicRecorderOptions {silenceLevel?: numbersilenceMs?: numberidleSilenceMs?: number+ /** Live PCM tap (streaming dictation): mono s16le chunks at the meter context's rate, which+ * `onPcmRate` reports once before the first chunk. The MediaRecorder blob is unaffected. */+ onPcm?: (chunk: ArrayBuffer) => void+ onPcmRate?: (sampleRate: number) => void}export interface MicRecording {@@ -87,6 +91,7 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {const streamRef = useRef<MediaStream | null>(null)const chunksRef = useRef<Blob[]>([])const audioContextRef = useRef<AudioContext | null>(null)+ const pcmTapRef = useRef<ScriptProcessorNode | null>(null)const animationRef = useRef<number | null>(null)const startedAtRef = useRef(0)const heardSpeechRef = useRef(false)@@ -101,6 +106,8 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {animationRef.current = null}+ pcmTapRef.current?.disconnect()+ pcmTapRef.current = null// Null the ref before closing so the context's own 'closed' statechange// isn't mistaken for a meter failure.const audioContext = audioContextRef.current@@ -157,6 +164,10 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {source.connect(analyser)audioContextRef.current = audioContext+ if (options.onPcm) {+ startPcmTap(audioContext, source, options)+ }+// A device or renderer error kills the context without throwing// anywhere we'd see it; the analyser just goes flat. Watch for it.const failIfCurrent = () => {@@ -227,6 +238,30 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {}}+ // ScriptProcessor: deprecated but universal, and it needs no worklet module URL in the Electron+ // renderer. The host resamples, so chunks go out at the context's own rate.+ const startPcmTap = (audioContext: AudioContext, source: MediaStreamAudioSourceNode, options: MicRecorderOptions) => {+ const tap = audioContext.createScriptProcessor(4096, 1, 1)+ pcmTapRef.current = tap+ options.onPcmRate?.(audioContext.sampleRate)++ tap.onaudioprocess = event => {+ const input = event.inputBuffer.getChannelData(0)+ const pcm = new Int16Array(input.length)++ for (let i = 0; i < input.length; i += 1) {+ const sample = Math.max(-1, Math.min(1, input[i]))+ pcm[i] = sample < 0 ? sample * 0x8000 : sample * 0x7fff+ }++ options.onPcm?.(pcm.buffer)+ }++ // A tap only fires while connected through to the destination; its output buffer stays silent.+ source.connect(tap)+ tap.connect(audioContext.destination)+ }+const start: MicRecorderHandle['start'] = async (options = {}) => {if (recorderRef.current) {returndiff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.ts b/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.tsindex d93643eb85c..97647b8ce88 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.ts@@ -3,6 +3,8 @@ import { useEffect, useRef, useState } from 'react'import { type ResolvedOwner, resolveOwnerNow } from '@/hermes'import { useI18n } from '@/i18n'import { syncSttLease, VOICE_INPUT_LEASE } from '@/lib/stt-lease'+import { fetchVoiceClientConfigFor } from '@/lib/voice-client-direct'+import { type DictationStreamSession, openDictationStream } from '@/lib/voice-stream'import { recordFeatureUse } from '@/store/desktop-metrics'import { notify, notifyError } from '@/store/notifications'@@ -27,6 +29,8 @@ interface VoiceRecorderOptions {interface Dictation {owner: ResolvedOwnerwarmup: Promise<void>+ /** Live STT session (stt.streaming): resolves to null when the host has no live wire. */+ live?: () => Promise<DictationStreamSession | null>}export function useVoiceRecorder({@@ -45,6 +49,7 @@ export function useVoiceRecorder({ownerRef.current = { connectionId: ownerConnectionId, profile: ownerProfile }const [voiceStatus, setVoiceStatus] = useState<VoiceStatus>('idle')const [elapsedSeconds, setElapsedSeconds] = useState(0)+ const [partial, setPartial] = useState('')const startedAtRef = useRef(0)const intervalRef = useRef<number | null>(null)const timeoutRef = useRef<number | null>(null)@@ -110,7 +115,7 @@ export function useVoiceRecorder({return}- const transcript = (await onTranscribeAudio(result.audio, dictation.owner)).trim()+ const transcript = (await liveTranscript(dictation)) ?? (await onTranscribeAudio(result.audio, dictation.owner)).trim()if (!live()) {return@@ -134,11 +139,29 @@ export function useVoiceRecorder({}}+ // The live session's final text, or null to transcribe the recorded blob instead (no session,+ // socket failure, or an empty result over a take the recorder kept).+ const liveTranscript = async (dictation: Dictation): Promise<null | string> => {+ const session = await dictation.live?.()++ if (!session) {+ return null+ }++ try {+ return (await session.stop()) || null+ } catch {+ return null+ }+ }+// The transcript settled (or failed): this dictation no longer needs the// engine held. Released to the owner that acquired it. The backend keeps the// shared model resident regardless.const finish = (dictation: Dictation) => {dictationRef.current = null+ setPartial('')+ void dictation.live?.().then(session => session?.cancel())void syncSttLease(VOICE_INPUT_LEASE, false, dictation.owner)}@@ -150,14 +173,19 @@ export function useVoiceRecorder({}try {- await handle.start({ onError: error => notifyError(error, voiceCopy.recordingFailed) })+ const owner = resolveOwnerNow(ownerRef.current)+ const stream = liveStream(owner)+ await handle.start({+ onError: error => notifyError(error, voiceCopy.recordingFailed),+ onPcm: stream.push,+ onPcmRate: stream.open+ })// The mic is open, so a transcript is coming: warm the backend's STT// engine now so a cold local model loads while the user is still// speaking instead of inside the transcription timeout (#105955).// Fire-and-forget for the MIC UX β but keep the promise: stop() awaits// it as the readiness barrier before transcription (see above).- const owner = resolveOwnerNow(ownerRef.current)- dictationRef.current = { owner, warmup: syncSttLease(VOICE_INPUT_LEASE, true, owner) }+ dictationRef.current = { live: stream.session, owner, warmup: syncSttLease(VOICE_INPUT_LEASE, true, owner) }startedAtRef.current = Date.now()setElapsedSeconds(0)setVoiceStatus('recording')@@ -171,6 +199,43 @@ export function useVoiceRecorder({}}+ // Live dictation plumbing for one take: chunks captured before the socket opens are buffered+ // (bounded) and flushed, so the first words reach the provider too. `session()` is null when the+ // host has no live wire, or when the meter never reported a rate (no PCM tap this take).+ const liveStream = (owner: ResolvedOwner) => {+ let session: DictationStreamSession | null = null+ let settled = false+ let buffered: ArrayBuffer[] = []+ let opening: Promise<DictationStreamSession | null> | null = null++ const open = (sampleRate: number) => {+ opening = (async () => {+ const config = await fetchVoiceClientConfigFor(owner).catch(() => null)+ const opened = config?.stt.streaming ? await openDictationStream(owner, sampleRate, setPartial) : null++ for (const chunk of opened ? buffered : []) {+ opened!.pushAudio(chunk)+ }++ buffered = []+ settled = true+ session = opened++ return opened+ })()+ }++ const push = (chunk: ArrayBuffer) => {+ if (session) {+ session.pushAudio(chunk)+ } else if (!settled && buffered.length < 64) {+ buffered.push(chunk)+ }+ }++ return { open, push, session: () => opening ?? Promise.resolve(null) }+ }+const dictate = () => {if (recording) {void stop()@@ -182,6 +247,7 @@ export function useVoiceRecorder({const voiceActivityState: VoiceActivityState = {elapsedSeconds,level,+ partial,status: voiceStatus}diff --git a/apps/desktop/src/app/chat/composer/types.ts b/apps/desktop/src/app/chat/composer/types.tsindex f6b75dad09a..3a9aa509221 100644--- a/apps/desktop/src/app/chat/composer/types.ts+++ b/apps/desktop/src/app/chat/composer/types.ts@@ -73,5 +73,7 @@ export type VoiceStatus = 'idle' | 'recording' | 'transcribing'export interface VoiceActivityState {elapsedSeconds: numberlevel: number+ /** Live STT text so far (stt.streaming); '' when none. */+ partial?: stringstatus: VoiceStatus}diff --git a/apps/desktop/src/app/chat/composer/voice-activity.tsx b/apps/desktop/src/app/chat/composer/voice-activity.tsxindex e694229f5b9..f6193338ac8 100644--- a/apps/desktop/src/app/chat/composer/voice-activity.tsx+++ b/apps/desktop/src/app/chat/composer/voice-activity.tsx@@ -192,7 +192,9 @@ export function VoiceActivity({ state }: { state: VoiceActivityState }) {</div><div className="flex min-w-0 flex-1 items-center gap-2">- <span className="truncate font-medium text-foreground/85">{title}</span>+ <span className="truncate font-medium text-foreground/85" title={state.partial || undefined}>+ {state.partial || title}+ </span><span aria-hidden="true" className="font-mono text-[0.6875rem] text-muted-foreground/85">{formatElapsed(state.elapsedSeconds)}</span>diff --git a/apps/desktop/src/app/settings/constants.ts b/apps/desktop/src/app/settings/constants.tsindex 310ed1564a2..28826c6fa7f 100644--- a/apps/desktop/src/app/settings/constants.ts+++ b/apps/desktop/src/app/settings/constants.ts@@ -361,6 +361,7 @@ export const ENUM_OPTIONS: Record<string, string[]> = {],// STT model lists mirror STT_MODEL_CATALOG in tools/transcription_common.py.'stt.openai.model': ['whisper-1', 'gpt-4o-mini-transcribe', 'gpt-4o-transcribe', 'gpt-transcribe'],+ 'stt.openai.streaming_model': ['gpt-live-transcribe', 'gpt-transcribe', 'gpt-4o-transcribe', 'gpt-4o-mini-transcribe'],'stt.groq.model': ['whisper-large-v3-turbo', 'whisper-large-v3'],'stt.mistral.model': ['voxtral-mini-latest', 'voxtral-mini-2602'],'stt.xai.model': ['grok-voice-transcribe-2.0', 'grok-voice-transcribe-1.0'],@@ -485,12 +486,14 @@ export const FIELD_LABELS: Record<string, string> = defineFieldCopy({enabled: 'Speech To Text',echoTranscripts: 'Echo Transcripts',provider: 'Speech-To-Text Provider',+ streaming: 'Live Transcription',local: {model: 'Local Transcription Model',language: 'Transcription Language'},openai: {- model: 'OpenAI STT Model'+ model: 'OpenAI STT Model',+ streamingModel: 'OpenAI Live Transcription Model'},groq: {model: 'Groq STT Model'@@ -686,6 +689,7 @@ export const FIELD_DESCRIPTIONS: Record<string, string> = defineFieldCopy({stt: {enabled: 'Enable local or provider-backed speech transcription.',echoTranscripts: 'Post the raw ποΈ transcript of voice messages back to the chat.',+ streaming: 'Show text while you speak (OpenAI, xAI, ElevenLabs). Falls back to the recording on any failure.',elevenlabs: {languageCode: 'Optional ISO-639-3 language code. Blank lets ElevenLabs auto-detect.'}@@ -782,6 +786,7 @@ export const SECTIONS: DesktopConfigSection[] = ['stt.enabled','stt.echo_transcripts','stt.provider',+ 'stt.streaming','voice.auto_tts','tts.edge.voice','tts.openai.model',@@ -811,6 +816,7 @@ export const SECTIONS: DesktopConfigSection[] = ['stt.local.model','stt.local.language','stt.openai.model',+ 'stt.openai.streaming_model','stt.groq.model','stt.mistral.model','stt.xai.model',diff --git a/apps/desktop/src/app/settings/voice-provider-fields.test.ts b/apps/desktop/src/app/settings/voice-provider-fields.test.tsindex 9de8b5febb9..2d4a250bfd3 100644--- a/apps/desktop/src/app/settings/voice-provider-fields.test.ts+++ b/apps/desktop/src/app/settings/voice-provider-fields.test.ts@@ -28,7 +28,7 @@ describe('voiceProviderKeys', () => {it('scopes to the exact provider segment (no prefix bleed)', () => {expect(voiceProviderKeys('tts', 'mini')).toEqual([])- expect(voiceProviderKeys('stt', 'openai')).toEqual(['stt.openai.model'])+ expect(voiceProviderKeys('stt', 'openai')).toEqual(['stt.openai.model', 'stt.openai.streaming_model'])})})diff --git a/apps/desktop/src/lib/voice-client-direct.ts b/apps/desktop/src/lib/voice-client-direct.tsindex e3119618413..6322e6c09e1 100644--- a/apps/desktop/src/lib/voice-client-direct.ts+++ b/apps/desktop/src/lib/voice-client-direct.ts@@ -55,7 +55,8 @@ interface RelayConfig {}export interface VoiceClientConfig {- stt: DirectSttConfig | RelayConfig+ /** `streaming`: the host serves live dictation over /api/audio/transcribe-stream (stt.streaming). */+ stt: (DirectSttConfig | RelayConfig) & { streaming?: boolean }tts: DirectTtsConfig | RelayConfig}diff --git a/apps/desktop/src/lib/voice-stream.ts b/apps/desktop/src/lib/voice-stream.tsnew file mode 100644index 00000000000..4462e03f772--- /dev/null+++ b/apps/desktop/src/lib/voice-stream.ts@@ -0,0 +1,137 @@+import type { ResolvedOwner } from '@/hermes'+import { resolveSiblingWsUrl } from '@/lib/sibling-ws-url'++/**+ * Live dictation STT: mic PCM streams to the host's `/api/audio/transcribe-stream` WebSocket+ * WHILE the user speaks; partial text arrives as it is recognized and the transcript lands right+ * at end of recording (server contract: `hermes_cli/web_routers/audio.py`). Provider keys never+ * leave the host, and the host resamples, so the client sends the AudioContext's own rate.+ *+ * client β {"sample_rate": N}, then binary s16le mono PCM frames, {"eos": true}+ * server β {"type":"partial","text"}, {"type":"final","transcript"}, {"type":"error","message"}+ *+ * Any failure (older backend, provider without a live wire, socket drop) resolves to `null` or+ * rejects stop(); the caller then transcribes its recorded blob exactly as before.+ */++export interface DictationStreamSession {+ /** Feed one PCM chunk (s16le mono at the announced rate). No-op once settled. */+ pushAudio: (chunk: ArrayBuffer) => void+ /** End the recording; resolves with the final transcript ('' = heard nothing). */+ stop: () => Promise<string>+ /** Abort without a transcript (cancel / unmount). */+ cancel: () => void+}++const OPEN_TIMEOUT_MS = 5_000++export async function openDictationStream(+ owner: ResolvedOwner,+ sampleRate: number,+ onPartial?: (text: string) => void+): Promise<DictationStreamSession | null> {+ let url: URL++ try {+ url = new URL(await resolveSiblingWsUrl(owner, '/api/audio/transcribe-stream'))+ } catch {+ return null+ }++ // A registry-minted URL may already carry the backend-namespace profile; keep it.+ if (owner.profile && !url.searchParams.has('profile')) {+ url.searchParams.set('profile', owner.profile)+ }++ const ws = new WebSocket(url.toString())+ ws.binaryType = 'arraybuffer'++ let settled = false+ let failure: Error | null = null+ let pending: { reject: (error: Error) => void; resolve: (text: string) => void } | null = null++ const settle = (outcome: Error | string) => {+ if (settled) {+ return+ }++ settled = true++ if (typeof outcome !== 'string') {+ failure = outcome+ pending?.reject(outcome)+ } else {+ pending?.resolve(outcome)+ }++ pending = null+ }++ ws.onmessage = event => {+ let message: { message?: string; text?: string; transcript?: string; type?: string }++ try {+ message = JSON.parse(String(event.data)) as typeof message+ } catch {+ return+ }++ if (message.type === 'partial' && typeof message.text === 'string') {+ onPartial?.(message.text)+ } else if (message.type === 'final') {+ settle((message.transcript ?? '').trim())+ ws.close()+ } else if (message.type === 'error') {+ settle(new Error(message.message || 'live transcription failed'))+ ws.close()+ }+ }++ const opened = await new Promise<boolean>(resolve => {+ const timer = window.setTimeout(() => resolve(false), OPEN_TIMEOUT_MS)++ ws.onopen = () => {+ window.clearTimeout(timer)+ resolve(true)+ }++ ws.onerror = () => {+ window.clearTimeout(timer)+ resolve(false)+ }+ })++ ws.onclose = () => settle(new Error('live transcription connection closed'))++ if (!opened || settled) {+ ws.close()++ return null+ }++ ws.send(JSON.stringify({ sample_rate: sampleRate }))++ return {+ pushAudio: chunk => {+ if (!settled && ws.readyState === WebSocket.OPEN) {+ ws.send(chunk)+ }+ },+ stop: () =>+ new Promise<string>((resolve, reject) => {+ if (settled) {+ reject(failure ?? new Error('live transcription already ended'))++ return+ }++ pending = { reject, resolve }+ ws.send(JSON.stringify({ eos: true }))+ }),+ cancel: () => {+ settled = true+ pending = null+ ws.close()+ }+ }+}diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex f9a22a43fb0..bcb8ec408b7 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4908,6 +4908,10 @@ export interface BrowserControllerCancelPayload {export interface VoiceStatusPayload {state: string}+/** ``methods_voice`` voice.record ``on_partial`` β live STT text so far (``stt.streaming``). */+export interface VoicePartialPayload {+ text: string+}/** ``methods_voice._vr_transcript`` / ``_deliver_fd_transcript`` / typed stop phrase in methods_prompt. */export interface VoiceTranscriptPayload {text?: string | null@@ -5908,6 +5912,8 @@ export interface BackendGatewayEventMap {'tool.start': ToolStartPayload/** Barge-in: the spoken interjection interrupted the turn; no payload. */'voice.interrupted': Record<string, never>+ /** Live STT text so far while the user is still speaking. */+ 'voice.partial': VoicePartialPayload/** Voice recorder state changed. */'voice.status': VoiceStatusPayload/** A voice capture produced text (or a stop phrase / silence limit). */@@ -5990,6 +5996,7 @@ export const GATEWAY_EVENT_TYPES = ['tool.output_risk','tool.start','voice.interrupted',+ 'voice.partial','voice.status','voice.transcript','wake.detected'diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 9e248eeebf4..a414e51609a 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -38545,6 +38545,21 @@"title": "VerificationStatusResult","type": "object"},+ "VoicePartialPayload": {+ "additionalProperties": false,+ "description": "``methods_voice`` voice.record ``on_partial`` \u2014 live STT text so far (``stt.streaming``).",+ "properties": {+ "text": {+ "title": "Text",+ "type": "string"+ }+ },+ "required": [+ "text"+ ],+ "title": "VoicePartialPayload",+ "type": "object"+ },"VoiceRecordAction": {"enum": ["start",@@ -40743,6 +40758,18 @@}]},+ {+ "name": "voice.partial",+ "summary": "Live STT text so far while the user is still speaking.",+ "params": [+ {+ "name": "payload",+ "schema": {+ "$ref": "#/components/schemas/VoicePartialPayload"+ }+ }+ ]+ },{"name": "voice.status","summary": "Voice recorder state changed.",diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..bfd00c923a1--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1,2 @@+TimeLord2010+# live STT plugin contract, #103173diff --git a/hermes_cli/cli_init_mixin.py b/hermes_cli/cli_init_mixin.pyindex 8c611e5c541..36e04fa1646 100644--- a/hermes_cli/cli_init_mixin.py+++ b/hermes_cli/cli_init_mixin.py@@ -429,6 +429,7 @@ class CLIInitMixin:self._voice_mode = self._voice_tts = self._voice_recording = Falseself._voice_processing = self._voice_continuous = Falseself._voice_recorder = self._voice_tts_stop = None+ self._voice_live_text = "" # live STT partial (stt.streaming) shown in the placeholderself._voice_tts_done = threading.Event()self._voice_tts_done.set()self._voice_barge_capture = threading.Event() # barge monitor is capturing the interruptiondiff --git a/hermes_cli/cli_tui_mixin.py b/hermes_cli/cli_tui_mixin.pyindex 660981ee27d..d3585588d00 100644--- a/hermes_cli/cli_tui_mixin.py+++ b/hermes_cli/cli_tui_mixin.py@@ -796,10 +796,10 @@ class CLITuiMixin:return []def _tui_placeholder_text(self):- if self._voice_recording:- return t("cli.tui.placeholder_recording", shortcut=self._voice_record_key_label())+ if self._voice_recording: # live STT partial text (stt.streaming) replaces the hint+ return self._voice_live_text or t("cli.tui.placeholder_recording", shortcut=self._voice_record_key_label())if self._voice_processing:- return t("cli.tui.placeholder_transcribing")+ return self._voice_live_text or t("cli.tui.placeholder_transcribing")if self._sudo_state:if (self._sudo_state.get("vault_save") or {}).get("step") == "identifier":return t("cli.tui.placeholder_vault_username")@@ -1898,7 +1898,7 @@ class CLITuiMixin:self._voice_tts = Falseself._voice_recorder = None # AudioRecorder (lazy init)self._voice_recording = False- self._voice_processing = False # STT in progress+ self._voice_processing, self._voice_live_text = False, "" # STT in progress; live partial textself._voice_continuous = False # auto-restart after the agent respondsself._voice_tts_done = threading.Event() # TTS playback finishedself._voice_tts_done.set() # initially "done" (no TTS pending)diff --git a/hermes_cli/cli_voice_mixin.py b/hermes_cli/cli_voice_mixin.pyindex e293bf96f69..92c2e4af585 100644--- a/hermes_cli/cli_voice_mixin.py+++ b/hermes_cli/cli_voice_mixin.py@@ -99,6 +99,8 @@ class CLIVoiceMixin:# Config-driven silence params, numeric-guarded against YAML scalar corruption.rec = self._voice_recorder+ self._voice_live_text = ""+ rec.on_live_partial = self._voice_on_live_partialrec._silence_threshold = _numeric_or(voice_cfg.get("silence_threshold"), 200)rec._silence_duration = _numeric_or(voice_cfg.get("silence_duration"), 3.0)# voice.max_recording_seconds β hard cap on one recording; explicit <= 0 disables it.@@ -181,6 +183,11 @@ class CLIVoiceMixin:_cprint(f"{_DIM}{t('cli.voice.autorestart_failed', error=e)}{_RST}")threading.Thread(target=_restart_recording, daemon=True).start()+ def _voice_on_live_partial(self, text: str) -> None:+ """Live STT partial (``stt.streaming``): shown in the input placeholder while recording."""+ self._voice_live_text = text+ self._voice_invalidate()+def _voice_stop_and_transcribe(self):"""Stop recording, transcribe via STT, and queue the transcript as input."""from cli import _DIM, _RST, _VoiceInputMessage, _cprint@@ -235,6 +242,7 @@ class CLIVoiceMixin:finally:with self._voice_lock:self._voice_processing = False+ self._voice_live_text = ""self._voice_invalidate()# On failure keep the source recording so long dictation is not lost.try:diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex e29687dbbd6..86f7ff61d59 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1158,13 +1158,12 @@ DEFAULT_CONFIG = {"enabled": True,# Echo the raw transcript of gateway voice messages back as a ποΈ message."echo_transcripts": True,- # No seeded "provider": a stored value counts as an explicit user pick; unset = autodetect- # ladder. Valid: "local" (faster-whisper) | "groq" | "openai" | "mistral" | "elevenlabs" |- # "deepinfra" | "xai". Global language hint unless a per-provider language overrides it. "en"- # because Whisper auto-detect misreads short/accented clips; "" = auto; or "es", "zh", ...+ # No seeded "provider" (a stored value is an explicit pick; unset = autodetect): local | groq |+ # openai | mistral | elevenlabs | deepinfra | xai. Global language hint unless a per-provider one+ # overrides it; "en" because Whisper auto-detect misreads short clips; "" = auto; "es", ..."language": "en",- # Client-side ffmpeg silence trim before cloud upload (local whisper uses VAD): silence- # inflates upload time, billing and hallucinations. Failure = raw upload.+ "streaming": False, # live partial text while speaking (openai/xai/elevenlabs); failure = file path+ # Pre-upload ffmpeg silence trim (local whisper uses VAD); failure = raw upload."cloud_trim_silence": True,"cloud_trim_threshold_db": -40, # quieter than this counts as silence"cloud_trim_keep_ms": 300, # how much of each pause survives (natural pacing)@@ -1188,6 +1187,7 @@ DEFAULT_CONFIG = {"openai": {# whisper-1, gpt-4o-mini-transcribe, gpt-4o-transcribe, gpt-transcribe"model": "whisper-1",+ "streaming_model": "gpt-live-transcribe", # stt.streaming; the one model with mid-utterance deltas"language": "", # auto-detect; set "en", "es", ... to force"timeout": 60, # seconds; allow self-hosted backends time to cold-start"max_retries": 1, # OpenAI SDK transport retriesdiff --git a/hermes_cli/voice.py b/hermes_cli/voice.pyindex 7f7a7d6fe10..d716e41c429 100644--- a/hermes_cli/voice.py+++ b/hermes_cli/voice.py@@ -332,6 +332,7 @@ def start_continuous(auto_restart: bool = True,max_recording_seconds: float = 0.0,on_stop_phrase: Optional[Callable[[str], None]] = None,+ on_partial: Optional[Callable[[str], None]] = None,) -> bool:"""Start a VAD-driven continuous recording loop.@@ -339,6 +340,7 @@ def start_continuous(non-positive / non-numeric disables the cap. ``on_stop_phrase`` receives the strippedtranscript when the user utters a bare stop phrase (``voice.stop_phrases``); the loop haltsfirst, so the consumer only reflects "voice off" β like the manual stop control.+ ``on_partial`` receives live STT text while the user speaks (``stt.streaming``)."""global _continuous_active, _continuous_recorder, _continuous_auto_restart, _continuous_no_speech_countglobal _continuous_callbacks@@ -359,6 +361,7 @@ def start_continuous(if _continuous_recorder is None:_continuous_recorder = create_audio_recorder()rec = _continuous_recorder+ rec.on_live_partial = on_partialrec._silence_threshold = silence_thresholdrec._silence_duration = silence_duration# Same numeric-with-bool-excluded guard as cli.py:_voice_start_recording.diff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.pyindex f651b8a3bf8..a4fe49a91d6 100644--- a/hermes_cli/web_routers/audio.py+++ b/hermes_cli/web_routers/audio.py@@ -1,4 +1,4 @@-"""Audio dashboard routes: transcription upload, voice config, ElevenLabs voices, TTS speak/lease and the speak-stream WebSocket.+"""Audio dashboard routes: transcription upload + live transcribe-stream, voice config, ElevenLabs voices, TTS speak/lease and the speak-stream WebSocket.Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch on``web_server`` stay there and are late-bound (cycle-safe).@@ -512,6 +512,83 @@ async def stt_lease(payload: STTLeaseRequest, profile: Optional[str] = None):return {"ok": True, "lease": lease, "active": payload.active, **result}[email protected]("/api/audio/transcribe-stream")+async def transcribe_stream_ws(ws: "WebSocket") -> None:+ """Live STT for Desktop dictation: mic PCM in while the user speaks, partial + final text out.++ Protocol:+ client β ``{"sample_rate": N}`` first (8000-48000), then binary s16le mono PCM frames,+ ``{"eos": true}`` when the recording ends (disconnect = cancel)+ server β ``{"type": "partial", "text": ...}`` as speech is recognized,+ ``{"type": "final", "transcript": ..., "provider": ...}``,+ ``{"type": "error", "message": ...}`` β also when no live STT is available, so the+ client falls back to ``POST /api/audio/transcribe`` with its recorded blob.+ """+ if not _ws_auth_ok(ws):+ await ws.close(code=4401)+ return+ if not _ws_request_is_allowed(ws):+ await ws.close(code=4403)+ return+ await ws.accept()++ profile = (ws.query_params.get("profile") or "").strip() or None+ loop = asyncio.get_running_loop()+ partials: asyncio.Queue = asyncio.Queue()++ def _open():+ from tools.transcription_streaming import open_streaming_session+ with _config_profile_scope(profile):+ return open_streaming_session(on_partial=lambda text: loop.call_soon_threadsafe(partials.put_nowait, text))++ session = None+ with contextlib.suppress(Exception):+ session = await loop.run_in_executor(None, _open)+ if session is None:+ with contextlib.suppress(Exception):+ await ws.send_json({"type": "error", "message": "no live STT for the configured provider"})+ await ws.close()+ return++ async def _forward_partials():+ while True:+ await ws.send_json({"type": "partial", "text": await partials.get()})++ forwarder = asyncio.ensure_future(_forward_partials())+ ended = False+ try:+ first = json.loads(await ws.receive_text())+ rate = int(first.get("sample_rate") or 0)+ if not 8000 <= rate <= 48000:+ raise ValueError(f"unsupported sample_rate {rate}")+ session.set_input_rate(rate)+ while True:+ message = await ws.receive()+ if message.get("type") == "websocket.disconnect":+ break+ if message.get("bytes"):+ session.push_audio(message["bytes"])+ elif message.get("text") and json.loads(message["text"]).get("eos"):+ ended = True+ break+ except (WebSocketDisconnect, ValueError, RuntimeError) as exc:+ _log.debug("transcribe-stream client ended early: %s", exc)+ if not ended:+ session.cancel()+ forwarder.cancel()+ return+ result = await loop.run_in_executor(None, session.finalize)+ await asyncio.sleep(0) # let the last partial flush before the final frame+ forwarder.cancel()+ with contextlib.suppress(Exception):+ if result.get("success"):+ await ws.send_json({"type": "final", "transcript": result.get("transcript", ""),+ "provider": result.get("provider", "")})+ else:+ await ws.send_json({"type": "error", "message": result.get("error") or "transcription failed"})+ await ws.close()++@router.websocket("/api/audio/speak-stream")async def speak_stream_ws(ws: "WebSocket") -> None:"""Streaming TTS for the desktop: text in, raw int16 PCM frames out.diff --git a/hermes_cli/web_server_config.py b/hermes_cli/web_server_config.pyindex 11dd4b0d0c4..3a28f5cca60 100644--- a/hermes_cli/web_server_config.py+++ b/hermes_cli/web_server_config.py@@ -129,6 +129,8 @@ _SCHEMA_OVERRIDES: Dict[str, Dict[str, Any]] = {"stt.local.model": _select("Local faster-whisper model size", "tiny", "base", "small", "medium", "large-v3"),"stt.groq.model": _select("Groq Whisper model", *STT_MODEL_CATALOG["groq"]),"stt.openai.model": _select("OpenAI transcription model", *STT_MODEL_CATALOG["openai"]),+ "stt.openai.streaming_model": _select("OpenAI live transcription model (stt.streaming)", "gpt-live-transcribe",+ "gpt-transcribe", "gpt-4o-transcribe", "gpt-4o-mini-transcribe"),"stt.mistral.model": _select("Mistral Voxtral transcription model", *STT_MODEL_CATALOG["mistral"]),"stt.xai.model": _select("xAI transcription model", *STT_MODEL_CATALOG["xai"]),"stt.elevenlabs.model_id": _select("ElevenLabs Scribe model", *STT_MODEL_CATALOG["elevenlabs"]),diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.jsonindex 8525ac102ce..d3347411786 100644--- a/locales/_keys.desktop.json+++ b/locales/_keys.desktop.json@@ -2961,6 +2961,7 @@"settings.fieldDescriptions.stt.echoTranscripts","settings.fieldDescriptions.stt.elevenlabs.languageCode","settings.fieldDescriptions.stt.enabled",+ "settings.fieldDescriptions.stt.streaming","settings.fieldDescriptions.terminal.cwd","settings.fieldDescriptions.terminal.daytonaImage","settings.fieldDescriptions.terminal.dockerImage",@@ -3038,7 +3039,9 @@"settings.fieldLabels.stt.local.model","settings.fieldLabels.stt.mistral.model","settings.fieldLabels.stt.openai.model",+ "settings.fieldLabels.stt.openai.streamingModel","settings.fieldLabels.stt.provider",+ "settings.fieldLabels.stt.streaming","settings.fieldLabels.stt.xai.model","settings.fieldLabels.terminal.backend","settings.fieldLabels.terminal.cwd",diff --git a/tests/tools/test_transcription_streaming.py b/tests/tools/test_transcription_streaming.pynew file mode 100644index 00000000000..09503201444--- /dev/null+++ b/tests/tools/test_transcription_streaming.py@@ -0,0 +1,89 @@+"""Live STT sessions: wire behaviour over a real socket, and the recorder hand-off."""++from __future__ import annotations++import json+import threading++from websockets.sync.server import serve++from tools import transcription_streaming as ts+from tools import voice_mode+++def _xai_like_server(received: list):+ """xAI ``/v1/stt`` shape: created first, a partial per audio frame, stitched final on audio.done."""++ def handler(ws):+ ws.send(json.dumps({"type": "transcript.created"}))+ words = []+ for raw in ws:+ if isinstance(raw, bytes):+ received.append(raw)+ words.append(f"w{len(words)}")+ ws.send(json.dumps({"type": "transcript.partial", "text": " ".join(words),+ "is_final": False, "speech_final": False}))+ elif json.loads(raw).get("type") == "audio.done":+ ws.send(json.dumps({"type": "transcript.partial", "text": " ".join(words),+ "is_final": True, "speech_final": True}))+ ws.send(json.dumps({"type": "transcript.done", "text": ""}))+ return++ server = serve(handler, "127.0.0.1", 0)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ return server+++def test_live_session_streams_partials_before_end_and_keeps_early_audio():+ received: list = []+ server = _xai_like_server(received)+ port = server.socket.getsockname()[1]+ partials: list = []+ seen_partial = threading.Event()++ def on_partial(text):+ partials.append(text)+ seen_partial.set()++ session = ts.XAIStreamingSession("k", f"http://127.0.0.1:{port}/v1", "grok-voice-transcribe-2.0", "en",+ on_partial).start()+ session.push_audio(b"\x01\x00" * 160) # before transcript.created: must be held, not dropped+ session.push_audio(b"\x02\x00" * 160)+ assert seen_partial.wait(5), "a partial must arrive while audio is still streaming"+ result = session.finalize(timeout=5)+ server.shutdown()++ assert result == {"success": True, "transcript": "w0 w1", "provider": "xai"}+ assert len(received) == 2+ assert partials[-1] == "w0 w1"+++class _Session:+ def __init__(self, result):+ self.result, self.ended = result, False++ def end_audio(self):+ self.ended = True++ def finalize(self):+ return self.result++ def cancel(self):+ pass+++def test_recording_uses_the_live_transcript_and_falls_back_to_the_file(tmp_path, monkeypatch):+ uploads: list = []+ monkeypatch.setattr("tools.transcription_tools.transcribe_audio",+ lambda path, **kw: uploads.append(path) or {"success": True, "transcript": "from file"})+ live_wav, failed_wav = str(tmp_path / "a.wav"), str(tmp_path / "b.wav")++ live = _Session({"success": True, "transcript": "from live", "provider": "xai"})+ voice_mode._park_live_session(live_wav, live)+ assert live.ended, "parking ends the audio so the provider flushes while the caller works"+ assert voice_mode.transcribe_recording(live_wav)["transcript"] == "from live"+ assert uploads == []++ voice_mode._park_live_session(failed_wav, _Session({"success": False, "transcript": "", "error": "socket"}))+ assert voice_mode.transcribe_recording(failed_wav)["transcript"] == "from file"+ assert uploads == [failed_wav]diff --git a/tools/transcription_streaming.py b/tools/transcription_streaming.pynew file mode 100644index 00000000000..bd83a61376b--- /dev/null+++ b/tools/transcription_streaming.py@@ -0,0 +1,543 @@+"""Live speech-to-text: feed microphone PCM while the user speaks, get partial and final text.++Every caller hands 16 kHz mono s16le PCM to :meth:`StreamingSession.push_audio` in any chunk+size, receives non-final text through ``on_partial`` as the provider recognizes it, and calls+:meth:`StreamingSession.finalize` at end of speech for the standard transcription envelope+(``success`` / ``transcript`` / ``provider`` / ``error``). One worker thread owns the provider+socket, so callers never block on network I/O while audio is captured.++Built-in wires (live-verified against each vendor except where noted):++- ``openai``: Realtime ``type: transcription`` session (``stt.openai.streaming_model``, default+ ``gpt-live-transcribe``, the one model that emits deltas before the turn is committed). The+ endpoint requires >= 24 kHz input, so PCM is resampled 16 k -> 24 k here.+- ``xai``: ``wss://api.x.ai/v1/stt`` with ``interim_results=true``.+- ``elevenlabs``: ``wss://api.elevenlabs.io/v1/speech-to-text/realtime`` (``scribe_v2_realtime``),+ built from the vendor AsyncAPI schema.++Plugin providers opt in through ``TranscriptionProvider.streaming_capable`` /+``open_stream_session``. Streaming is opt-in (``stt.streaming: true``); every surface falls back+to the file path when no session opens or a session fails.+"""++from __future__ import annotations++import base64+import contextvars+import json+import logging+import queue+import threading+import time+from array import array+from typing import Any, Callable, Dict, Optional+from urllib.parse import urlencode, urlsplit, urlunsplit++from agent.memory_provider import spawn_context_thread+from utils import is_truthy_value++logger = logging.getLogger(__name__)++INPUT_RATE = 16000 # the contract every caller feeds+DEFAULT_OPENAI_STREAMING_MODEL = "gpt-live-transcribe"+ELEVENLABS_REALTIME_MODEL = "scribe_v2_realtime"+STREAMING_PROVIDERS = ("openai", "xai", "elevenlabs")+_FINALIZE_TIMEOUT_S = 20.0+_CONNECT_TIMEOUT_S = 10.0++PartialCallback = Callable[[str], None]+++class Resampler:+ """Stateful s16le mono rate converter (linear; box-average for integer downsampling)."""++ def __init__(self, src_rate: int, dst_rate: int) -> None:+ self.src, self.dst = int(src_rate), int(dst_rate)+ self._pos = 0.0 # fractional read position into the carried + new samples+ self._carry = array("h")++ def __call__(self, pcm: bytes) -> bytes:+ if self.src == self.dst or not pcm:+ return pcm+ samples = array("h")+ samples.frombytes(pcm[: len(pcm) - len(pcm) % 2])+ if self.src % self.dst == 0:+ data = self._carry + samples+ step = self.src // self.dst+ usable = len(data) - len(data) % step+ out = array("h", (sum(data[i:i + step]) // step for i in range(0, usable, step)))+ self._carry = data[usable:]+ return out.tobytes()+ data = self._carry + samples+ ratio = self.src / self.dst+ out = array("h")+ pos = self._pos+ last = len(data) - 1+ while pos < last:+ i = int(pos)+ frac = pos - i+ out.append(int(data[i] + (data[i + 1] - data[i]) * frac))+ pos += ratio+ keep = int(pos)+ self._carry = data[keep:]+ self._pos = pos - keep+ return out.tobytes()+++class StreamingSession:+ """One utterance of live STT. Thread-safe ``push_audio``; single-use."""++ provider = "unknown"++ def __init__(self, on_partial: Optional[PartialCallback] = None) -> None:+ self._on_partial = on_partial+ self._audio: "queue.Queue[Optional[bytes]]" = queue.Queue()+ self._done = threading.Event()+ self._cancelled = threading.Event()+ self._result: Dict[str, Any] = {}+ self._partial = ""+ self._worker: Optional[threading.Thread] = None+ self._to_16k: Optional[Resampler] = None++ def set_input_rate(self, rate: int) -> None:+ """Accept PCM at ``rate`` (e.g. the mic's device rate); the worker converts it to 16 kHz,+ so a realtime capture callback never pays for resampling."""+ if int(rate) != INPUT_RATE:+ self._to_16k = Resampler(int(rate), INPUT_RATE)++ def _take_audio(self, block: bool, timeout: float = 0.0) -> Optional[bytes]:+ """Next 16 kHz chunk (``b""`` when none is queued, None at end of audio)."""+ try:+ chunk = self._audio.get(timeout=timeout) if block else self._audio.get_nowait()+ except queue.Empty:+ return b""+ if chunk and self._to_16k is not None:+ chunk = self._to_16k(chunk)+ return chunk++ # ββ caller API ββ+ def start(self) -> "StreamingSession":+ # copy_context: a plugin session reads secrets from the opener's profile scope.+ ctx = contextvars.copy_context()+ self._worker = threading.Thread(target=ctx.run, args=(self._run,), name=f"stt-stream-{self.provider}",+ daemon=True)+ self._worker.start()+ return self++ def push_audio(self, pcm16k: bytes) -> None:+ if pcm16k and not self._done.is_set():+ self._audio.put(bytes(pcm16k))++ def end_audio(self) -> None:+ """Signal end of speech without waiting (the worker flushes the provider)."""+ self._audio.put(None)++ def finalize(self, timeout: float = _FINALIZE_TIMEOUT_S) -> Dict[str, Any]:+ self.end_audio()+ if not self._done.wait(timeout):+ self.cancel()+ return self._error("live transcription timed out")+ return dict(self._result)++ def cancel(self) -> None:+ self._cancelled.set()+ self._audio.put(None)+ self._finish(self._error("cancelled"))++ def partial_transcript(self) -> str:+ return self._partial++ # ββ worker side ββ+ def _set_partial(self, text: str) -> None:+ text = text.strip()+ if text and text != self._partial:+ self._partial = text+ if self._on_partial is not None:+ try:+ self._on_partial(text)+ except Exception: # noqa: BLE001 β a UI callback must not kill the socket+ logger.debug("on_partial callback raised", exc_info=True)++ def _error(self, message: str) -> Dict[str, Any]:+ return {"success": False, "transcript": "", "provider": self.provider, "error": message}++ def _finish(self, result: Dict[str, Any]) -> None:+ if not self._done.is_set():+ self._result = result+ self._done.set()++ def _run(self) -> None:+ try:+ self._finish(self._session())+ except Exception as exc: # health: allow BLE001 -- worker boundary: every failure becomes the envelope+ logger.warning("Live STT (%s) failed: %s", self.provider, exc, exc_info=True)+ self._finish(self._error(f"live transcription failed: {exc}"))++ def _session(self) -> Dict[str, Any]: # pragma: no cover - overridden+ raise NotImplementedError+++class _WebSocketSession(StreamingSession):+ """A provider wire over one websocket: subclasses map audio out and events in."""++ url = ""+ headers: Dict[str, str] = {}++ def _session(self) -> Dict[str, Any]:+ from websockets.sync.client import connect++ ws = connect(self.url, additional_headers=self.headers, open_timeout=_CONNECT_TIMEOUT_S,+ close_timeout=1, max_size=None)+ try:+ return self._loop(ws)+ finally:+ # Publish first, close after: the sync close handshake waits up to close_timeout on a+ # server that already hung up, and the caller is blocked on finalize() meanwhile.+ spawn_context_thread(ws.close, name="stt-stream-close").start()++ def _loop(self, ws: Any) -> Dict[str, Any]:+ self._open(ws)+ ending_since: Optional[float] = None+ while True:+ if self._cancelled.is_set():+ return self._error("cancelled")+ if ending_since is None:+ ending_since = self._drain_audio(ws)+ elif time.monotonic() - ending_since > _FINALIZE_TIMEOUT_S:+ return self._error("provider never finalized the transcript")+ try:+ raw = ws.recv(timeout=0.02)+ except TimeoutError:+ continue+ if isinstance(raw, (bytes, bytearray)):+ continue+ result = self._event(json.loads(raw))+ if result is not None:+ self._finish(result)+ return result+ if self._backlog and self._ready():+ self._flush_backlog(ws)++ def _drain_audio(self, ws: Any) -> Optional[float]:+ """Send queued audio; on end-of-audio send the provider's flush and return its time."""+ while True:+ chunk = self._take_audio(block=False)+ if chunk is None:+ self._end(ws)+ return time.monotonic()+ if not chunk:+ if self._audio.empty():+ return None+ continue+ if self._ready():+ self._send_audio(ws, chunk)+ else:+ self._backlog.append(chunk)++ _backlog: list[bytes]++ def _ready(self) -> bool:+ return True++ def _flush_backlog(self, ws: Any) -> None:+ backlog, self._backlog = self._backlog, []+ for chunk in backlog:+ self._send_audio(ws, chunk)++ def _open(self, ws: Any) -> None:+ self._backlog = []++ def _send_audio(self, ws: Any, chunk: bytes) -> None: # pragma: no cover - overridden+ raise NotImplementedError++ def _end(self, ws: Any) -> None: # pragma: no cover - overridden+ raise NotImplementedError++ def _event(self, event: Dict[str, Any]) -> Optional[Dict[str, Any]]: # pragma: no cover+ raise NotImplementedError+++class OpenAIRealtimeSession(_WebSocketSession):+ provider = "openai"++ def __init__(self, api_key: str, base_url: str, model: str, language: Optional[str],+ prompt: Optional[str], on_partial: Optional[PartialCallback] = None) -> None:+ super().__init__(on_partial)+ parts = urlsplit(base_url.rstrip("/"))+ scheme = "wss" if parts.scheme == "https" else "ws"+ self.url = urlunsplit((scheme, parts.netloc, f"{parts.path}/realtime", "intent=transcription", ""))+ self.headers = {"Authorization": f"Bearer {api_key}"}+ self.model, self.language, self.prompt = model, language, prompt+ self._resample = Resampler(INPUT_RATE, 24000)+ self._text = ""+ self._sent_audio = False++ def _open(self, ws: Any) -> None:+ super()._open(ws)+ transcription: Dict[str, Any] = {"model": self.model}+ if self.language:+ # gpt-live-transcribe takes a ``languages`` list and rejects the singular field.+ if self.model == DEFAULT_OPENAI_STREAMING_MODEL:+ transcription["languages"] = [self.language]+ else:+ transcription["language"] = self.language+ if self.prompt:+ transcription["prompt"] = self.prompt+ ws.send(json.dumps({"type": "session.update", "session": {"type": "transcription", "audio": {"input": {+ "format": {"type": "audio/pcm", "rate": 24000}, "transcription": transcription,+ "turn_detection": None}}}}))++ def _send_audio(self, ws: Any, chunk: bytes) -> None:+ pcm = self._resample(chunk)+ if pcm:+ self._sent_audio = True+ ws.send(json.dumps({"type": "input_audio_buffer.append", "audio": base64.b64encode(pcm).decode()}))++ def _end(self, ws: Any) -> None:+ if not self._sent_audio:+ self._finish({"success": True, "transcript": "", "provider": self.provider})+ self._cancelled.set()+ return+ ws.send(json.dumps({"type": "input_audio_buffer.commit"}))++ def _event(self, event: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ kind = str(event.get("type") or "")+ if kind.endswith("input_audio_transcription.delta"):+ self._text += str(event.get("delta") or "")+ self._set_partial(self._text)+ elif kind.endswith("input_audio_transcription.completed"):+ return {"success": True, "transcript": str(event.get("transcript") or self._text).strip(),+ "provider": self.provider}+ elif kind == "error":+ message = str((event.get("error") or {}).get("message") or "provider error")+ # Committing < 100 ms of audio is "buffer too small": the user said nothing.+ if "buffer too small" in message.lower():+ return {"success": True, "transcript": "", "provider": self.provider}+ return self._error(message)+ return None+++class XAIStreamingSession(_WebSocketSession):+ provider = "xai"++ def __init__(self, api_key: str, base_url: str, model: str, language: Optional[str],+ on_partial: Optional[PartialCallback] = None) -> None:+ super().__init__(on_partial)+ parts = urlsplit(base_url.rstrip("/"))+ scheme = "wss" if parts.scheme == "https" else "ws"+ query = {"sample_rate": INPUT_RATE, "encoding": "pcm", "interim_results": "true", "model": model}+ if language:+ query["language"] = language+ self.url = urlunsplit((scheme, parts.netloc, f"{parts.path}/stt", urlencode(query), ""))+ self.headers = {"Authorization": f"Bearer {api_key}"}+ self._created = False+ self._utterances: list[str] = [] # speech_final stitched utterances+ self._chunks: list[str] = [] # is_final chunks of the current utterance+ self._interim = ""++ def _ready(self) -> bool:+ return self._created # the server drops audio sent before transcript.created++ def _send_audio(self, ws: Any, chunk: bytes) -> None:+ ws.send(chunk)++ def _end(self, ws: Any) -> None:+ if not self._created:+ self._backlog.clear()+ ws.send(json.dumps({"type": "audio.done"}))++ def _text(self) -> str:+ return " ".join(p for p in (*self._utterances, *self._chunks, self._interim) if p).strip()++ def _event(self, event: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ kind = event.get("type")+ if kind == "transcript.created":+ self._created = True+ return None+ if kind == "transcript.partial":+ text = str(event.get("text") or "").strip()+ if event.get("speech_final"):+ self._utterances.append(text)+ self._chunks, self._interim = [], ""+ elif event.get("is_final"):+ self._chunks.append(text)+ self._interim = ""+ else:+ self._interim = text+ self._set_partial(self._text())+ return None+ if kind == "transcript.done":+ return {"success": True, "transcript": self._text(), "provider": self.provider}+ if kind == "error":+ return self._error(str(event.get("message") or "provider error"))+ return None+++class ElevenLabsRealtimeSession(_WebSocketSession):+ provider = "elevenlabs"++ def __init__(self, api_key: str, base_url: str, language: Optional[str],+ on_partial: Optional[PartialCallback] = None) -> None:+ super().__init__(on_partial)+ parts = urlsplit(base_url.rstrip("/"))+ scheme = "wss" if parts.scheme == "https" else "ws"+ query = {"model_id": ELEVENLABS_REALTIME_MODEL, "audio_format": f"pcm_{INPUT_RATE}",+ "commit_strategy": "vad"}+ if language:+ query["language_code"] = language+ self.url = urlunsplit((scheme, parts.netloc, f"{parts.path}/speech-to-text/realtime", urlencode(query), ""))+ self.headers = {"xi-api-key": api_key}+ self._committed: list[str] = []+ self._interim = ""+ self._ending = False++ def _chunk(self, pcm: bytes, commit: bool) -> str:+ return json.dumps({"message_type": "input_audio_chunk", "audio_base_64": base64.b64encode(pcm).decode(),+ "commit": commit, "sample_rate": INPUT_RATE})++ def _send_audio(self, ws: Any, chunk: bytes) -> None:+ ws.send(self._chunk(chunk, False))++ def _end(self, ws: Any) -> None:+ self._ending = True+ ws.send(self._chunk(b"", True))++ def _text(self) -> str:+ return " ".join(p for p in (*self._committed, self._interim) if p).strip()++ def _event(self, event: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ kind = event.get("message_type")+ if kind == "partial_transcript":+ self._interim = str(event.get("text") or "").strip()+ self._set_partial(self._text())+ elif kind == "committed_transcript":+ text = str(event.get("text") or "").strip()+ if text:+ self._committed.append(text)+ self._interim = ""+ self._set_partial(self._text())+ if self._ending:+ return {"success": True, "transcript": self._text(), "provider": self.provider}+ elif kind in ("insufficient_audio_activity", "commit_throttled") and self._ending:+ return {"success": True, "transcript": self._text(), "provider": self.provider}+ elif kind and kind not in ("session_started", "committed_transcript_with_timestamps", "warning"):+ if "error" in event:+ return self._error(f"{kind}: {event.get('error')}")+ return None+++class _PluginSession(StreamingSession):+ """Adapts a plugin ``TranscriptionStreamSession`` to the caller API (partials polled)."""++ def __init__(self, provider_name: str, inner: Any, on_partial: Optional[PartialCallback]) -> None:+ super().__init__(on_partial)+ self.provider, self._inner = provider_name, inner++ def _session(self) -> Dict[str, Any]:+ while True:+ chunk = self._take_audio(block=True, timeout=0.25)+ if self._cancelled.is_set():+ return self._error("cancelled")+ if chunk is None:+ return dict(self._inner.finalize())+ if chunk:+ self._inner.push_audio(chunk)+ self._set_partial(str(self._inner.partial_transcript() or ""))+++# ββ resolution ββ++def streaming_enabled(stt_config: Dict[str, Any]) -> bool:+ return is_truthy_value(stt_config.get("streaming", False), default=False)+++def _openai_credentials() -> Optional[tuple[str, str]]:+ """Direct OpenAI credentials only: the managed Nous gateway proxies the REST audio API, not+ the Realtime socket."""+ from tools.tool_backend_helpers import NOUS_MANAGED_PROVIDER, read_selection+ from tools.transcription_tools import _resolve_openai_audio_client_config+ if read_selection("stt") == NOUS_MANAGED_PROVIDER:+ return None+ try:+ api_key, base_url = _resolve_openai_audio_client_config()+ except ValueError:+ return None+ return api_key, base_url+++def _builtin_session(provider: str, stt_config: Dict[str, Any], language: Optional[str],+ prompt: Optional[str], on_partial: Optional[PartialCallback]) -> Optional[StreamingSession]:+ from tools import transcription_common as tc+ from tools import transcription_tools as tt+ raw_section = stt_config.get(provider)+ section: Dict[str, Any] = raw_section if isinstance(raw_section, dict) else {}+ if provider == "openai":+ creds = _openai_credentials()+ if creds is None:+ return None+ model = str(section.get("streaming_model") or DEFAULT_OPENAI_STREAMING_MODEL)+ return OpenAIRealtimeSession(creds[0], creds[1], model, language, prompt, on_partial)+ if provider == "xai":+ from hermes_cli.config import get_env_value+ api_key = str(get_env_value("XAI_API_KEY") or "").strip() # API key only, like the Desktop wire+ if not api_key:+ return None+ base = str(section.get("base_url") or get_env_value("XAI_STT_BASE_URL") or tc.XAI_STT_BASE_URL)+ return XAIStreamingSession(api_key, base, tc.normalize_xai_stt_model(section.get("model")),+ language, on_partial)+ if provider == "elevenlabs":+ api_key = tt._resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs")+ if not api_key:+ return None+ base = str(section.get("base_url") or tc.ELEVENLABS_STT_BASE_URL)+ return ElevenLabsRealtimeSession(api_key, base, language, on_partial)+ return None+++def _plugin_session(provider: str, language: Optional[str], prompt: Optional[str],+ on_partial: Optional[PartialCallback]) -> Optional[StreamingSession]:+ from agent.transcription_registry import get_provider+ registered = get_provider(provider)+ if registered is None or not registered.streaming_capable:+ return None+ return _PluginSession(provider, registered.open_stream_session(language=language, prompt=prompt), on_partial)+++def streaming_available(stt_config: Optional[Dict[str, Any]] = None) -> bool:+ """Cheap capability probe (no connection): would :func:`open_streaming_session` try a wire?"""+ from tools import transcription_tools as tt+ cfg = tt._load_stt_config() if stt_config is None else stt_config+ if not streaming_enabled(cfg):+ return False+ provider = tt._get_provider(cfg)+ if provider in STREAMING_PROVIDERS:+ return _builtin_session(provider, cfg, None, None, None) is not None+ from agent.transcription_registry import get_provider+ registered = get_provider(provider)+ return bool(registered is not None and registered.streaming_capable)+++def open_streaming_session(on_partial: Optional[PartialCallback] = None,+ stt_config: Optional[Dict[str, Any]] = None) -> Optional[StreamingSession]:+ """Start a live STT session for the active profile's provider, or None (use the file path).++ None when ``stt.streaming`` is off, the provider has no live wire, or it lacks credentials.+ """+ from tools import transcription_tools as tt+ cfg = tt._load_stt_config() if stt_config is None else stt_config+ if not streaming_enabled(cfg):+ return None+ provider = tt._get_provider(cfg)+ if provider in ("none", "local", "local_command"):+ return None+ language = tt._resolve_stt_language(provider, cfg, extra_keys=("language_code",) if provider == "elevenlabs" else ())+ prompt = str(cfg.get("prompt") or "").strip() or None+ try:+ if provider in STREAMING_PROVIDERS:+ session = _builtin_session(provider, cfg, language, prompt, on_partial)+ else:+ session = _plugin_session(provider, language, prompt, on_partial)+ except Exception: # noqa: BLE001 β a broken session open falls back to the file path+ logger.warning("Live STT session for %s could not open", provider, exc_info=True)+ return None+ return session.start() if session is not None else Nonediff --git a/tools/voice_client_config.py b/tools/voice_client_config.pyindex a909b36fcc6..d310f362164 100644--- a/tools/voice_client_config.py+++ b/tools/voice_client_config.py@@ -235,14 +235,21 @@ def resolve_client_voice_config() -> Dict[str, Any]:(the web server's ``_config_profile_scope``) before calling β identical tohow ``/api/audio/transcribe`` scopes ``transcribe_recording``."""- if not _client_direct_enabled():- disabled = _relay("voice.client_direct disabled")- return {"stt": disabled, "tts": disabled}out: Dict[str, Any] = {}- for key, resolver in (("stt", _resolve_stt_client_config), ("tts", _resolve_tts_client_config)):- try:- out[key] = resolver()- except Exception:- logger.exception("client voice-config %s resolution failed", key.upper())- out[key] = _relay("resolution error")+ if not _client_direct_enabled():+ out = {"stt": _relay("voice.client_direct disabled"), "tts": _relay("voice.client_direct disabled")}+ else:+ for key, resolver in (("stt", _resolve_stt_client_config), ("tts", _resolve_tts_client_config)):+ try:+ out[key] = resolver()+ except Exception:+ logger.exception("client voice-config %s resolution failed", key.upper())+ out[key] = _relay("resolution error")+ # Live dictation always goes through the host's /api/audio/transcribe-stream socket (keys stay+ # server-side), independent of client_direct; the verdict above remains the blob fallback.+ from tools.transcription_streaming import streaming_available+ try:+ out["stt"]["streaming"] = streaming_available()+ except Exception:+ logger.debug("live STT capability probe failed", exc_info=True)return outdiff --git a/tools/voice_mode.py b/tools/voice_mode.pyindex 5044885d10e..b8612914d72 100644--- a/tools/voice_mode.py+++ b/tools/voice_mode.py@@ -523,12 +523,55 @@ def _new_recording_path(ext: str) -> str:return os.path.join(_TEMP_DIR, f"recording_{time.strftime('%Y%m%d_%H%M%S')}.{ext}")+# WAV path -> live STT session that heard the same take (``stt.streaming``). transcribe_recording+# pops it, so every consumer of a recorder's WAV gets the live transcript with no call-site change.+_LIVE_SESSIONS: Dict[str, Any] = {}+_LIVE_SESSIONS_MAX = 8+_LIVE_LOCK = threading.Lock()+++def _park_live_session(wav_path: Optional[str], session: Any) -> None:+ if session is None:+ return+ if not wav_path:+ session.cancel()+ return+ session.end_audio() # the provider flushes while the caller is still handling the WAV+ with _LIVE_LOCK:+ _LIVE_SESSIONS[wav_path] = session+ while len(_LIVE_SESSIONS) > _LIVE_SESSIONS_MAX:+ _LIVE_SESSIONS.pop(next(iter(_LIVE_SESSIONS))).cancel()+++def _take_live_session(wav_path: str) -> Any:+ with _LIVE_LOCK:+ return _LIVE_SESSIONS.pop(wav_path, None)++class _RecorderBase:"""Lock, recording flag, start time and live RMS shared by both recorder backends."""def __init__(self) -> None:self._lock = threading.Lock()self._recording, self._start_time, self._current_rms = False, 0.0, 0+ # Live STT (``stt.streaming``): hosts set ``on_live_partial`` to render partial text.+ self.on_live_partial: Optional[Callable[[str], None]] = None+ self._live: Any = None++ def _open_live_session(self, sample_rate: int) -> None:+ from tools.transcription_streaming import open_streaming_session+ try:+ self._live = open_streaming_session(on_partial=self.on_live_partial)+ except Exception: # noqa: BLE001 β live STT is an accelerator; the WAV path still runs+ logger.debug("Live STT session did not open", exc_info=True)+ self._live = None+ if self._live is not None:+ self._live.set_input_rate(sample_rate)+ logger.info("Live STT streaming (%s)", self._live.provider)++ def _detach_live(self) -> Any:+ live, self._live = self._live, None+ return live@propertydef is_recording(self) -> bool:@@ -723,6 +766,9 @@ class AudioRecorder(_RecorderBase):def _on_audio_block(self, np, indata) -> None:self._frames.append(indata.copy())+ live = self._live+ if live is not None:+ live.push_audio(indata.tobytes())rms = int(_rms(np, indata))self._current_rms = rmsself._peak_rms = max(self._peak_rms, rms)@@ -802,6 +848,7 @@ class AudioRecorder(_RecorderBase):self._on_silence_stop = on_silence_stopself._sample_rate = _default_input_samplerate(sd)self._ensure_stream()+ self._open_live_session(self._sample_rate)with self._lock:self._recording = Truelogger.info("Voice recording started (rate=%d, channels=%d)", self._sample_rate, CHANNELS)@@ -829,6 +876,11 @@ class AudioRecorder(_RecorderBase):def stop(self) -> Optional[str]:"""Stop recording (stream stays alive) and return the WAV path, or None if unusable."""+ wav_path = self._stop_capture()+ _park_live_session(wav_path, self._detach_live())+ return wav_path++ def _stop_capture(self) -> Optional[str]:with self._lock:if not self._recording:return None@@ -856,6 +908,9 @@ class AudioRecorder(_RecorderBase):def _discard(self) -> None:with self._lock:self._recording, self._frames, self._on_silence_stop, self._current_rms = False, [], None, 0+ live = self._detach_live()+ if live is not None:+ live.cancel()def cancel(self) -> None:"""Stop recording and discard all captured audio (stream stays alive)."""@@ -883,13 +938,31 @@ def create_audio_recorder() -> AudioRecorder | TermuxAudioRecorder:# ββ STT dispatch ββ+def _live_result(wav_path: str) -> Optional[Dict[str, Any]]:+ """The live session's transcript for this take, or None to transcribe the WAV instead.++ A failed or empty live result falls back to the file: an empty live transcript over a take the+ recorder accepted as speech is more likely a dropped socket than silence."""+ session = _take_live_session(wav_path)+ if session is None:+ return None+ result = session.finalize()+ if result.get("success") and (result.get("transcript") or "").strip():+ return result+ logger.info("Live STT gave no transcript (%s); transcribing the recording",+ result.get("error") or "empty")+ return None++def transcribe_recording(wav_path: str, model: Optional[str] = None) -> Dict[str, Any]:"""Transcribe a WAV via ``transcribe_audio()``, filtering Whisper hallucinations;returns ``{success, transcript[, error]}``."""from tools.transcription_tools import transcribe_audio- # transcribe_audio fits oversized recordings under the provider's upload cap itself.- result = transcribe_audio(wav_path, model=model, source="voice_mode")+ result = _live_result(wav_path)+ if result is None:+ # transcribe_audio fits oversized recordings under the provider's upload cap itself.+ result = transcribe_audio(wav_path, model=model, source="voice_mode")# A configured stop phrase always survives: "bye"/"okay" overlap the# hallucination blocklist, and swallowing them would make "bye" fail to end the chat.if result.get("success"):diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex cd1f402fd56..6f27dd5e7a6 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -665,6 +665,12 @@ class VoiceStatusPayload(Payload):state: str+class VoicePartialPayload(Payload):+ """``methods_voice`` voice.record ``on_partial`` β live STT text so far (``stt.streaming``)."""++ text: str++class VoiceTranscriptPayload(Payload):"""``methods_voice._vr_transcript`` / ``_deliver_fd_transcript`` / typed stop phrase in methods_prompt."""@@ -683,6 +689,7 @@ class WakeDetectedPayload(Payload):event("voice.status", VoiceStatusPayload, doc="Voice recorder state changed.")+event("voice.partial", VoicePartialPayload, doc="Live STT text so far while the user is still speaking.")event("voice.transcript", VoiceTranscriptPayload, doc="A voice capture produced text (or a stop phrase / silence limit).")event("wake.detected", WakeDetectedPayload, doc="A wake phrase fired.")@@ -754,6 +761,6 @@ __all__ = ["StreamDeltaPayload", "SubagentEventPayload", "SubagentOutputTailEntry", "TerminalClosePayload","TerminalOutputPayload", "TipShowPayload", "TodoUpdatedPayload", "ToolCompletePayload","ToolGeneratingPayload", "ToolLabel", "ToolLabelKind", "ToolOutputRiskPayload", "ToolStartPayload",- "TurnStatus", "VoiceStatusPayload",+ "TurnStatus", "VoicePartialPayload", "VoiceStatusPayload","VoiceTranscriptPayload", "WakeDetectedPayload",]diff --git a/tui_gateway/methods_voice.py b/tui_gateway/methods_voice.pyindex 5f7b9c03c05..d9caa53d553 100644--- a/tui_gateway/methods_voice.py+++ b/tui_gateway/methods_voice.py@@ -766,7 +766,7 @@ def _(rid, params: dict) -> dict:silence_threshold=_voice_cfg_number(voice_cfg.get("silence_threshold"), 200),silence_duration=_voice_cfg_number(voice_cfg.get("silence_duration"), 3.0),auto_restart=False, max_recording_seconds=max_rec if max_rec > 0 else 0.0,- on_stop_phrase=_vr_on_stop_phrase)+ on_stop_phrase=_vr_on_stop_phrase, on_partial=lambda t: _voice_emit("voice.partial", {"text": t}))if started is False:_resume_voice_wake()return _ok(rid, {"status": "busy" if started is False else "recording"})diff --git a/ui-tui/src/__tests__/voicePartialStore.test.ts b/ui-tui/src/__tests__/voicePartialStore.test.tsnew file mode 100644index 00000000000..e228cd73e42--- /dev/null+++ b/ui-tui/src/__tests__/voicePartialStore.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it, vi } from 'vitest'++import { $voicePartial, handleVoiceCapture } from '../app/voicePartialStore.js'++describe('handleVoiceCapture', () => {+ it('shows live STT text until the capture settles', () => {+ const voice = { setProcessing: vi.fn(), setRecording: vi.fn() }++ handleVoiceCapture({ payload: { text: 'schedule a meeting' }, type: 'voice.partial' } as any, voice)+ handleVoiceCapture({ payload: { state: 'transcribing' }, type: 'voice.status' } as any, voice)+ expect($voicePartial.get()).toBe('schedule a meeting')+ expect(voice.setProcessing).toHaveBeenLastCalledWith(true)++ handleVoiceCapture({ payload: { state: 'idle' }, type: 'voice.status' } as any, voice)+ expect($voicePartial.get()).toBe('')+ expect(voice.setRecording).toHaveBeenLastCalledWith(false)+ })+})diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.tsindex 433c944670e..03c21fb83fc 100644--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@ -51,6 +51,7 @@ import {stderrLooksLikeProblem,stderrProblemActivity} from './userMessages.js'+import { handleVoiceCapture } from './voicePartialStore.js'import { isWakeUserDisabled } from './wakeState.js'const NO_PROVIDER_RE = /\bNo (?:LLM|inference) provider configured\b/i@@ -801,6 +802,10 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:return}+ if (handleVoiceCapture(ev, ctx.voice)) {+ return+ }+switch (ev.type) {case 'connection.request':if (ev.payload) {@@ -1040,25 +1045,6 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:return}- case 'voice.status': {- // Continuous VAD loop reports its internal state so the status bar- // can show listening / transcribing / idle without polling.- const state = String(ev.payload?.state ?? '')-- if (state === 'listening') {- setVoiceRecording(true)- setVoiceProcessing(false)- } else if (state === 'transcribing') {- setVoiceRecording(false)- setVoiceProcessing(true)- } else {- setVoiceRecording(false)- setVoiceProcessing(false)- }-- return- }-case 'voice.transcript': {// Explicit user-intent stop: the user said (or typed) a bare stop// phrase. The backend already halted the capture loop and flippeddiff --git a/ui-tui/src/app/voicePartialStore.ts b/ui-tui/src/app/voicePartialStore.tsnew file mode 100644index 00000000000..1753ac3b5d4--- /dev/null+++ b/ui-tui/src/app/voicePartialStore.ts@@ -0,0 +1,43 @@+import { atom } from 'nanostores'++import type { AnyGatewayEvent } from '../gatewayTypes.js'++// Live STT text so far while the user is still speaking (`voice.partial`, stt.streaming). The+// composer shows it as its placeholder until the capture settles.+export const $voicePartial = atom('')++interface VoiceCaptureSetters {+ setProcessing: (value: boolean) => void+ setRecording: (value: boolean) => void+}++/** Capture-state events (`voice.partial`, `voice.status`); true when fully handled here. A+ * `voice.transcript` only clears the partial and stays with the main handler. */+export function handleVoiceCapture(ev: AnyGatewayEvent, voice: VoiceCaptureSetters): boolean {+ if (ev.type === 'voice.partial') {+ $voicePartial.set(String(ev.payload?.text ?? ''))++ return true+ }++ if (ev.type === 'voice.transcript') {+ $voicePartial.set('')++ return false+ }++ if (ev.type !== 'voice.status') {+ return false+ }++ // The continuous VAD loop reports listening / transcribing / idle so the status bar needs no polling.+ const state = String(ev.payload?.state ?? '')+ voice.setRecording(state === 'listening')+ voice.setProcessing(state === 'transcribing')++ if (state !== 'listening' && state !== 'transcribing') {+ $voicePartial.set('')+ }++ return true+}diff --git a/ui-tui/src/components/appLayout.tsx b/ui-tui/src/components/appLayout.tsxindex 29101142069..2808ae5ccd0 100644--- a/ui-tui/src/components/appLayout.tsx+++ b/ui-tui/src/components/appLayout.tsx@@ -11,6 +11,7 @@ import { $isBlocked, $overlayState, patchOverlayState } from '../app/overlayStorimport { $petBox } from '../app/petFlashStore.js'import { $uiState } from '../app/uiStore.js'import { usePet } from '../app/usePet.js'+import { $voicePartial } from '../app/voicePartialStore.js'import { INLINE_MODE, NATIVE_MODE, SHOW_FPS, TERMUX_TUI_MODE } from '../config/env.js'import { placeholder } from '../content/placeholders.js'import { prevRenderedMsg } from '../domain/blockLayout.js'@@ -42,6 +43,12 @@ import { type InputCursorSnapshot, TextInput, type TextInputMouseApi } from './t// Box geometry, kept here so the transcript's reservation math matches the// rendered overlay exactly.++/** Blank-input hint: live STT text while dictating (stt.streaming) always wins; else a rotating+ * placeholder on a fresh transcript, or the busy hint. */+const composerHint = (voicePartial: string, freshTranscript: boolean, busyHint: string) =>+ voicePartial || (freshTranscript ? placeholder() : busyHint)+const PET_BOTTOM = 3 // rows the pet floats above the screen bottom (over the composer)const PET_PAD_LEFT = 2const PET_RIGHT = 1@@ -304,6 +311,7 @@ const ComposerPane = memo(function ComposerPane({nativeMode: boolean}) {const ui = useStore($uiState)+ const voicePartial = useStore($voicePartial)const T = useT()const isBlocked = useStore($isBlocked)const sh = (composer.inputBuf[0] ?? composer.input).startsWith('!')@@ -462,7 +470,7 @@ const ComposerPane = memo(function ComposerPane({onChange={composer.updateInput}onPaste={composer.handleTextPaste}onSubmit={composer.submit}- placeholder={composer.empty ? placeholder() : ui.busy ? T.composer.interruptHint : ''}+ placeholder={composerHint(voicePartial, composer.empty, ui.busy ? T.composer.interruptHint : '')}// Exactly the "(and N more toolsetsβ¦)" tone. `muted` is a// MID-luminance family tone, so it reads receded on both// poles even when polarity detection is wrong (transparentdiff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex a72071438d3..37e407c5be6 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -2435,6 +2435,7 @@ stt:echo_transcripts: true # Post raw transcripts back to the chat as ποΈ "..." (default: true)provider: "local" # "local" | "groq" | "openai" | "mistral" | "xai" | "elevenlabs" | "deepinfra" | ...language: "en" # GLOBAL language hint for every provider (per-provider language wins); set "" for auto-detect+ streaming: false # live partial text while you speak (openai, xai, elevenlabs); see Voice Mode > Live transcriptioncloud_trim_silence: true # trim long pauses with ffmpeg before uploading to a cloud provider (default: true)cloud_trim_threshold_db: -40 # audio quieter than this counts as silencecloud_trim_keep_ms: 300 # how much of each pause survives the trim (keeps natural pacing)diff --git a/website/docs/user-guide/features/voice-mode.md b/website/docs/user-guide/features/voice-mode.mdindex 5e64aec3410..db7c8f10878 100644--- a/website/docs/user-guide/features/voice-mode.md+++ b/website/docs/user-guide/features/voice-mode.md@@ -174,6 +174,27 @@ Say **"stop"** β and nothing else β to end the voice conversation hands-free**Typing** a bare stop phrase while a voice chat is active works the same way on every surface (CLI, TUI, desktop): the message ends the voice chat instead of being sent to the agent. Outside a voice chat, typed "stop" is an ordinary message.+### Live transcription (streaming STT)++Set `stt.streaming: true` to transcribe while you speak instead of after you stop. Partial text appears as you talk (in the classic CLI and TUI input placeholder, and in the Desktop dictation pill), and the transcript is ready when you stop speaking instead of after a full upload.++```yaml+stt:+ provider: openai # or xai, elevenlabs+ streaming: true+ openai:+ streaming_model: gpt-live-transcribe # the default; the one OpenAI model that streams text mid-utterance+```++| Provider | Live endpoint | Notes |+|---|---|---|+| `openai` | Realtime transcription session | Needs your own `OPENAI_API_KEY`; the Nous-managed audio gateway serves file transcription only |+| `xai` | `wss://api.x.ai/v1/stt` | Needs `XAI_API_KEY` (the Grok OAuth login is not used for live STT) |+| `elevenlabs` | Scribe v2 realtime | `ELEVENLABS_API_KEY` |+| plugin | `TranscriptionProvider.streaming_capable` | Plugins opt in with `open_stream_session()` |++Live transcription covers CLI and TUI voice mode and Desktop dictation. Local whisper, Groq, Mistral and DeepInfra keep using the file path. If a live session can't open, or fails mid-recording, Hermes transcribes the recording as usual, so turning this on never loses a take.+### Streaming TTSWhen TTS is enabled, the agent speaks its reply **sentence-by-sentence** as it generates text β you don't wait for the full response. This works with **every TTS provider**: