Skip to content

The agent that grows with you

fix(desktop): drop voice-conversation barge captures that echo the spoken reply

Austin Pickettf0410eb4f0c0
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 288841f9ef3..83eeec55a86 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
@@ -2,6 +2,7 @@ import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
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 type { MicRecording } from './use-mic-recorder'
@@ -27,6 +28,7 @@ vi.mock('@/lib/voice-barge-in', () => ({
const markVoicePlaybackInterrupted = vi.fn()
const stopVoicePlayback = vi.fn()
+const takeVoicePlaybackInterrupted = vi.fn(() => true)
const playSpeechTextMock = vi.fn(async () => true)
const startSpeechStreamMock = vi.fn(async () => null)
@@ -35,7 +37,8 @@ vi.mock('@/lib/voice-playback', () => ({
markVoicePlaybackInterrupted: () => markVoicePlaybackInterrupted(),
playSpeechText: (...args: unknown[]) => playSpeechTextMock(...(args as [])),
startSpeechStream: (...args: unknown[]) => startSpeechStreamMock(...(args as [])),
- stopVoicePlayback: () => stopVoicePlayback()
+ stopVoicePlayback: () => stopVoicePlayback(),
+ takeVoicePlaybackInterrupted: () => takeVoicePlaybackInterrupted()
}))
vi.mock('@/lib/thinking-sound', () => ({
@@ -278,6 +281,93 @@ describe('useVoiceConversation full-duplex barge-in', () => {
})
})
+// #126708 — over speakers the reply bleeds into the mic and trips the
+// playback-phase barge. The CLI drops a capture that matches what it was
+// speaking (tools/voice_mode_transcript.is_tts_echo); the desktop loop must
+// too, instead of submitting Hermes' own words as an "interrupting" user turn.
+describe('useVoiceConversation TTS echo guard (#126708)', () => {
+ const spokenReply =
+ "Sure, here's a summary of what we found. The build failed because of a missing dependency in the " +
+ "lockfile. I've already gone ahead and regenerated it, and the tests are passing again locally."
+
+ let replyReady: boolean
+
+ beforeEach(() => {
+ replyReady = false
+ monitorCalls.length = 0
+ vi.clearAllMocks()
+ micHandle.start.mockResolvedValue(undefined)
+ micHandle.stop.mockResolvedValue(null)
+ })
+
+ afterEach(() => {
+ $voicePlayback.set({ ...$voicePlayback.get(), status: 'idle' })
+ cleanup()
+ })
+
+ /** Barge while `spokenReply` is (or is not) audibly playing, then deliver the capture. */
+ const bargeWith = async (transcript: string, { playing }: { playing: boolean }) => {
+ const convo = renderConversation({
+ pendingResponse: () => (replyReady ? { id: 'reply-1', pending: false, text: spokenReply } : null),
+ transcript
+ })
+
+ await act(async () => {
+ await convo.hook.result.current.start()
+ })
+ await enterThinking(convo.hook)
+ await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0))
+
+ const monitor = monitorCalls.at(-1)
+
+ replyReady = true
+ $voicePlayback.set({ ...$voicePlayback.get(), status: playing ? 'speaking' : 'idle' })
+
+ act(() => {
+ monitor?.onSpeech()
+ })
+ // The barged reply is consumed (settleAfterSpeech) and the turn ends.
+ replyReady = false
+ convo.hook.rerender({ busy: false })
+
+ const startsBefore = micHandle.start.mock.calls.length
+
+ await act(async () => {
+ monitor?.onUtterance?.(new Blob(['e'], { type: 'audio/webm' }))
+ })
+ await waitFor(() => expect(convo.onTranscribeAudio).toHaveBeenCalledTimes(2))
+
+ return { ...convo, startsBefore }
+ }
+
+ it('drops a playback-phase capture that is a fragment of the reply being spoken', async () => {
+ const { onSubmit, startsBefore } = await bargeWith('the build failed because of a missing dependency', {
+ playing: true
+ })
+
+ // The mic re-arms for a real turn…
+ await waitFor(() => expect(micHandle.start.mock.calls.length).toBeGreaterThan(startsBefore))
+ // …and only the kickoff turn was ever submitted.
+ expect(onSubmit).toHaveBeenCalledTimes(1)
+ expect(onSubmit).not.toHaveBeenCalledWith('the build failed because of a missing dependency')
+ // The "user interrupted" latch is cleared so a later genuine turn isn't annotated.
+ expect(takeVoicePlaybackInterrupted).toHaveBeenCalledTimes(1)
+ })
+
+ it('still submits a genuine interjection captured during playback', async () => {
+ const { onSubmit } = await bargeWith('actually can you also check my calendar for tomorrow', { playing: true })
+
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('actually can you also check my calendar for tomorrow'))
+ expect(takeVoicePlaybackInterrupted).not.toHaveBeenCalled()
+ })
+
+ it('does not apply the guard to a generation-phase trip (nothing audible to echo)', async () => {
+ const { onSubmit } = await bargeWith('the build failed because of a missing dependency', { playing: false })
+
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('the build failed because of a missing dependency'))
+ })
+})
+
// #44263 — the "Read replies aloud" toggle ($autoSpeakReplies, the store the
// settings toggle writes, seeded once from voice.auto_tts) must govern the
// voice-conversation loop too: with it off, Voice Chat runs STT-only and the
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 41c8d55b14a..4b1aeab50b2 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
@@ -9,9 +9,11 @@ import {
playSpeechText,
type SpeechStreamSession,
startSpeechStream,
- stopVoicePlayback
+ stopVoicePlayback,
+ takeVoicePlaybackInterrupted
} from '@/lib/voice-playback'
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'
@@ -91,6 +93,9 @@ export function useVoiceConversation({
const stopBargeMonitorRef = useRef<(() => void) | null>(null)
const bargeCapturePendingRef = useRef(false)
const bargedRef = useRef(false)
+ // Reply text that was playing when the barge tripped ('' for a
+ // generation-phase trip: nothing audible, so nothing to echo).
+ const bargeEchoTextRef = useRef('')
const speechStartSequenceRef = useRef(0)
const enabledRef = useRef(enabled)
const mutedRef = useRef(muted)
@@ -157,6 +162,7 @@ export function useVoiceConversation({
stopBargeMonitorRef.current = null
bargeCapturePendingRef.current = false
bargedRef.current = false
+ bargeEchoTextRef.current = ''
speechSessionRef.current = null
responseIdRef.current = null
spokenSourceLengthRef.current = 0
@@ -367,6 +373,10 @@ export function useVoiceConversation({
*/
const submitCapturedUtterance = useCallback(
async (audio: Blob | null) => {
+ const echoSource = bargeEchoTextRef.current
+
+ bargeEchoTextRef.current = ''
+
const resumeListening = () => {
if (enabledRef.current && !mutedRef.current) {
pendingStartRef.current = true
@@ -403,6 +413,18 @@ export function useVoiceConversation({
return
}
+ // Fail-closed echo guard (tools/voice_mode_transcript.is_tts_echo):
+ // over speakers the reply bleeds into the mic and trips the playback-
+ // phase trigger. A transcript matching what was being spoken is
+ // Hermes hearing itself — treat it as silence: no submit, and clear
+ // the interruption latch so a later real turn isn't annotated.
+ if (echoSource && isTtsEcho(transcript, echoSource)) {
+ takeVoicePlaybackInterrupted()
+ resumeListening()
+
+ return
+ }
+
// A generation-phase barge interrupted the in-flight turn; the submit
// path refuses while `busy`, so wait for the interrupt to settle.
const deadline = Date.now() + INTERRUPT_SETTLE_TIMEOUT_MS
@@ -447,6 +469,9 @@ export function useVoiceConversation({
isPlaying: () => $voicePlayback.get().status === 'speaking',
thresholdMultiplier: $bargeInThresholdMultiplier.get(),
onSpeech: () => {
+ // Snapshot before playback is cut: the reply may be consumed by the
+ // time the capture is transcribed.
+ bargeEchoTextRef.current = $voicePlayback.get().status === 'speaking' ? (pendingResponse()?.text ?? '') : ''
bargeCapturePendingRef.current = true
bargedRef.current = true
markVoicePlaybackInterrupted()
@@ -464,7 +489,7 @@ export function useVoiceConversation({
void submitCapturedUtterance(audio)
}
})
- }, [submitCapturedUtterance])
+ }, [pendingResponse, submitCapturedUtterance])
/** Push any new reply text into the live session; finish when complete. */
const feedSpeechSession = useCallback(
diff --git a/apps/desktop/src/lib/voice-tts-echo.test.ts b/apps/desktop/src/lib/voice-tts-echo.test.ts
new file mode 100644
index 00000000000..8fdc60b4fb2
--- /dev/null
+++ b/apps/desktop/src/lib/voice-tts-echo.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest'
+
+import { isTtsEcho, sequenceMatcherRatio } from './voice-tts-echo'
+
+// Mirrors tests/tools/test_voice_tts_echo_guard.py::TestIsTtsEcho so the
+// desktop guard and the CLI guard agree on what counts as echo.
+describe('isTtsEcho', () => {
+ it('flags a near-verbatim repeat', () => {
+ const spoken =
+ '맞아요. 사용자가 마이크를 끄는 게 아니라 앱이 제 음성은 에코 제거로 걸러내고 실제 사용자 음성만 끼어들기로 받아야 해요.'
+
+ expect(isTtsEcho(spoken, spoken)).toBe(true)
+ })
+
+ it('flags a repeat with a leading stutter', () => {
+ expect(
+ isTtsEcho('네 방금 네 방금도 제 답변이 그대로 다시 입력됐어요.', '네, 방금도 제 답변이 그대로 다시 입력됐어요.')
+ ).toBe(true)
+ })
+
+ it('does not flag an unrelated interjection', () => {
+ expect(
+ isTtsEcho(
+ 'actually can you also check my calendar for tomorrow',
+ 'The weather today is sunny with a light breeze from the west.'
+ )
+ ).toBe(false)
+ })
+
+ it('does not flag a short unrelated reply', () => {
+ expect(isTtsEcho('stop', "I've finished summarizing the document you shared earlier.")).toBe(false)
+ })
+
+ it('flags a short fragment of a longer multi-sentence reply', () => {
+ const spoken =
+ "Sure, here's a summary of what we found. The build failed because of a missing dependency in the " +
+ "lockfile. I've already gone ahead and regenerated it, and the tests are passing again locally. Let " +
+ "me know if you'd like me to open a PR for this or if you want to review the diff first before I do " +
+ 'anything else.'
+
+ expect(isTtsEcho("Sure, here's a summary of what we found.", spoken)).toBe(true)
+ })
+
+ it('flags a fragment from the middle of a reply', () => {
+ const spoken =
+ 'The deployment finished successfully. All three services came up healthy, and the smoke tests passed without any errors.'
+
+ expect(isTtsEcho('the smoke tests passed without any errors', spoken)).toBe(true)
+ })
+
+ it('does not flag a short genuine acknowledgement that appears inside the reply', () => {
+ expect(isTtsEcho('yes', 'Yes, I can help with that -- let me pull up the details for you.')).toBe(false)
+ })
+
+ it('flags a fragment in a no-whitespace language', () => {
+ const spoken = '部署已经成功完成。所有三个服务都正常运行状态良好,冒烟测试也全部通过,没有发现任何错误。'
+
+ expect(isTtsEcho('所有三个服务都正常运行状态良好', spoken)).toBe(true)
+ })
+
+ it('treats empty inputs as not echo', () => {
+ expect(isTtsEcho('', 'hello')).toBe(false)
+ expect(isTtsEcho('hello', '')).toBe(false)
+ expect(isTtsEcho('', '')).toBe(false)
+ })
+
+ it('is case and whitespace insensitive', () => {
+ expect(isTtsEcho(' SURE, I can help with that right away. ', 'Sure, I can help with that right away.')).toBe(
+ true
+ )
+ })
+
+ it('honors a custom threshold', () => {
+ const spoken = 'This is a moderately similar sentence about testing.'
+ const transcript = 'This is a rather different sentence about coding.'
+
+ expect(isTtsEcho(transcript, spoken, 0.5)).toBe(true)
+ expect(isTtsEcho(transcript, spoken, 0.95)).toBe(false)
+ })
+})
+
+describe('sequenceMatcherRatio', () => {
+ // Reference values from CPython difflib.SequenceMatcher(None, a, b).ratio().
+ it.each([
+ ['abcd', 'bcde', 0.75],
+ [
+ 'This is a rather different sentence about coding.',
+ 'This is a moderately similar sentence about testing.',
+ 0.693069306930693
+ ],
+ ['', '', 1]
+ ])('%j vs %j', (a, b, expected) => {
+ expect(sequenceMatcherRatio(Array.from(a), Array.from(b))).toBeCloseTo(expected, 12)
+ })
+
+ it('applies autojunk to a 200+ element b like CPython', () => {
+ const a = Array.from('the smoke tests passed without any errors')
+ const b = Array.from('The deployment finished successfully. '.repeat(6).toLowerCase())
+
+ expect(sequenceMatcherRatio(a, b)).toBeCloseTo(0.02973977695167286, 12)
+ })
+})
diff --git a/apps/desktop/src/lib/voice-tts-echo.ts b/apps/desktop/src/lib/voice-tts-echo.ts
new file mode 100644
index 00000000000..a3ffa60d6e5
--- /dev/null
+++ b/apps/desktop/src/lib/voice-tts-echo.ts
@@ -0,0 +1,160 @@
+// TTS self-echo guard for the voice-conversation barge monitor — a port of
+// tools/voice_mode_transcript.is_tts_echo (the CLI's fix for the
+// TTS -> STT -> TTS loop). Over speakers, Hermes' own reply bleeds into the
+// mic, trips the playback-phase barge trigger, and gets transcribed; without
+// this check the fragment is submitted as a user turn nobody spoke (#126708).
+//
+// Keep in lockstep with the Python rule: character-level similarity via a
+// faithful difflib.SequenceMatcher(None, a, b).ratio() port (autojunk
+// included), 0.6 threshold, and a transcript-sized sliding window over the
+// spoken text for fragments of long replies.
+
+/** tools/voice_mode_transcript.DEFAULT_TTS_ECHO_SIMILARITY_THRESHOLD */
+export const DEFAULT_TTS_ECHO_SIMILARITY_THRESHOLD = 0.6
+
+/** tools/voice_mode_transcript.MIN_FRAGMENT_LENGTH_FOR_ECHO — below this a
+ * genuine one-word barge ("yes") would trivially match a same-size window. */
+export const MIN_FRAGMENT_LENGTH_FOR_ECHO = 10
+
+// Code points, like Python str indexing (UTF-16 units would split CJK/emoji).
+const normalizeForEchoCompare = (text: string): string[] => Array.from(text.replace(/\s+/gu, ' ').trim().toLowerCase())
+
+/** difflib.SequenceMatcher(None, a, b).ratio() — isjunk=None, autojunk=True. */
+export function sequenceMatcherRatio(a: readonly string[], b: readonly string[]): number {
+ const total = a.length + b.length
+
+ if (total === 0) {
+ return 1
+ }
+
+ const b2j = new Map<string, number[]>()
+
+ b.forEach((ch, j) => {
+ const indices = b2j.get(ch)
+
+ if (indices) {
+ indices.push(j)
+ } else {
+ b2j.set(ch, [j])
+ }
+ })
+
+ // autojunk: elements more common than 1% of a 200+-long b are "popular" and
+ // never seed a match (they can still extend one, as in CPython).
+ if (b.length >= 200) {
+ const ntest = Math.floor(b.length / 100) + 1
+
+ for (const [ch, indices] of b2j) {
+ if (indices.length > ntest) {
+ b2j.delete(ch)
+ }
+ }
+ }
+
+ const findLongestMatch = (alo: number, ahi: number, blo: number, bhi: number): [number, number, number] => {
+ let besti = alo
+ let bestj = blo
+ let bestsize = 0
+ let j2len = new Map<number, number>()
+
+ for (let i = alo; i < ahi; i++) {
+ const next = new Map<number, number>()
+
+ for (const j of b2j.get(a[i]) ?? []) {
+ if (j < blo) {
+ continue
+ }
+
+ if (j >= bhi) {
+ break
+ }
+
+ const k = (j2len.get(j - 1) ?? 0) + 1
+ next.set(j, k)
+
+ if (k > bestsize) {
+ besti = i - k + 1
+ bestj = j - k + 1
+ bestsize = k
+ }
+ }
+
+ j2len = next
+ }
+
+ // bjunk is empty (isjunk=None), so CPython's "extend with non-junk" loops
+ // always run; this is how popular elements join a match.
+ while (besti > alo && bestj > blo && a[besti - 1] === b[bestj - 1]) {
+ besti--
+ bestj--
+ bestsize++
+ }
+
+ while (besti + bestsize < ahi && bestj + bestsize < bhi && a[besti + bestsize] === b[bestj + bestsize]) {
+ bestsize++
+ }
+
+ return [besti, bestj, bestsize]
+ }
+
+ let matches = 0
+ const queue: [number, number, number, number][] = [[0, a.length, 0, b.length]]
+
+ while (queue.length > 0) {
+ const [alo, ahi, blo, bhi] = queue.pop()!
+ const [i, j, k] = findLongestMatch(alo, ahi, blo, bhi)
+
+ if (k) {
+ matches += k
+
+ if (alo < i && blo < j) {
+ queue.push([alo, i, blo, j])
+ }
+
+ if (i + k < ahi && j + k < bhi) {
+ queue.push([i + k, ahi, j + k, bhi])
+ }
+ }
+ }
+
+ return (2 * matches) / total
+}
+
+/**
+ * True when `transcript` looks like a self-capture of `spokenText` (the reply
+ * Hermes was speaking when the barge tripped). A genuine interjection rarely
+ * matches Hermes' own words, so a high ratio signals speaker bleed. Playback
+ * captures span only pre-roll plus time-to-silence, so for long replies the
+ * transcript is a FRAGMENT; when the whole-string ratio misses, a
+ * transcript-sized window slides across the spoken text.
+ */
+export function isTtsEcho(
+ transcript: string,
+ spokenText: string,
+ threshold: number = DEFAULT_TTS_ECHO_SIMILARITY_THRESHOLD
+): boolean {
+ const a = normalizeForEchoCompare(transcript || '')
+ const b = normalizeForEchoCompare(spokenText || '')
+
+ if (a.length === 0 || b.length === 0) {
+ return false
+ }
+
+ const similar = (x: readonly string[], y: readonly string[]) => sequenceMatcherRatio(x, y) >= threshold
+
+ if (similar(a, b)) {
+ return true
+ }
+
+ if (a.length < MIN_FRAGMENT_LENGTH_FOR_ECHO || a.length >= b.length) {
+ return false
+ }
+
+ for (let start = 0; start <= b.length - a.length; start++) {
+ if (similar(a, b.slice(start, start + a.length))) {
+ return true
+ }
+ }
+
+ return false
+}