Skip to content

The agent that grows with you

fix(desktop): client-direct STT hallucination filter and voice.barge_in pref (#126708)

Brooklyn Nicholsone49a6afe07ef
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.test.tsx
index 83eeec55a86..3ce59dbd895 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.test.tsx
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { BargeMonitorCallbacks } from '@/lib/voice-barge-in'
import { $voicePlayback } from '@/store/voice-playback'
-import { $autoSpeakReplies } from '@/store/voice-prefs'
+import { $autoSpeakReplies, $bargeInEnabled } from '@/store/voice-prefs'
import type { MicRecording } from './use-mic-recorder'
import { useVoiceConversation } from './use-voice-conversation'
@@ -173,6 +173,27 @@ describe('useVoiceConversation full-duplex barge-in', () => {
await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0))
})
+ it('never arms the barge monitor when voice.barge_in is false (#126708)', async () => {
+ $bargeInEnabled.set(false)
+ try {
+ const { hook } = renderConversation()
+
+ await act(async () => {
+ await hook.result.current.start()
+ })
+ await enterThinking(hook)
+
+ await waitFor(() => expect(hook.result.current.status).toBe('thinking'))
+ // Give the drive effect a chance to arm — it must not.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 50))
+ })
+ expect(monitorCalls.length).toBe(0)
+ } finally {
+ $bargeInEnabled.set(true)
+ }
+ })
+
it('interrupts the in-flight turn when speech trips mid-generation', async () => {
const { hook, onInterrupt } = renderConversation()
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts
index 82ac8871de7..2a49f497f32 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts
@@ -17,7 +17,7 @@ import { isVoiceStopCommand } from '@/lib/voice-stop-word'
import { isTtsEcho } from '@/lib/voice-tts-echo'
import { notify, notifyError } from '@/store/notifications'
import { $voicePlayback } from '@/store/voice-playback'
-import { $autoSpeakReplies, $bargeInThresholdMultiplier, $voiceSilenceMs } from '@/store/voice-prefs'
+import { $autoSpeakReplies, $bargeInEnabled, $bargeInThresholdMultiplier, $voiceSilenceMs } from '@/store/voice-prefs'
import { useComposerScope } from '../scope'
@@ -474,6 +474,12 @@ export function useVoiceConversation({
* all call this).
*/
const ensureBargeMonitor = useCallback(() => {
+ // `voice.barge_in: false` disarms the listener entirely, mirroring the
+ // gateway's `_arm_barge_listener_if_enabled` gate.
+ if (!$bargeInEnabled.get()) {
+ return
+ }
+
if (stopBargeMonitorRef.current) {
return
}
diff --git a/apps/desktop/src/app/session/hooks/use-hermes-config.ts b/apps/desktop/src/app/session/hooks/use-hermes-config.ts
index a663a2c44c4..4402c79d66d 100644
--- a/apps/desktop/src/app/session/hooks/use-hermes-config.ts
+++ b/apps/desktop/src/app/session/hooks/use-hermes-config.ts
@@ -21,6 +21,7 @@ import { setShowToolActivityFromConfig } from '@/store/tool-activity'
import { refreshVoiceLiveStatus } from '@/store/voice-live'
import {
applyAutoSpeakFromConfig,
+ applyBargeInEnabledFromConfig,
applyBargeInThresholdFromConfig,
applyThinkingSoundFromConfig,
applyVoiceSilenceMsFromConfig,
@@ -155,6 +156,7 @@ export function useHermesConfig({ activeSessionIdRef }: HermesConfigOptions) {
applyAutoSpeakFromConfig(config)
applyVoiceStopPhraseFromConfig(config, defaults)
+ applyBargeInEnabledFromConfig(config)
applyBargeInThresholdFromConfig(config)
applyThinkingSoundFromConfig(config)
applyVoiceSilenceMsFromConfig(config, defaults)
diff --git a/apps/desktop/src/lib/voice-client-direct.test.ts b/apps/desktop/src/lib/voice-client-direct.test.ts
index 6b82532b21f..f0a2ecb38a8 100644
--- a/apps/desktop/src/lib/voice-client-direct.test.ts
+++ b/apps/desktop/src/lib/voice-client-direct.test.ts
@@ -6,6 +6,7 @@ import {
clearVoiceClientConfigCache,
type DirectTtsConfig,
fetchVoiceClientConfig,
+ isSttSilenceHallucination,
synthesizeSpeechClientDirect,
transcribeAudioClientDirect,
transcriptFromOpenAiMultipartBody
@@ -156,6 +157,52 @@ describe('transcribeAudioClientDirect', () => {
expect(fetchMock).not.toHaveBeenCalled()
})
+ it('treats a Whisper silence hallucination like the relay path: silence, not a turn (#126708)', async () => {
+ const filter = {
+ phrases: ['thank you', 'bye', 'you', 'the end'],
+ repeat_regex: '^(?:thank you|thanks|bye|you|ok|okay|the end|[.,!\\s])+$'
+ }
+
+ mockDesktopApi({ ok: true, stt: { ...directStt, hallucination_filter: filter }, tts: relay })
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('Thank you.', { status: 200 })))
+ expect(await transcribeAudioClientDirect(new Blob(['x']))).toBe('')
+
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('OK. OK. OK.', { status: 200 })))
+ expect(await transcribeAudioClientDirect(new Blob(['x']))).toBe('')
+
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('The end', { status: 200 })))
+ expect(await transcribeAudioClientDirect(new Blob(['x']))).toBe('')
+
+ // A real utterance passes through untouched, and an older backend without
+ // the filter never drops a transcript.
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('Thanks, that fixed it', { status: 200 })))
+ expect(await transcribeAudioClientDirect(new Blob(['x']))).toBe('Thanks, that fixed it')
+
+ // Older backend: no hallucination_filter on the config → pass-through.
+ clearVoiceClientConfigCache()
+ mockDesktopApi({ ok: true, stt: directStt, tts: relay })
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('Thank you.', { status: 200 })))
+ expect(await transcribeAudioClientDirect(new Blob(['x']))).toBe('Thank you.')
+ })
+
+ it('isSttSilenceHallucination mirrors the relay contract', () => {
+ const filter = {
+ phrases: ['thank you', 'bye', 'you'],
+ repeat_regex: '^(?:thank you|thanks|bye|you|ok|okay|the end|[.,!\\s])+$'
+ }
+
+ // Known hallucination, case/punctuation-insensitive.
+ expect(isSttSilenceHallucination('Thank you!', filter)).toBe(true)
+ // Repetitive filler.
+ expect(isSttSilenceHallucination('ok ok ok', filter)).toBe(true)
+ // Empty = silence.
+ expect(isSttSilenceHallucination(' ', filter)).toBe(true)
+ // A genuine short utterance is NOT a hallucination.
+ expect(isSttSilenceHallucination('OK, do it', filter)).toBe(false)
+ // No filter (older backend) → never drop.
+ expect(isSttSilenceHallucination('Thank you.', null)).toBe(false)
+ })
+
it('surfaces provider rejections instead of silently relaying', async () => {
mockDesktopApi({ ok: true, stt: directStt, tts: relay })
vi.stubGlobal(
diff --git a/apps/desktop/src/lib/voice-client-direct.ts b/apps/desktop/src/lib/voice-client-direct.ts
index 62fed48cbdc..0a2dea2c57e 100644
--- a/apps/desktop/src/lib/voice-client-direct.ts
+++ b/apps/desktop/src/lib/voice-client-direct.ts
@@ -29,6 +29,9 @@ export interface DirectSttConfig {
language: null | string
/** Seconds the gateway allows one transcription request (`stt.openai.timeout`); absent on older backends. */
timeout_s?: null | number
+ /** Silence-hallucination contract the relay path applies (`is_whisper_hallucination`);
+ * absent on older backends — a matching transcript is still returned as-is then. */
+ hallucination_filter?: null | { phrases: string[]; repeat_regex: string }
}
export interface DirectTtsConfig {
@@ -190,6 +193,39 @@ export function sttTimeoutSeconds(stt: Pick<DirectSttConfig, 'timeout_s'>): numb
return Number.isFinite(value) && value > 0 ? value : DEFAULT_STT_TIMEOUT_S
}
+/**
+ * The relay path's Whisper-silence filter (`is_whisper_hallucination`,
+ * tools/voice_mode_transcript.py): empty, an exact known hallucination
+ * (lowercased, trailing `.!` stripped), or repetitive filler like
+ * "Thank you. Thank you." A client-direct transcript must agree with a
+ * relayed one instead of submitting "thank you" on silence as a real turn.
+ * No filter on the config (older backend) → the transcript passes through.
+ */
+export function isSttSilenceHallucination(
+ transcript: string,
+ filter: DirectSttConfig['hallucination_filter']
+): boolean {
+ if (!filter) {
+ return false
+ }
+
+ const cleaned = transcript.trim().toLowerCase()
+
+ if (!cleaned) {
+ return true
+ }
+
+ if (filter.phrases.includes(cleaned.replaceAll('!', '').replaceAll('.', ''))) {
+ return true
+ }
+
+ try {
+ return new RegExp(filter.repeat_regex, 'i').test(cleaned)
+ } catch {
+ return false
+ }
+}
+
/**
* `fetch` with the STT deadline. A slow or wedged endpoint otherwise keeps the
* dictation UI in "transcribing" forever — the browser applies no timeout of
@@ -253,7 +289,11 @@ export async function transcribeAudioClientDirect(audio: Blob): Promise<null | s
throw new Error(`${stt.provider} STT error (HTTP ${response.status}): ${await providerErrorText(response)}`)
}
- return transcriptFromOpenAiMultipartBody(await response.text())
+ const transcript = transcriptFromOpenAiMultipartBody(await response.text())
+
+ // Silence hallucination ("thank you" on quiet audio): treat as silence,
+ // exactly like the relay endpoint, instead of submitting a phantom turn.
+ return isSttSilenceHallucination(transcript, stt.hallucination_filter) ? '' : transcript
}
if (stt.wire === 'xai-stt') {
@@ -277,8 +317,10 @@ export async function transcribeAudioClientDirect(audio: Blob): Promise<null | s
}
const result = (await response.json()) as { text?: string }
+ const transcript = (result.text || '').trim()
- return (result.text || '').trim()
+ // Silence hallucination: same contract as the relay endpoint.
+ return isSttSilenceHallucination(transcript, stt.hallucination_filter) ? '' : transcript
}
if (stt.wire === 'elevenlabs-stt') {
@@ -305,8 +347,10 @@ export async function transcribeAudioClientDirect(audio: Blob): Promise<null | s
}
const result = (await response.json()) as { text?: string }
+ const transcript = (result.text || '').trim()
- return (result.text || '').trim()
+ // Silence hallucination: same contract as the relay endpoint.
+ return isSttSilenceHallucination(transcript, stt.hallucination_filter) ? '' : transcript
}
return null
diff --git a/apps/desktop/src/store/voice-prefs.test.ts b/apps/desktop/src/store/voice-prefs.test.ts
index b708cc1bfd7..0181240ccdc 100644
--- a/apps/desktop/src/store/voice-prefs.test.ts
+++ b/apps/desktop/src/store/voice-prefs.test.ts
@@ -9,10 +9,12 @@ import { saveHermesConfig } from '@/hermes'
import { isVoiceStopCommand } from '@/lib/voice-stop-word'
import {
+ $bargeInEnabled,
$bargeInThresholdMultiplier,
$voiceSilenceMs,
$voiceStopPhrase,
$voiceStopPhraseConfig,
+ applyBargeInEnabledFromConfig,
applyBargeInThresholdFromConfig,
applyVoiceSilenceMsFromConfig,
applyVoiceStopPhraseFromConfig
@@ -174,6 +176,30 @@ describe('applyBargeInThresholdFromConfig', () => {
})
})
+// `voice.barge_in` mirrors the gateway's `_arm_barge_listener_if_enabled`
+// (tui_gateway/methods_voice.py): the listener is armed unless the key is
+// explicitly false.
+describe('applyBargeInEnabledFromConfig', () => {
+ it('disarms only an explicit false', () => {
+ applyBargeInEnabledFromConfig({ voice: { barge_in: false } })
+ expect($bargeInEnabled.get()).toBe(false)
+
+ applyBargeInEnabledFromConfig({ voice: { barge_in: true } })
+ expect($bargeInEnabled.get()).toBe(true)
+ })
+
+ it('absent, null, or malformed values keep barge-in enabled', () => {
+ for (const voice of [undefined, {}, { barge_in: null }, { barge_in: 'nope' }, { barge_in: 0 }]) {
+ applyBargeInEnabledFromConfig({ voice: { barge_in: false } })
+ applyBargeInEnabledFromConfig({ voice })
+ expect($bargeInEnabled.get()).toBe(true)
+ }
+
+ applyBargeInEnabledFromConfig(null)
+ expect($bargeInEnabled.get()).toBe(true)
+ })
+})
+
// `voice.silence_duration` drives the desktop loop the way it drives the
// CLI/TUI capture paths, but only when the user actually changed it: `/api/config`
// merges DEFAULT_CONFIG, so an untouched install reports the backend default
diff --git a/apps/desktop/src/store/voice-prefs.ts b/apps/desktop/src/store/voice-prefs.ts
index 8c7d9b10192..4a648df8e9e 100644
--- a/apps/desktop/src/store/voice-prefs.ts
+++ b/apps/desktop/src/store/voice-prefs.ts
@@ -90,6 +90,16 @@ export function applyVoiceStopPhraseFromConfig(config: ConfigPayload, defaults?:
)
}
+// `voice.barge_in` — whether talking over the reply interrupts playback,
+// mirroring `_arm_barge_listener_if_enabled` (tui_gateway/methods_voice.py):
+// armed unless the key is explicitly false. Absent/malformed → enabled.
+export const $bargeInEnabled = atom<boolean>(true)
+
+/** Seed the barge-in gate from a loaded config payload. */
+export function applyBargeInEnabledFromConfig(config: ConfigPayload) {
+ $bargeInEnabled.set(voiceValue(config, 'barge_in') !== false)
+}
+
// `voice.barge_in_threshold_multiplier` — barge-in sensitivity shared with the
// CLI/TUI full-duplex listener. `null` = unset/invalid, so the monitor keeps its
// built-in trigger levels (same as the backend's `float(v or 0)` → default).
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index a2f6e1f7c03..5f4ffef73a2 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -500,6 +500,7 @@ export interface HermesConfig {
auto_tts?: boolean
stop_phrases?: unknown
thinking_sound?: unknown
+ barge_in?: unknown
barge_in_threshold_multiplier?: unknown
silence_duration?: unknown
}
diff --git a/tools/voice_client_config.py b/tools/voice_client_config.py
index c0fb356a4f9..5467982ceef 100644
--- a/tools/voice_client_config.py
+++ b/tools/voice_client_config.py
@@ -62,6 +62,21 @@ def _direct(wire: str, provider: str, base_url: Any, api_key: str, model: Any, *
"api_key": api_key, "model": model, **extra}
+def stt_hallucination_filter() -> Dict[str, Any]:
+ """The Whisper-silence hallucination contract the relay path applies
+ (``transcribe_recording`` → ``is_whisper_hallucination``), shipped to the
+ client so a client-direct transcription agrees with a relayed one instead
+ of submitting "thank you" on silence as a real turn."""
+ from tools.voice_mode_transcript import WHISPER_HALLUCINATIONS
+
+ return {
+ "phrases": sorted(WHISPER_HALLUCINATIONS),
+ # Python's _HALLUCINATION_REPEAT_RE (IGNORECASE) for repetitive filler
+ # like "OK. OK. OK." — a JS regex source, so a single backslash.
+ "repeat_regex": "^(?:thank you|thanks|bye|you|ok|okay|the end|[.,!\\s])+$",
+ }
+
+
def _deepinfra_model(section: Dict[str, Any], kind: str) -> Optional[str]:
"""Configured model, else the first catalog model of ``kind`` (stt/tts)."""
from hermes_cli.models import deepinfra_model_ids
@@ -101,7 +116,8 @@ def _resolve_stt_client_config() -> Dict[str, Any]:
timeout_s = tc._config_number(_section(stt_config, "openai"), "timeout", 60.0)
def direct(wire: str, base_url: Any, api_key: str, model: Any) -> Dict[str, Any]:
- return _direct(wire, provider, base_url, api_key, model, language=language, timeout_s=timeout_s)
+ return _direct(wire, provider, base_url, api_key, model, language=language, timeout_s=timeout_s,
+ hallucination_filter=stt_hallucination_filter())
def env_base_url(env_var: str, default: str) -> str:
from hermes_cli.config import get_env_value