Step 1 of adding a backend proxy server (API keys held server-side instead of shipped in the installer). Moves everything app-specific into "Max Avatar/" via git mv (preserves history): src/, tests/, scripts/, assets/, build/, resources/, package.json/-lock.json, electron-builder.yml, electron.vite.config.ts, eslint.config.mjs, playwright.config.ts, vitest.config.mts, sonar-project.properties, tsconfig*.json, Dockerfile, .editorconfig/.env*/.gitignore/.prettier*. CLAUDE.md, README.md, docs/, .claude/, .gitea/, .husky/, .vscode/, and the docker-compose files stay at the repo root, since they'll apply to both the app and the future backend. No application code needed changes (all its internal paths are relative to its own tree). Adjusted what referenced the old root from outside: - .husky/pre-commit: cd into "Max Avatar" before lint-staged - .gitea/workflows/*.yml: working-directory + cache-dependency-path + artifact paths + SonarQube projectBaseDir - docker-compose.yml: build context -> ./Max Avatar - Max Avatar/Dockerfile: node:20-alpine -> node:24-alpine (same node:sqlite issue already fixed elsewhere, never applied here before) - .vscode/launch.json, README.md: updated paths/instructions Verified from Max Avatar/ after the move: npm ci, typecheck, lint, test:coverage (473/473, same coverage numbers), build, and dev all work unchanged. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
225 lines
7.7 KiB
TypeScript
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())
|
|
})
|
|
})
|