Skip to content

The agent that grows with you

18.4 KB
Raw Blame
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, $bargeInEnabled } from '@/store/voice-prefs'

import type { MicRecording } from './use-mic-recorder'
import { useVoiceConversation } from './use-voice-conversation'

// The full-duplex contract: the barge monitor is live across the WHOLE agent
// turn — generation (thinking) and playback (speaking) — so speaking over the
// model interrupts it mid-generation instead of the mic being deaf until TTS
// starts (the Windows report: interruption "never works" because the deaf
// window covered generation, and playback bleed made the old monitor's
// trigger unreachable).

const monitorCalls: BargeMonitorCallbacks[] = []
const stopMonitor = vi.fn()

vi.mock('@/lib/voice-barge-in', () => ({
  monitorSpeechDuringPlayback: (callbacks: BargeMonitorCallbacks) => {
    monitorCalls.push(callbacks)

    return stopMonitor
  }
}))

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)

vi.mock('@/lib/voice-playback', () => ({
  markVoicePlaybackInterrupted: () => markVoicePlaybackInterrupted(),
  playSpeechText: (...args: unknown[]) => playSpeechTextMock(...(args as [])),
  startSpeechStream: (...args: unknown[]) => startSpeechStreamMock(...(args as [])),
  stopVoicePlayback: () => stopVoicePlayback(),
  takeVoicePlaybackInterrupted: () => takeVoicePlaybackInterrupted()
}))

vi.mock('@/lib/thinking-sound', () => ({
  startThinkingSound: vi.fn(),
  stopThinkingSound: vi.fn()
}))

const micHandle = {
  cancel: vi.fn(),
  start: vi.fn(async () => undefined),
  stop: vi.fn<() => Promise<MicRecording | null>>(async () => null)
}

vi.mock('./use-mic-recorder', () => ({
  useMicRecorder: () => ({ handle: micHandle, level: 0, recording: false })
}))

vi.mock('@/i18n', () => ({
  useI18n: () => ({
    t: {
      notifications: {
        voice: {
          configureSpeechToText: 'configure STT',
          couldNotStartSession: 'could not start',
          microphoneFailed: 'mic failed',
          playbackFailed: 'playback failed',
          transcriptionFailed: 'transcription failed',
          unavailable: 'unavailable'
        }
      }
    }
  })
}))

vi.mock('@/store/notifications', () => ({
  notify: vi.fn(),
  notifyError: vi.fn()
}))

interface HookProps {
  busy: boolean
}

function renderConversation(
  overrides: {
    onInterrupt?: () => void
    pendingResponse?: () => { id: string; pending: boolean; text: string } | null
    transcript?: string
  } = {}
) {
  const onInterrupt = overrides.onInterrupt ?? vi.fn()

  // Mirrors the real app: submitting a turn makes the agent busy.
  const onBusyChange: { current: (busy: boolean) => void } = { current: () => undefined }

  const onSubmit = vi.fn(async () => {
    onBusyChange.current(true)
  })

  const onStopWord = vi.fn()

  // First transcription is the turn that starts the conversation; subsequent
  // ones are barge captures (the overridable transcript).
  let transcriptions = 0

  const onTranscribeAudio = vi.fn(async () =>
    transcriptions++ === 0 ? 'kick off the task' : (overrides.transcript ?? 'and another thing')
  )

  const pendingResponse = overrides.pendingResponse ?? (() => null)
  const reply = { id: 'reply-1', pending: false, text: 'Here is the answer.' }

  const hook = renderHook(
    ({ busy }: HookProps) =>
      useVoiceConversation({
        busy,
        consumePendingResponse: vi.fn(),
        enabled: true,
        onInterrupt,
        onStopWord,
        onSubmit,
        onTranscribeAudio,
        pendingResponse
      }),
    { initialProps: { busy: false } }
  )

  onBusyChange.current = busy => hook.rerender({ busy })

  return { hook, onInterrupt, onBusyChange, onStopWord, onSubmit, onTranscribeAudio, reply }
}

/** Drive the hook into the generation phase (turn submitted, model working). */
async function enterThinking(hook: ReturnType<typeof renderConversation>['hook']) {
  await act(async () => {
    await hook.result.current.start()
  })
  await waitFor(() => expect(hook.result.current.status).toBe('listening'))

  micHandle.stop.mockResolvedValueOnce({
    audio: new Blob(['q'], { type: 'audio/webm' }),
    durationMs: 900,
    heardSpeech: true
  })

  await act(async () => {
    hook.result.current.stopTurn()
  })
  await waitFor(() => expect(hook.result.current.status).toBe('thinking'))
}

