Files
ForgeBase/tests/unit/components/useVoiceAssistant.test.ts
T
williamandClaude Sonnet 5 e9690a49f9
CI / quality (push) Failing after 6m22s
feat: add CI/CD, code quality, testing and security hardening
Implements Max_Code_Quality_CICD_Production.md: TypeScript strict mode,
ESLint flat config with type-checking and security plugin, Prettier,
Husky + lint-staged, Vitest with 80%+ coverage (473 tests), Playwright
e2e, Electron security hardening (contextIsolation, CSP, IPC validation),
electron-builder + electron-updater, Dockerfile, Gitea Actions CI/release
workflows, and SonarQube docker-compose setup. Also fixes two real bugs
found while writing tests: unawaited clipboard promises and a mermaid
container ref timing issue in CoachDrawingView.

Fixes lint-staged on Windows/Node 24 by invoking eslint/prettier via
`node <bin>.js` instead of their .cmd shims, which Node's child_process
now refuses to spawn without shell:true.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 09:05:21 +01:00

225 lines
7.7 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook } from '@testing-library/react'
import type { VoiceTurnResult } from '../../../src/shared/voice'
const bindSpeechAvatar = vi.fn()
const enqueueSpeech = vi.fn(async () => {})
const setRestingAnimation = vi.fn()
vi.mock('../../../src/renderer/src/voice/speechQueue', () => ({
bindSpeechAvatar,
enqueueSpeech,
setRestingAnimation
}))
let rafCallback: ((time: number) => void) | undefined
function tick(): void {
const cb = rafCallback
rafCallback = undefined
cb?.(performance.now())
}
let loudness: 'loud' | 'quiet' = 'quiet'
class FakeAnalyser {
fftSize = 1024
getByteTimeDomainData(array: Uint8Array): void {
array.fill(loudness === 'loud' ? 255 : 128)
}
}
class FakeAudioContext {
close = vi.fn(async () => {})
createMediaStreamSource = vi.fn(() => ({ connect: vi.fn() }))
createAnalyser = vi.fn(() => new FakeAnalyser())
}
function fakeStream(): MediaStream {
const stop = vi.fn()
const endedListeners: (() => void)[] = []
return {
getTracks: () => [{ stop }],
getAudioTracks: () => [
{
addEventListener: (_event: string, cb: () => void) => endedListeners.push(cb),
fireEnded: () => endedListeners.forEach((cb) => cb())
}
]
} as unknown as MediaStream
}
const getUserMedia = vi.fn(async () => fakeStream())
const deviceChangeListeners: (() => void)[] = []
class FakeMediaRecorder {
static instances: FakeMediaRecorder[] = []
state: 'recording' | 'inactive' = 'recording'
ondataavailable: ((event: { data: Blob }) => void) | null = null
onstop: (() => void) | null = null
constructor(public stream: MediaStream) {
FakeMediaRecorder.instances.push(this)
}
start(): void {
this.state = 'recording'
}
stop(): void {
this.state = 'inactive'
this.ondataavailable?.({ data: new Blob([new Uint8Array(2000)], { type: 'audio/webm' }) })
this.onstop?.()
}
}
const sendVoiceTurn = vi.fn(async (): Promise<VoiceTurnResult> => ({
ok: true,
transcript: 'bonjour',
reply: 'salut',
audio: new ArrayBuffer(4)
}))
const { useVoiceAssistant } = await import('../../../src/renderer/src/voice/useVoiceAssistant')
describe('useVoiceAssistant()', () => {
beforeEach(() => {
vi.clearAllMocks()
rafCallback = undefined
loudness = 'quiet'
deviceChangeListeners.length = 0
FakeMediaRecorder.instances = []
sendVoiceTurn.mockResolvedValue({
ok: true,
transcript: 'bonjour',
reply: 'salut',
audio: new ArrayBuffer(4)
})
;(window as unknown as { api: Record<string, unknown> }).api = { sendVoiceTurn }
vi.stubGlobal('AudioContext', FakeAudioContext)
vi.stubGlobal('MediaRecorder', FakeMediaRecorder)
vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => {
rafCallback = cb
return 1
})
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
Object.defineProperty(navigator, 'mediaDevices', {
value: {
getUserMedia,
addEventListener: vi.fn((_event: string, cb: () => void) => {
deviceChangeListeners.push(cb)
}),
removeEventListener: vi.fn()
},
configurable: true
})
})
it('should immediately report idle and skip microphone access when disabled', () => {
const onStateChange = vi.fn()
renderHook(() => useVoiceAssistant({ current: null }, false, onStateChange))
expect(onStateChange).toHaveBeenCalledWith('idle')
expect(getUserMedia).not.toHaveBeenCalled()
})
it('should request the microphone and bind the avatar when enabled', async () => {
renderHook(() => useVoiceAssistant({ current: null }, true))
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
await vi.waitFor(() => expect(bindSpeechAvatar).toHaveBeenCalled())
})
it('should log and not throw when the microphone is unavailable', async () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
getUserMedia.mockRejectedValueOnce(new Error('no mic'))
renderHook(() => useVoiceAssistant({ current: null }, true))
await vi.waitFor(() => expect(errorSpy).toHaveBeenCalled())
})
it('should start recording once the audio level crosses the speech threshold', async () => {
const onStateChange = vi.fn()
renderHook(() => useVoiceAssistant({ current: null }, true, onStateChange))
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
loudness = 'loud'
tick()
expect(onStateChange).toHaveBeenCalledWith('recording')
expect(FakeMediaRecorder.instances.length).toBe(1)
})
it('should discard a too-short utterance without sending it to the main process', async () => {
const onStateChange = vi.fn()
renderHook(() => useVoiceAssistant({ current: null }, true, onStateChange))
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
loudness = 'loud'
tick()
// Arrete immediatement : duree ecoulee bien en dessous de MIN_SPEECH_MS.
FakeMediaRecorder.instances[0]?.stop()
await vi.waitFor(() => expect(onStateChange).toHaveBeenCalledWith('idle'))
expect(sendVoiceTurn).not.toHaveBeenCalled()
})
it('should send a long-enough utterance and play back a successful reply', async () => {
const onStateChange = vi.fn()
renderHook(() => useVoiceAssistant({ current: null }, true, onStateChange))
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
loudness = 'loud'
tick()
await new Promise((resolve) => setTimeout(resolve, 310))
FakeMediaRecorder.instances[0]?.stop()
await vi.waitFor(() => expect(sendVoiceTurn).toHaveBeenCalled())
await vi.waitFor(() => expect(enqueueSpeech).toHaveBeenCalled())
expect(onStateChange).toHaveBeenCalledWith('speaking')
})
it('should return to idle without error reporting when the turn is ignored (no wake word)', async () => {
sendVoiceTurn.mockResolvedValue({ ok: 'ignored', transcript: '' })
const onStateChange = vi.fn()
const onError = vi.fn()
renderHook(() => useVoiceAssistant({ current: null }, true, onStateChange, onError))
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
loudness = 'loud'
tick()
await new Promise((resolve) => setTimeout(resolve, 310))
FakeMediaRecorder.instances[0]?.stop()
await vi.waitFor(() => expect(sendVoiceTurn).toHaveBeenCalled())
expect(onError).not.toHaveBeenCalled()
})
it('should report an error and return to idle when the turn fails', async () => {
sendVoiceTurn.mockResolvedValue({ ok: false, error: 'API indisponible' })
const onError = vi.fn()
renderHook(() => useVoiceAssistant({ current: null }, true, undefined, onError))
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
loudness = 'loud'
tick()
await new Promise((resolve) => setTimeout(resolve, 310))
FakeMediaRecorder.instances[0]?.stop()
await vi.waitFor(() => expect(onError).toHaveBeenCalledWith('API indisponible'))
})
it('should stop tracks and close the audio context on unmount', async () => {
const cancelAnimationFrame = vi
.spyOn(window, 'cancelAnimationFrame')
.mockImplementation(() => {})
const { unmount } = renderHook(() => useVoiceAssistant({ current: null }, true))
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
unmount()
expect(cancelAnimationFrame).toHaveBeenCalled()
})
it('should restart the microphone when the audio device list changes', async () => {
renderHook(() => useVoiceAssistant({ current: null }, true))
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
getUserMedia.mockClear()
vi.useFakeTimers()
deviceChangeListeners[0]?.()
await vi.advanceTimersByTimeAsync(500)
vi.useRealTimers()
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
})
})