describe('useVoiceConversation full-duplex barge-in', () => {
  beforeEach(() => {
    monitorCalls.length = 0
    vi.clearAllMocks()
    micHandle.start.mockResolvedValue(undefined)
    micHandle.stop.mockResolvedValue(null)
  })

  afterEach(cleanup)

  it('arms the barge monitor during generation (before any reply audio exists)', async () => {
    const { hook } = renderConversation()

    await act(async () => {
      await hook.result.current.start()
    })
    await enterThinking(hook)

    await waitFor(() => expect(hook.result.current.status).toBe('thinking'))
    // busy=true + thinking → the full-duplex monitor must be live.
    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()

    await act(async () => {
      await hook.result.current.start()
    })
    await enterThinking(hook)
    await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0))

    act(() => {
      monitorCalls.at(-1)?.onSpeech()
    })

    expect(onInterrupt).toHaveBeenCalledTimes(1)
    expect(markVoicePlaybackInterrupted).toHaveBeenCalled()
    expect(stopVoicePlayback).toHaveBeenCalled()
  })

  it('submits the captured interruption once the interrupt settles (busy clears)', async () => {
    const { hook, onSubmit } = renderConversation({ transcript: 'no, do it differently' })

    await act(async () => {
      await hook.result.current.start()
    })
    await enterThinking(hook)
    await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0))

    const monitor = monitorCalls.at(-1)

    act(() => {
      monitor?.onSpeech()
    })

    // Interrupt lands → the turn ends → busy flips false.
    hook.rerender({ busy: false })

    await act(async () => {
      monitor?.onUtterance?.(new Blob(['x'], { type: 'audio/webm' }))
    })

    await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('no, do it differently'))
  })

  it('does not interrupt when speech trips during playback (turn already done)', async () => {
    const { hook, onInterrupt } = renderConversation()

    await act(async () => {
      await hook.result.current.start()
    })
    await enterThinking(hook)
    await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0))

    // Turn finished; playback phase.
    hook.rerender({ busy: false })

    act(() => {
      monitorCalls.at(-1)?.onSpeech()
    })

    expect(onInterrupt).not.toHaveBeenCalled()
    expect(stopVoicePlayback).toHaveBeenCalled()
  })

  it('a spoken stop command in the barge capture ends the conversation instead of submitting', async () => {
    const { hook, onStopWord, onSubmit } = renderConversation({ transcript: 'stop' })

    await act(async () => {
      await hook.result.current.start()
    })
    await enterThinking(hook)
    await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0))

    const monitor = monitorCalls.at(-1)

    act(() => {
      monitor?.onSpeech()
    })
    hook.rerender({ busy: false })

    await act(async () => {
      monitor?.onUtterance?.(new Blob(['s'], { type: 'audio/webm' }))
    })

    await waitFor(() => expect(onStopWord).toHaveBeenCalledTimes(1))
    // Only the kickoff turn was submitted — the "stop" capture never was.
    expect(onSubmit).toHaveBeenCalledTimes(1)
    expect(onSubmit).not.toHaveBeenCalledWith('stop')
  })

  it('re-arms a single monitor per turn (idempotent ensure)', async () => {
    const { hook } = renderConversation()

    await act(async () => {
      await hook.result.current.start()
    })
    await enterThinking(hook)
    await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0))

    const armed = monitorCalls.length

    // Effect re-runs (busy toggles, status changes) must not open more mics.
    hook.rerender({ busy: true })
    hook.rerender({ busy: true })

    expect(monitorCalls.length).toBe(armed)
  })

  it('disarms the live monitor when voice.barge_in flips off mid-turn (#126708)', async () => {
    const { hook } = renderConversation()

    try {
      await act(async () => {
        await hook.result.current.start()
      })
      await enterThinking(hook)
      await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0))
      expect(stopMonitor).not.toHaveBeenCalled()

      // The config refresh lands mid-turn: barge-in off must stop the LIVE
      // monitor, not just gate future ones.
      act(() => {
        $bargeInEnabled.set(false)
      })

      await waitFor(() => expect(stopMonitor).toHaveBeenCalledTimes(1))
    } finally {
      act(() => {
        $bargeInEnabled.set(true)
      })
    }
  })
})

// #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
// reply stays text on screen — no TTS stream or sentence playback is started
// for it, and the loop re-arms the mic for the next turn.
describe('useVoiceConversation honors the read-aloud toggle (#44263)', () => {
  let replyReady: boolean

  beforeEach(() => {
    replyReady = false
    vi.clearAllMocks()
    micHandle.start.mockResolvedValue(undefined)
    micHandle.stop.mockResolvedValue(null)
  })

  afterEach(() => {
    $autoSpeakReplies.set(false)
    cleanup()
  })

  const driveOneTurn = async () => {
    const { hook, onSubmit, onBusyChange, reply } = renderConversation({
      pendingResponse: () => (replyReady ? reply : null)
    })

    await act(async () => {
      await hook.result.current.start()
    })
    await enterThinking(hook)

    // The reply lands (still busy), then the turn completes — the order the
    // real app produces: streaming reply text arrives before busy clears.
    replyReady = true
    onBusyChange.current(false)

    await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))

    return { hook }
  }

  it('does not start TTS for the reply when read-aloud is off', async () => {
    $autoSpeakReplies.set(false)

    await driveOneTurn()

    // The loop settles back into listening (mic re-armed for the next turn)
    // without ever opening TTS for the reply.
    await waitFor(() => expect(monitorCalls.length).toBeGreaterThanOrEqual(0))

    expect(startSpeechStreamMock).not.toHaveBeenCalled()
    expect(playSpeechTextMock).not.toHaveBeenCalled()
  })

  it('opens the live speech stream when read-aloud is on', async () => {
    $autoSpeakReplies.set(true)

    await driveOneTurn()

    await waitFor(() => expect(startSpeechStreamMock).toHaveBeenCalled())

    // The mocked stream session resolves null, so the loop falls back to
    // per-sentence playback — that too is TTS for the reply.
    await waitFor(() => expect(playSpeechTextMock).toHaveBeenCalled())
  })
})

// #123357 Part 1 — when a barge capture genuinely cannot submit (live busy
// never clears within the settle window), the transcript must still reach the
// composer instead of vanishing: it is parked in the input so the user sees
// and can send it, and the loop goes back to listening.
describe('useVoiceConversation parks an undeliverable barge transcript (#123357)', () => {
  const parkText = vi.fn()
  const focusInput = vi.fn()

  beforeEach(() => {
    monitorCalls.length = 0
    vi.clearAllMocks()
    micHandle.start.mockResolvedValue(undefined)
    micHandle.stop.mockResolvedValue(null)
  })

  afterEach(cleanup)

  it('parks the transcript in the composer when live busy never clears', async () => {
    vi.useFakeTimers({ shouldAdvanceTime: true })
    parkText.mockClear()
    focusInput.mockClear()

    const submitted: string[] = []
    const transcriptions: string[] = ['kick off the task', 'what about the other approach']

    const hook = renderHook(
      ({ busy }: HookProps) =>
        useVoiceConversation({
          busy,
          consumePendingResponse: vi.fn(),
          enabled: true,
          focusInput,
          onSubmit: async text => {
            submitted.push(text)
            // Mirrors the real wiring: a submitted turn makes the agent busy
            // (renderConversation's onBusyChange), so the drive effect arms
            // the full-duplex monitor for the generation phase.
            hook.rerender({ busy: true })
          },
          onTranscribeAudio: async () => transcriptions.shift() ?? '',
          parkText,
          pendingResponse: () => null
        }),
      { initialProps: { busy: false } }
    )

    await act(async () => {
      await hook.result.current.start()
    })
    await waitFor(() => expect(hook.result.current.status).toBe('listening'))

    micHandle.stop.mockResolvedValueOnce({
      audio: new Blob(['q'], { type: 'audio/webm' }),
      durationMs: 900,
      heardSpeech: true
    })
    await act(async () => {
      hook.result.current.stopTurn()
    })
    expect(submitted).toEqual(['kick off the task'])

    // The turn stays busy the whole time; the monitor is armed mid-generation
    // by the drive effect above (busy=true while status is 'thinking').
    await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0))

    const monitor = monitorCalls.at(-1)

    act(() => {
      monitor?.onSpeech()
    })

    // The interrupt never settles: busy stays true through the whole window.
    await act(async () => {
      await vi.advanceTimersByTimeAsync(6_000)
    })
    await act(async () => {
      await monitor?.onUtterance?.(new Blob(['barge'], { type: 'audio/webm' }))
    })
    await act(async () => {
      await vi.advanceTimersByTimeAsync(6_000)
    })

    expect(parkText).toHaveBeenCalledTimes(1)
    expect(parkText).toHaveBeenCalledWith('what about the other approach')
    expect(focusInput).toHaveBeenCalled()
    expect(submitted).toEqual(['kick off the task'])

    vi.useRealTimers()
  })
})