feat: add CI/CD, code quality, testing and security hardening
CI / quality (push) Failing after 6m22s

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>
This commit is contained in:
william
2026-10-29 09:05:21 +01:00
co-authored by Claude Sonnet 5
parent 1959ddb41a
commit e9690a49f9
230 changed files with 22781 additions and 448 deletions
+170
View File
@@ -0,0 +1,170 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, act, fireEvent, waitFor } from '@testing-library/react'
import type { VoiceState } from '../../../src/renderer/src/voice/useVoiceAssistant'
vi.mock('../../../src/renderer/src/components/AvatarViewer', () => ({
default: ({ onReady }: { onReady: (handle: unknown) => void }) => {
onReady({ playAnimation: vi.fn(), playAnimationByName: vi.fn(), animationNames: [] })
return <div data-testid="avatar-viewer" />
}
}))
let capturedOnStateChange: ((state: VoiceState) => void) | undefined
let capturedOnError: ((message: string) => void) | undefined
const useVoiceAssistant = vi.fn(
(
_ref: unknown,
_enabled: boolean,
onStateChange?: (state: VoiceState) => void,
onError?: (message: string) => void
) => {
capturedOnStateChange = onStateChange
capturedOnError = onError
}
)
vi.mock('../../../src/renderer/src/voice/useVoiceAssistant', () => ({ useVoiceAssistant }))
vi.mock('../../../src/renderer/src/voice/useProactiveSpeech', () => ({
useProactiveSpeech: vi.fn()
}))
vi.mock('../../../src/renderer/src/voice/useCameraCapture', () => ({ useCameraCapture: vi.fn() }))
vi.mock('../../../src/renderer/src/voice/useMeetingRecorder', () => ({
useMeetingRecorder: vi.fn()
}))
let onCourseBuildStepCb: ((state: unknown) => void) | undefined
let onUpdateAvailableCb: (() => void) | undefined
let onUpdateReadyCb: (() => void) | undefined
const sendDroppedFiles = vi.fn()
const getPathForFile = vi.fn(() => 'C:\\fichier.txt')
const showContextMenu = vi.fn()
const getWindowBounds = vi.fn(async () => ({ x: 0, y: 0, width: 100, height: 100 }))
const setWindowPosition = vi.fn()
function setupWindowApi(): void {
;(window as unknown as { api: Record<string, unknown> }).api = {
onCourseBuildStep: vi.fn((cb: (s: unknown) => void) => {
onCourseBuildStepCb = cb
return () => {}
}),
onUpdateAvailable: vi.fn((cb: () => void) => {
onUpdateAvailableCb = cb
return () => {}
}),
onUpdateReady: vi.fn((cb: () => void) => {
onUpdateReadyCb = cb
return () => {}
}),
onToggleListening: vi.fn(() => () => {}),
onToggleMeetingTranscription: vi.fn(() => () => {}),
onProactiveSpeech: vi.fn(() => () => {}),
getPathForFile,
sendDroppedFiles,
showContextMenu,
getWindowBounds,
setWindowPosition
}
}
const { default: App } = await import('../../../src/renderer/src/App')
describe('<App />', () => {
beforeEach(() => {
vi.clearAllMocks()
setupWindowApi()
})
it('should render the avatar viewer', () => {
render(<App />)
expect(screen.getByTestId('avatar-viewer')).toBeInTheDocument()
})
it('should show the thinking indicator while processing', () => {
render(<App />)
act(() => capturedOnStateChange?.('processing'))
expect(screen.getByText('Max reflechit...')).toBeInTheDocument()
})
it('should show a voice error banner and clear it when a new state arrives', () => {
vi.useFakeTimers()
render(<App />)
act(() => capturedOnError?.('Erreur reseau'))
expect(screen.getByText(/Erreur reseau/)).toBeInTheDocument()
act(() => {
vi.advanceTimersByTime(5000)
})
expect(screen.queryByText(/Erreur reseau/)).not.toBeInTheDocument()
vi.useRealTimers()
})
it('should hide the error banner once recording starts again', () => {
render(<App />)
act(() => capturedOnError?.('Erreur reseau'))
expect(screen.getByText(/Erreur reseau/)).toBeInTheDocument()
act(() => capturedOnStateChange?.('recording'))
expect(screen.queryByText(/Erreur reseau/)).not.toBeInTheDocument()
})
it('should display the course build stepper once a state arrives', () => {
render(<App />)
act(() =>
onCourseBuildStepCb?.({
subject: 'algebre',
steps: [{ key: 'recherche', label: 'Recherche', status: 'done' }]
})
)
expect(screen.getByText(/algebre/)).toBeInTheDocument()
})
it('should display the update banner when an update is available, then ready', () => {
render(<App />)
act(() => onUpdateAvailableCb?.())
expect(screen.getByText(/telechargement en cours/)).toBeInTheDocument()
act(() => onUpdateReadyCb?.())
expect(screen.getByText(/prochaine fermeture/)).toBeInTheDocument()
})
it('should forward dropped files to the main process', () => {
render(<App />)
const container = screen.getByTestId('avatar-viewer').parentElement!
fireEvent.drop(container, { dataTransfer: { files: [{ name: 'a.txt' }] } })
expect(getPathForFile).toHaveBeenCalled()
expect(sendDroppedFiles).toHaveBeenCalledWith(['C:\\fichier.txt'])
})
it('should not call sendDroppedFiles when nothing is dropped', () => {
render(<App />)
const container = screen.getByTestId('avatar-viewer').parentElement!
fireEvent.drop(container, { dataTransfer: { files: [] } })
expect(sendDroppedFiles).not.toHaveBeenCalled()
})
it('should request the context menu with the current listening/transcribing state', () => {
render(<App />)
const container = screen.getByTestId('avatar-viewer').parentElement!
fireEvent.contextMenu(container)
expect(showContextMenu).toHaveBeenCalledWith(true, false)
})
it('should start dragging the window on mouse down and stop on mouse up', async () => {
render(<App />)
const container = screen.getByTestId('avatar-viewer').parentElement!
fireEvent.mouseDown(container, { button: 0, screenX: 10, screenY: 10 })
await waitFor(() => expect(getWindowBounds).toHaveBeenCalled())
fireEvent.mouseMove(window, { screenX: 20, screenY: 15 })
expect(setWindowPosition).toHaveBeenCalled()
fireEvent.mouseUp(window)
setWindowPosition.mockClear()
fireEvent.mouseMove(window, { screenX: 50, screenY: 50 })
expect(setWindowPosition).not.toHaveBeenCalled()
})
it('should ignore a non-primary mouse button for dragging', async () => {
render(<App />)
const container = screen.getByTestId('avatar-viewer').parentElement!
fireEvent.mouseDown(container, { button: 2 })
await new Promise((resolve) => setTimeout(resolve, 10))
expect(getWindowBounds).not.toHaveBeenCalled()
})
})
+166
View File
@@ -0,0 +1,166 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, cleanup } from '@testing-library/react'
const disposeGeometry = vi.fn()
const disposeMaterial = vi.fn()
const disposeRenderer = vi.fn()
const sceneAdd = vi.fn()
let loadedMesh: FakeMesh | undefined
class FakeObject3D {
frustumCulled = true
traverse(cb: (obj: unknown) => void): void {
if (loadedMesh) cb(loadedMesh)
}
}
class FakeMesh extends FakeObject3D {
geometry = { dispose: disposeGeometry }
material = { dispose: disposeMaterial }
}
class FakeScene extends FakeObject3D {
add = sceneAdd
}
class FakeCamera {
fov = 30
aspect = 1
position = { set: vi.fn() }
updateProjectionMatrix = vi.fn()
lookAt = vi.fn()
}
class FakeRenderer {
domElement = document.createElement('canvas')
setPixelRatio = vi.fn()
setClearColor = vi.fn()
setSize = vi.fn()
render = vi.fn()
dispose = disposeRenderer
}
class FakeAnimationAction {
reset = vi.fn(() => this)
fadeIn = vi.fn(() => this)
fadeOut = vi.fn(() => this)
play = vi.fn(() => this)
}
class FakeAnimationMixer {
update = vi.fn()
clipAction = vi.fn(() => new FakeAnimationAction())
}
class FakeVector3 {
x = 0
y = 0
z = 0
}
class FakeBox3 {
max = { y: 2 }
min = { y: 0 }
setFromObject = vi.fn(() => this)
getCenter = vi.fn(() => new FakeVector3())
}
class FakeClock {
getDelta = vi.fn(() => 0.016)
}
vi.mock('three', () => ({
Scene: FakeScene,
PerspectiveCamera: FakeCamera,
WebGLRenderer: FakeRenderer,
HemisphereLight: vi.fn(),
DirectionalLight: class {
position = { set: vi.fn() }
},
AnimationMixer: FakeAnimationMixer,
Box3: FakeBox3,
Vector3: FakeVector3,
Clock: FakeClock,
Mesh: FakeMesh
}))
const CLIPS = [
{ name: 'talking' },
{ name: 'bow' },
{ name: 'clap' },
{ name: 'fold_arms' },
{ name: 'idle' }
]
let gltfLoadCallback: ((gltf: unknown) => void) | undefined
let gltfErrorCallback: ((error: unknown) => void) | undefined
const loaderLoad = vi.fn(
(
_file: string,
onLoad: (gltf: unknown) => void,
_onProgress: unknown,
onError: (error: unknown) => void
) => {
gltfLoadCallback = onLoad
gltfErrorCallback = onError
}
)
vi.mock('three/examples/jsm/loaders/GLTFLoader.js', () => ({
GLTFLoader: class {
load = loaderLoad
}
}))
const { default: AvatarViewer } = await import('../../../src/renderer/src/components/AvatarViewer')
describe('<AvatarViewer />', () => {
beforeEach(() => {
vi.clearAllMocks()
loadedMesh = undefined
vi.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 1)
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
})
it('should render a container div', () => {
const { container } = render(<AvatarViewer />)
expect(container.querySelector('div')).toBeInTheDocument()
})
it('should call onReady with a working handle once the model loads', () => {
const onReady = vi.fn()
render(<AvatarViewer onReady={onReady} />)
gltfLoadCallback?.({ scene: new FakeScene(), animations: CLIPS })
expect(onReady).toHaveBeenCalledWith(
expect.objectContaining({ animationNames: ['talking', 'bow', 'clap', 'fold_arms', 'idle'] })
)
})
it('should play an animation by name via the handle given to onReady', () => {
let handle: { playAnimationByName: (name: string) => void } | undefined
render(<AvatarViewer onReady={(h) => (handle = h)} />)
gltfLoadCallback?.({ scene: new FakeScene(), animations: CLIPS })
handle?.playAnimationByName('idle')
// Pas d'assertion sur l'animation interne directement observable depuis l'exterieur, mais
// l'appel ne doit pas lever d'exception et doit couvrir le chemin de recherche par nom.
expect(() => handle?.playAnimationByName('inexistante')).not.toThrow()
})
it('should log an error when the model fails to load', () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
render(<AvatarViewer />)
gltfErrorCallback?.(new Error('404'))
expect(errorSpy).toHaveBeenCalled()
})
it('should dispose geometry, material and renderer resources on unmount', () => {
loadedMesh = new FakeMesh()
render(<AvatarViewer />)
cleanup()
expect(disposeGeometry).toHaveBeenCalled()
expect(disposeMaterial).toHaveBeenCalled()
expect(disposeRenderer).toHaveBeenCalled()
})
})
@@ -0,0 +1,131 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor, act } from '@testing-library/react'
const drawShape = vi.fn()
vi.mock('../../../src/renderer/src/components/drawRoughShapes', () => ({ drawShape }))
const roughCanvas = vi.fn(() => ({}))
vi.mock('roughjs', () => ({ default: { canvas: roughCanvas } }))
const mermaidRender = vi.fn(async () => ({ svg: '<svg></svg>' }))
const mermaidInitialize = vi.fn()
vi.mock('mermaid', () => ({
default: { initialize: mermaidInitialize, render: mermaidRender }
}))
interface InitDrawingPayload {
title: string
width: number
height: number
}
interface RevealShapePayload {
requestId: string
shape: { type: string }
audio: ArrayBuffer | null
}
interface RenderMermaidPayload {
requestId: string
title: string
mermaidCode: string
}
interface PlayCaptionPayload {
requestId: string
audio: ArrayBuffer
}
const listeners: {
onInitDrawing?: (payload: InitDrawingPayload) => void
onRevealShape?: (payload: RevealShapePayload) => void
onRenderMermaid?: (payload: RenderMermaidPayload) => void
onPlayCaption?: (payload: PlayCaptionPayload) => void
} = {}
function setupWindowApi(): void {
;(window as unknown as { api: Record<string, unknown> }).api = {
onInitDrawing: vi.fn((cb: (payload: InitDrawingPayload) => void) => {
listeners.onInitDrawing = cb
return () => {}
}),
onRevealShape: vi.fn((cb: (payload: RevealShapePayload) => void) => {
listeners.onRevealShape = cb
return () => {}
}),
onRenderMermaid: vi.fn((cb: (payload: RenderMermaidPayload) => void) => {
listeners.onRenderMermaid = cb
return () => {}
}),
onPlayCaption: vi.fn((cb: (payload: PlayCaptionPayload) => void) => {
listeners.onPlayCaption = cb
return () => {}
}),
acknowledgeShapeReveal: vi.fn(),
acknowledgeMermaidRendered: vi.fn(),
acknowledgeCaptionDone: vi.fn()
}
}
const { default: CoachDrawingView } =
await import('../../../src/renderer/src/components/CoachDrawingView')
describe('<CoachDrawingView />', () => {
beforeEach(() => {
vi.clearAllMocks()
setupWindowApi()
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(
{} as CanvasRenderingContext2D
)
})
it('should show a waiting message before any drawing is initialized', () => {
render(<CoachDrawingView />)
expect(screen.getByText(/En attente/)).toBeInTheDocument()
})
it('should display the title once a drawing is initialized', () => {
render(<CoachDrawingView />)
act(() => listeners.onInitDrawing?.({ title: 'Mon dessin', width: 700, height: 500 }))
expect(screen.getByText('Mon dessin')).toBeInTheDocument()
})
it('should draw a revealed shape and acknowledge it when there is no audio', () => {
render(<CoachDrawingView />)
act(() => listeners.onInitDrawing?.({ title: 'Mon dessin', width: 700, height: 500 }))
const api = (window as unknown as { api: { acknowledgeShapeReveal: ReturnType<typeof vi.fn> } })
.api
act(() =>
listeners.onRevealShape?.({ requestId: 'r1', shape: { type: 'circle' }, audio: null })
)
expect(drawShape).toHaveBeenCalled()
expect(api.acknowledgeShapeReveal).toHaveBeenCalledWith('r1')
})
it('should switch to mermaid mode and render the diagram on success, waiting for the container to mount', async () => {
render(<CoachDrawingView />)
act(() =>
listeners.onRenderMermaid?.({
requestId: 'r2',
title: 'Cycle de l-eau',
mermaidCode: 'graph LR; A --> B'
})
)
expect(screen.getByText('Cycle de l-eau')).toBeInTheDocument()
const api = (
window as unknown as { api: { acknowledgeMermaidRendered: ReturnType<typeof vi.fn> } }
).api
await waitFor(() => expect(api.acknowledgeMermaidRendered).toHaveBeenCalledWith('r2', true))
})
it('should report a mermaid render failure', async () => {
mermaidRender.mockRejectedValueOnce(new Error('syntaxe invalide'))
render(<CoachDrawingView />)
act(() =>
listeners.onRenderMermaid?.({ requestId: 'r3', title: 'Echec', mermaidCode: 'invalide' })
)
const api = (
window as unknown as { api: { acknowledgeMermaidRendered: ReturnType<typeof vi.fn> } }
).api
await waitFor(() =>
expect(api.acknowledgeMermaidRendered).toHaveBeenCalledWith('r3', false, 'syntaxe invalide')
)
})
})
@@ -0,0 +1,111 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, act } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ExerciseForm } from '../../../src/shared/coach'
let onFormCallback: ((form: ExerciseForm) => void) | undefined
const submitWrittenForm = vi.fn()
function setupWindowApi(): void {
;(window as unknown as { api: Record<string, unknown> }).api = {
onAskWrittenForm: vi.fn((cb: (form: ExerciseForm) => void) => {
onFormCallback = cb
return () => {}
}),
submitWrittenForm
}
}
const { default: CoachExerciseView } =
await import('../../../src/renderer/src/components/CoachExerciseView')
const FORM: ExerciseForm = {
requestId: 'req-1',
items: [
{
id: '0',
question: 'Quelle est la capitale de la France ?',
type: 'free_text',
options: null
},
{ id: '1', question: 'Vrai ou faux : 2+2=4', type: 'true_false', options: null },
{ id: '2', question: 'Choisis la bonne reponse', type: 'multiple_choice', options: ['A', 'B'] }
]
}
describe('<CoachExerciseView />', () => {
beforeEach(() => {
vi.clearAllMocks()
setupWindowApi()
})
it('should show a waiting message before any form is received', () => {
render(<CoachExerciseView />)
expect(screen.getByText(/En attente de questions/)).toBeInTheDocument()
})
it('should display every question once a form is received', () => {
render(<CoachExerciseView />)
act(() => onFormCallback?.(FORM))
expect(screen.getByText(/capitale de la France/)).toBeInTheDocument()
expect(screen.getByText(/2\+2=4/)).toBeInTheDocument()
expect(screen.getByText(/bonne reponse/)).toBeInTheDocument()
})
it('should keep the submit button disabled until every question is answered', async () => {
const user = userEvent.setup()
render(<CoachExerciseView />)
act(() => onFormCallback?.(FORM))
const submitButton = screen.getByText('Soumettre tout le formulaire')
expect(submitButton).toBeDisabled()
await user.type(screen.getByRole('textbox'), 'Paris')
await user.click(screen.getByText('Vrai'))
await user.click(screen.getByText('A'))
expect(submitButton).toBeEnabled()
})
it('should allow answering "Je ne sais pas" to satisfy a question', async () => {
const user = userEvent.setup()
render(<CoachExerciseView />)
act(() => onFormCallback?.({ requestId: 'req-2', items: [FORM.items[0]!] }))
const submitButton = screen.getByText('Soumettre tout le formulaire')
expect(submitButton).toBeDisabled()
await user.click(screen.getByText('Je ne sais pas'))
expect(submitButton).toBeEnabled()
})
it('should submit all answers and show the confirmation message', async () => {
const user = userEvent.setup()
render(<CoachExerciseView />)
act(() => onFormCallback?.(FORM))
await user.type(screen.getByRole('textbox'), 'Paris')
await user.click(screen.getByText('Vrai'))
await user.click(screen.getByText('A'))
await user.click(screen.getByText('Soumettre tout le formulaire'))
expect(submitWrittenForm).toHaveBeenCalledWith('req-1', [
{ id: '0', answer: 'Paris' },
{ id: '1', answer: 'Vrai' },
{ id: '2', answer: 'A' }
])
expect(screen.getByText(/Reponses envoyees a Max/)).toBeInTheDocument()
})
it('should reset state and show a fresh form when a second form arrives', () => {
render(<CoachExerciseView />)
act(() => onFormCallback?.(FORM))
act(() =>
onFormCallback?.({
requestId: 'req-3',
items: [{ id: '0', question: 'Autre question', type: 'free_text', options: null }]
})
)
expect(screen.getByText(/Autre question/)).toBeInTheDocument()
expect(screen.queryByText(/capitale de la France/)).not.toBeInTheDocument()
})
})
@@ -0,0 +1,236 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type {
SubjectProgress,
ModuleDetail,
CourseComplianceReport
} from '../../../src/shared/coach'
const drawShape = vi.fn()
vi.mock('../../../src/renderer/src/components/drawRoughShapes', () => ({ drawShape }))
vi.mock('roughjs', () => ({ default: { canvas: vi.fn(() => ({})) } }))
const mermaidRender = vi.fn(async () => ({ svg: '<svg></svg>' }))
vi.mock('mermaid', () => ({ default: { initialize: vi.fn(), render: mermaidRender } }))
let navigateCallback: ((payload: { subject: string; module: string }) => void) | undefined
const getCoachProgress = vi.fn()
const getModuleDetail = vi.fn()
const getCourseCompliance = vi.fn(async (): Promise<CourseComplianceReport | null> => null)
const requestModuleEvaluation = vi.fn()
function setupWindowApi(): void {
;(window as unknown as { api: Record<string, unknown> }).api = {
getCoachProgress,
getModuleDetail,
getCourseCompliance,
requestModuleEvaluation,
onNavigateToModule: vi.fn((cb: (payload: { subject: string; module: string }) => void) => {
navigateCallback = cb
return () => {}
})
}
}
const { default: CoachProgressView } =
await import('../../../src/renderer/src/components/CoachProgressView')
const SUBJECT: SubjectProgress = {
subject: 'algebre',
level: 'debutant',
status: 'in_progress',
objective: 'Tu seras capable de resoudre une equation',
lastSessionAt: new Date().toISOString(),
concepts: [
{
name: 'Module A',
status: 'acquired',
lastReviewedAt: new Date().toISOString(),
nextReviewAt: null,
locked: false,
orderIndex: 0
},
{
name: 'Module B',
status: 'not_started',
lastReviewedAt: new Date().toISOString(),
nextReviewAt: null,
locked: true,
orderIndex: 1
}
]
}
const MODULE_DETAIL: ModuleDetail = {
name: 'Module A',
status: 'acquired',
locked: false,
theorySummary: 'Contenu du module.',
assessments: [
{
question: 'Question 1 ?',
answer: 'Reponse',
dontKnow: false,
difficulty: 'facile',
exerciseStyle: 'prediction',
targetsCommonError: null,
createdAt: new Date().toISOString()
}
],
diagrams: []
}
describe('<CoachProgressView />', () => {
beforeEach(() => {
vi.clearAllMocks()
setupWindowApi()
getCoachProgress.mockResolvedValue([SUBJECT])
getModuleDetail.mockResolvedValue(MODULE_DETAIL)
getCourseCompliance.mockResolvedValue(null)
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
clearRect: vi.fn()
} as unknown as CanvasRenderingContext2D)
})
it('should show a loading state before subjects arrive', () => {
getCoachProgress.mockReturnValue(new Promise(() => {}))
render(<CoachProgressView />)
expect(screen.getByText('Chargement...')).toBeInTheDocument()
})
it('should list the loaded subjects', async () => {
render(<CoachProgressView />)
expect(await screen.findByText('algebre')).toBeInTheDocument()
})
it('should show an empty state when there are no subjects yet', async () => {
getCoachProgress.mockResolvedValue([])
render(<CoachProgressView />)
expect(await screen.findByText(/Aucun sujet d.apprentissage/)).toBeInTheDocument()
})
it('should navigate to the modules view and list each module', async () => {
const user = userEvent.setup()
render(<CoachProgressView />)
await user.click(await screen.findByText('algebre'))
expect(screen.getByText('Module A')).toBeInTheDocument()
expect(screen.getByText('Module B')).toBeInTheDocument()
expect(screen.getByText(/Niveau : debutant/)).toBeInTheDocument()
expect(screen.getByText(/resoudre une equation/)).toBeInTheDocument()
})
it('should disable a locked module button', async () => {
const user = userEvent.setup()
render(<CoachProgressView />)
await user.click(await screen.findByText('algebre'))
expect(screen.getByText('Module B').closest('button')).toBeDisabled()
})
it('should show the compliance checklist once loaded', async () => {
getCourseCompliance.mockResolvedValue({
subject: 'algebre',
checks: [
{ key: 'sources', label: 'Recherche sourcee', ok: true, detail: 'ok' },
{ key: 'objective', label: 'Objectif mesurable', ok: false, detail: 'manquant' }
]
})
const user = userEvent.setup()
render(<CoachProgressView />)
await user.click(await screen.findByText('algebre'))
await waitFor(() => expect(screen.getByText(/1\/2/)).toBeInTheDocument())
})
it('should navigate to a module detail view and show its content', async () => {
const user = userEvent.setup()
render(<CoachProgressView />)
await user.click(await screen.findByText('algebre'))
await user.click(screen.getByText('Module A'))
expect(await screen.findByText('Contenu du module.')).toBeInTheDocument()
expect(screen.getByText('Question 1 ?')).toBeInTheDocument()
})
it('should show the "evaluer ce module" button for an unlocked, unacquired module', async () => {
getModuleDetail.mockResolvedValue({ ...MODULE_DETAIL, status: 'in_progress' })
const user = userEvent.setup()
render(<CoachProgressView />)
await user.click(await screen.findByText('algebre'))
await user.click(screen.getByText('Module A'))
const evalButton = await screen.findByText('Evaluer ce module')
await user.click(evalButton)
expect(requestModuleEvaluation).toHaveBeenCalledWith('algebre', 'Module A')
})
it('should not show the evaluation button once the module is acquired', async () => {
const user = userEvent.setup()
render(<CoachProgressView />)
await user.click(await screen.findByText('algebre'))
await user.click(screen.getByText('Module A'))
await screen.findByText('Contenu du module.')
expect(screen.queryByText('Evaluer ce module')).not.toBeInTheDocument()
})
it('should navigate directly to a module detail view on an incoming navigate-to-module event', async () => {
render(<CoachProgressView />)
await waitFor(() => expect(navigateCallback).toBeDefined())
navigateCallback?.({ subject: 'algebre', module: 'Module A' })
expect(await screen.findByText('Contenu du module.')).toBeInTheDocument()
})
it('should render a shapes diagram for a module', async () => {
getModuleDetail.mockResolvedValue({
...MODULE_DETAIL,
diagrams: [
{
kind: 'shapes',
title: 'Mon schema',
data: { title: 'Mon schema', width: 400, height: 300, shapes: [] },
createdAt: new Date().toISOString()
}
]
})
const user = userEvent.setup()
render(<CoachProgressView />)
await user.click(await screen.findByText('algebre'))
await user.click(screen.getByText('Module A'))
expect(await screen.findByText('Mon schema')).toBeInTheDocument()
})
it('should render a mermaid diagram for a module', async () => {
getModuleDetail.mockResolvedValue({
...MODULE_DETAIL,
diagrams: [
{
kind: 'mermaid',
title: 'Mon diagramme',
data: { mermaidCode: 'graph LR; A --> B' },
createdAt: new Date().toISOString()
}
]
})
const user = userEvent.setup()
render(<CoachProgressView />)
await user.click(await screen.findByText('algebre'))
await user.click(screen.getByText('Module A'))
expect(await screen.findByText('Mon diagramme')).toBeInTheDocument()
await waitFor(() => expect(mermaidRender).toHaveBeenCalled())
})
it('should go back from the module view to the modules list', async () => {
const user = userEvent.setup()
render(<CoachProgressView />)
await user.click(await screen.findByText('algebre'))
await user.click(screen.getByText('Module A'))
await screen.findByText('Contenu du module.')
await user.click(screen.getByText(/Retour aux modules/))
expect(screen.getByText('Module A')).toBeInTheDocument()
expect(screen.getByText('Module B')).toBeInTheDocument()
})
it('should go back from the modules view to the subjects list', async () => {
const user = userEvent.setup()
render(<CoachProgressView />)
await user.click(await screen.findByText('algebre'))
await user.click(screen.getByText(/Retour aux sujets/))
expect(await screen.findByText('algebre')).toBeInTheDocument()
})
})
@@ -0,0 +1,32 @@
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import CourseBuildStepper from '../../../src/renderer/src/components/CourseBuildStepper'
import type { CourseBuildState } from '../../../src/shared/courseBuild'
const STATE: CourseBuildState = {
subject: 'algebre',
steps: [
{ key: 'recherche', label: 'Recherche approfondie', status: 'done', detail: '5 source(s)' },
{ key: 'plan', label: 'Objectif et plan de modules', status: 'active' },
{ key: 'redaction', label: 'Redaction des modules', status: 'pending' }
]
}
describe('<CourseBuildStepper />', () => {
it('should display the subject name', () => {
render(<CourseBuildStepper state={STATE} />)
expect(screen.getByText(/algebre/)).toBeInTheDocument()
})
it('should display every step label', () => {
render(<CourseBuildStepper state={STATE} />)
expect(screen.getByText('Recherche approfondie')).toBeInTheDocument()
expect(screen.getByText('Objectif et plan de modules')).toBeInTheDocument()
expect(screen.getByText('Redaction des modules')).toBeInTheDocument()
})
it('should display the detail text only for steps that have one', () => {
render(<CourseBuildStepper state={STATE} />)
expect(screen.getByText('5 source(s)')).toBeInTheDocument()
})
})
@@ -0,0 +1,10 @@
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import ThinkingIndicator from '../../../src/renderer/src/components/ThinkingIndicator'
describe('<ThinkingIndicator />', () => {
it('should display the "Max reflechit..." message', () => {
render(<ThinkingIndicator />)
expect(screen.getByText('Max reflechit...')).toBeInTheDocument()
})
})
@@ -0,0 +1,15 @@
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import UpdateBanner from '../../../src/renderer/src/components/UpdateBanner'
describe('<UpdateBanner />', () => {
it('should show a downloading message when status is "available"', () => {
render(<UpdateBanner status="available" />)
expect(screen.getByText(/telechargement en cours/)).toBeInTheDocument()
})
it('should show an install-on-restart message when status is "ready"', () => {
render(<UpdateBanner status="ready" />)
expect(screen.getByText(/prochaine fermeture/)).toBeInTheDocument()
})
})
@@ -0,0 +1,15 @@
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import VoiceErrorBanner from '../../../src/renderer/src/components/VoiceErrorBanner'
describe('<VoiceErrorBanner />', () => {
it('should display the given error message', () => {
render(<VoiceErrorBanner message="ElevenLabs injoignable" />)
expect(screen.getByText(/ElevenLabs injoignable/)).toBeInTheDocument()
})
it('should prefix the message with "Erreur"', () => {
render(<VoiceErrorBanner message="Reseau indisponible" />)
expect(screen.getByText(/^Erreur :/)).toBeInTheDocument()
})
})
@@ -0,0 +1,174 @@
import { describe, it, expect, vi } from 'vitest'
import {
boxesOverlap,
findFreeLabelPosition,
drawArrowHead,
drawShape,
type LabelBox
} from '../../../src/renderer/src/components/drawRoughShapes'
import type { RoughCanvas } from 'roughjs/bin/canvas'
function fakeCtx(): {
ctx: CanvasRenderingContext2D
fillText: ReturnType<typeof vi.fn>
beginPath: ReturnType<typeof vi.fn>
fill: ReturnType<typeof vi.fn>
} {
const fillText = vi.fn()
const beginPath = vi.fn()
const fill = vi.fn()
const ctx = {
measureText: vi.fn(() => ({ width: 40 })),
save: vi.fn(),
restore: vi.fn(),
beginPath,
moveTo: vi.fn(),
lineTo: vi.fn(),
closePath: vi.fn(),
fill,
fillText,
fillStyle: '',
font: ''
} as unknown as CanvasRenderingContext2D
return { ctx, fillText, beginPath, fill }
}
function fakeRoughCanvas(): {
rc: RoughCanvas
rectangle: ReturnType<typeof vi.fn>
circle: ReturnType<typeof vi.fn>
line: ReturnType<typeof vi.fn>
curve: ReturnType<typeof vi.fn>
arc: ReturnType<typeof vi.fn>
} {
const rectangle = vi.fn()
const circle = vi.fn()
const line = vi.fn()
const curve = vi.fn()
const arc = vi.fn()
const rc = { rectangle, circle, line, curve, arc } as unknown as RoughCanvas
return { rc, rectangle, circle, line, curve, arc }
}
describe('boxesOverlap()', () => {
it('should detect overlapping boxes', () => {
const a: LabelBox = { x: 0, y: 0, width: 10, height: 10 }
const b: LabelBox = { x: 5, y: 5, width: 10, height: 10 }
expect(boxesOverlap(a, b)).toBe(true)
})
it('should detect non-overlapping boxes', () => {
const a: LabelBox = { x: 0, y: 0, width: 10, height: 10 }
const b: LabelBox = { x: 100, y: 100, width: 10, height: 10 }
expect(boxesOverlap(a, b)).toBe(false)
})
})
describe('findFreeLabelPosition()', () => {
it('should return the starting position when nothing is placed yet', () => {
const { ctx } = fakeCtx()
const box = findFreeLabelPosition(ctx, 'Label', 10, 30, [])
expect(box).toEqual({ x: 10, y: 14, width: 40, height: 16 })
})
it('should shift downward to avoid an already-placed overlapping box', () => {
const { ctx } = fakeCtx()
const placed: LabelBox[] = [{ x: 10, y: 14, width: 40, height: 16 }]
const box = findFreeLabelPosition(ctx, 'Label', 10, 30, placed)
expect(box.y).toBeGreaterThan(14)
})
it('should fall back to the last attempted position after 20 attempts if always overlapping', () => {
const { ctx } = fakeCtx()
const placed: LabelBox[] = Array.from({ length: 25 }, (_, i) => ({
x: 10,
y: 14 + i * 16,
width: 40,
height: 16
}))
const box = findFreeLabelPosition(ctx, 'Label', 10, 30, placed)
expect(box).toBeDefined()
})
})
describe('drawArrowHead()', () => {
it('should draw a filled triangle at the arrow tip', () => {
const { ctx, beginPath, fill } = fakeCtx()
drawArrowHead(ctx, 0, 0, 10, 10, '#000')
expect(beginPath).toHaveBeenCalled()
expect(fill).toHaveBeenCalled()
})
})
describe('drawShape()', () => {
it('should draw a rectangle', () => {
const { rc, rectangle } = fakeRoughCanvas()
const { ctx } = fakeCtx()
drawShape(rc, ctx, { type: 'rect', x: 1, y: 2, width: 10, height: 20 }, [])
expect(rectangle).toHaveBeenCalledWith(1, 2, 10, 20, expect.anything())
})
it('should draw a circle', () => {
const { rc, circle } = fakeRoughCanvas()
const { ctx } = fakeCtx()
drawShape(rc, ctx, { type: 'circle', x: 1, y: 2, radius: 5 }, [])
expect(circle).toHaveBeenCalledWith(1, 2, 10, expect.anything())
})
it('should draw a line and position its label at the segment midpoint', () => {
const { rc, line } = fakeRoughCanvas()
const { ctx, fillText } = fakeCtx()
drawShape(rc, ctx, { type: 'line', x: 0, y: 0, x2: 10, y2: 0, label: 'AB' }, [])
expect(line).toHaveBeenCalledWith(0, 0, 10, 0, expect.anything())
expect(fillText).toHaveBeenCalled()
})
it('should draw an arrow with an arrowhead', () => {
const { rc, line } = fakeRoughCanvas()
const { ctx, fill } = fakeCtx()
drawShape(rc, ctx, { type: 'arrow', x: 0, y: 0, x2: 10, y2: 10 }, [])
expect(line).toHaveBeenCalled()
expect(fill).toHaveBeenCalled()
})
it('should draw a stroke curve only when at least 2 points are given', () => {
const { rc, curve } = fakeRoughCanvas()
const { ctx } = fakeCtx()
drawShape(
rc,
ctx,
{
type: 'stroke',
points: [
{ x: 0, y: 0 },
{ x: 1, y: 1 }
]
},
[]
)
expect(curve).toHaveBeenCalled()
})
it('should not draw a stroke with fewer than 2 points', () => {
const { rc, curve } = fakeRoughCanvas()
const { ctx } = fakeCtx()
drawShape(rc, ctx, { type: 'stroke', points: [{ x: 0, y: 0 }] }, [])
expect(curve).not.toHaveBeenCalled()
})
it('should draw an arc', () => {
const { rc, arc } = fakeRoughCanvas()
const { ctx } = fakeCtx()
drawShape(rc, ctx, { type: 'arc', x: 0, y: 0, radius: 10, startAngle: 0, endAngle: 90 }, [])
expect(arc).toHaveBeenCalled()
})
it('should draw text content directly and record its label box', () => {
const { rc } = fakeRoughCanvas()
const { ctx, fillText } = fakeCtx()
const placed: LabelBox[] = []
drawShape(rc, ctx, { type: 'text', x: 0, y: 0, content: 'Bonjour' }, placed)
expect(fillText).toHaveBeenCalledWith('Bonjour', 0, 0)
expect(placed.length).toBe(1)
})
})
+86
View File
@@ -0,0 +1,86 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
let nextPlayShouldReject = false
class FakeAudio {
onended: (() => void) | null = null
onerror: (() => void) | null = null
play = vi.fn(async () => {
if (nextPlayShouldReject) {
nextPlayShouldReject = false
throw new Error('autoplay blocked')
}
})
}
let lastAudio: FakeAudio | null = null
function createAudio(): FakeAudio {
const audio = new FakeAudio()
lastAudio = audio
return audio
}
vi.stubGlobal('Audio', vi.fn(createAudio))
URL.createObjectURL = vi.fn(() => 'blob:fake')
URL.revokeObjectURL = vi.fn()
const { enqueueSpeech, bindSpeechAvatar, setRestingAnimation } =
await import('../../../src/renderer/src/voice/speechQueue')
describe('speechQueue', () => {
beforeEach(() => {
vi.clearAllMocks()
lastAudio = null
})
it('should play the avatar talking animation while audio plays, then return to the resting animation', async () => {
const playAnimationByName = vi.fn()
bindSpeechAvatar({
current: { playAnimationByName, animationNames: [], playAnimation: vi.fn() }
})
setRestingAnimation('idle')
const promise = enqueueSpeech(new ArrayBuffer(4))
expect(playAnimationByName).toHaveBeenCalledWith('talking')
lastAudio?.onended?.()
await promise
expect(playAnimationByName).toHaveBeenCalledWith('idle')
})
it('should play queued items sequentially, one at a time', async () => {
const playAnimationByName = vi.fn()
bindSpeechAvatar({
current: { playAnimationByName, animationNames: [], playAnimation: vi.fn() }
})
const first = enqueueSpeech(new ArrayBuffer(4))
const firstAudio = lastAudio
const second = enqueueSpeech(new ArrayBuffer(4))
// Le second ne doit pas encore avoir cree son propre element audio : il attend son tour.
expect(lastAudio).toBe(firstAudio)
firstAudio?.onended?.()
await first
lastAudio?.onended?.()
await second
})
it('should resolve and continue the queue when playback errors out', async () => {
const promise = enqueueSpeech(new ArrayBuffer(4))
lastAudio?.onerror?.()
await expect(promise).resolves.toBeUndefined()
})
it('should resolve and continue the queue when play() itself rejects', async () => {
nextPlayShouldReject = true
const promise = enqueueSpeech(new ArrayBuffer(4))
await expect(promise).resolves.toBeUndefined()
})
it('should work gracefully when no avatar has been bound yet', async () => {
bindSpeechAvatar({ current: null })
const promise = enqueueSpeech(new ArrayBuffer(4))
lastAudio?.onended?.()
await expect(promise).resolves.toBeUndefined()
})
})
@@ -0,0 +1,51 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook } from '@testing-library/react'
let onCaptureCallback: ((requestId: string) => void) | undefined
const sendCameraFrameResult = vi.fn()
const onCaptureCameraFrame = vi.fn((cb: (requestId: string) => void) => {
onCaptureCallback = cb
return () => {}
})
const stopTrack = vi.fn()
const getUserMedia = vi.fn(async () => ({
getTracks: () => [{ stop: stopTrack }]
}))
const { useCameraCapture } = await import('../../../src/renderer/src/voice/useCameraCapture')
describe('useCameraCapture()', () => {
beforeEach(() => {
vi.clearAllMocks()
;(window as unknown as { api: Record<string, unknown> }).api = {
onCaptureCameraFrame,
sendCameraFrameResult
}
Object.defineProperty(navigator, 'mediaDevices', {
value: { getUserMedia },
configurable: true
})
vi.spyOn(HTMLMediaElement.prototype, 'play').mockResolvedValue()
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
drawImage: vi.fn()
} as unknown as CanvasRenderingContext2D)
HTMLCanvasElement.prototype.toDataURL = vi.fn(() => 'data:image/png;base64,abc')
})
it('should capture a frame and send it back on request', async () => {
renderHook(() => useCameraCapture())
onCaptureCallback?.('req-1')
await vi.waitFor(() => expect(sendCameraFrameResult).toHaveBeenCalled())
expect(sendCameraFrameResult).toHaveBeenCalledWith('req-1', 'data:image/png;base64,abc')
expect(stopTrack).toHaveBeenCalled()
})
it('should send null when the camera is unavailable', async () => {
getUserMedia.mockRejectedValueOnce(new Error('no camera'))
renderHook(() => useCameraCapture())
onCaptureCallback?.('req-2')
await vi.waitFor(() => expect(sendCameraFrameResult).toHaveBeenCalled())
expect(sendCameraFrameResult).toHaveBeenCalledWith('req-2', null)
})
})
@@ -0,0 +1,96 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook } from '@testing-library/react'
let onToggleCallback: ((transcribing: boolean) => void) | undefined
const sendMeetingAudioChunk = vi.fn()
const sendMeetingRecordingStopped = vi.fn()
const onToggleMeetingTranscription = vi.fn((cb: (transcribing: boolean) => void) => {
onToggleCallback = cb
return () => {}
})
function fakeStream(): MediaStream {
const stop = vi.fn()
return { getTracks: () => [{ stop }] } as unknown as MediaStream
}
const getUserMedia = vi.fn(async () => fakeStream())
const enumerateDevices = vi.fn(async () => [])
class FakeMediaRecorder {
static instances: FakeMediaRecorder[] = []
state: 'recording' | 'inactive' = 'recording'
ondataavailable: ((event: { data: Blob }) => void) | null = null
onstop: (() => void) | null = null
constructor(
public stream: MediaStream,
public options: { mimeType: string }
) {
FakeMediaRecorder.instances.push(this)
}
start(): void {
this.state = 'recording'
}
stop(): void {
this.state = 'inactive'
this.ondataavailable?.({ data: new Blob(['chunk'], { type: 'audio/webm' }) })
this.onstop?.()
}
}
const { useMeetingRecorder } = await import('../../../src/renderer/src/voice/useMeetingRecorder')
describe('useMeetingRecorder()', () => {
beforeEach(() => {
vi.clearAllMocks()
FakeMediaRecorder.instances = []
;(window as unknown as { api: Record<string, unknown> }).api = {
onToggleMeetingTranscription,
sendMeetingAudioChunk,
sendMeetingRecordingStopped
}
Object.defineProperty(navigator, 'mediaDevices', {
value: { getUserMedia, enumerateDevices },
configurable: true
})
vi.stubGlobal('MediaRecorder', FakeMediaRecorder)
})
it('should start recording the microphone when transcription is toggled on', async () => {
renderHook(() => useMeetingRecorder())
onToggleCallback?.(true)
await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(1))
expect(getUserMedia).toHaveBeenCalledWith({ audio: true })
})
it('should give up quietly when the microphone is unavailable, without ever starting a recorder', async () => {
getUserMedia.mockRejectedValueOnce(new Error('no mic'))
renderHook(() => useMeetingRecorder())
onToggleCallback?.(true)
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
// Rien n'a jamais demarre : stopper ensuite ne doit ni planter ni envoyer de notification pour
// une session qui n'a jamais existe.
expect(() => onToggleCallback?.(false)).not.toThrow()
expect(FakeMediaRecorder.instances.length).toBe(0)
})
it('should send the recorded chunk and notify the main process when stopped', async () => {
renderHook(() => useMeetingRecorder())
onToggleCallback?.(true)
await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(1))
onToggleCallback?.(false)
await vi.waitFor(() => expect(sendMeetingAudioChunk).toHaveBeenCalled())
expect(sendMeetingRecordingStopped).toHaveBeenCalled()
})
it('should start a new segment automatically instead of stopping when not asked to stop', async () => {
renderHook(() => useMeetingRecorder())
onToggleCallback?.(true)
await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(1))
FakeMediaRecorder.instances[0]?.stop()
await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(2))
expect(sendMeetingRecordingStopped).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,34 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook } from '@testing-library/react'
const bindSpeechAvatar = vi.fn()
const enqueueSpeech = vi.fn(async () => {})
vi.mock('../../../src/renderer/src/voice/speechQueue', () => ({ bindSpeechAvatar, enqueueSpeech }))
let onProactiveSpeechCallback: ((audio: ArrayBuffer) => void) | undefined
const onProactiveSpeech = vi.fn((cb: (audio: ArrayBuffer) => void) => {
onProactiveSpeechCallback = cb
return () => {}
})
const { useProactiveSpeech } = await import('../../../src/renderer/src/voice/useProactiveSpeech')
describe('useProactiveSpeech()', () => {
beforeEach(() => {
vi.clearAllMocks()
;(window as unknown as { api: Record<string, unknown> }).api = { onProactiveSpeech }
})
it('should bind the avatar ref to the shared speech queue', () => {
const avatarRef = { current: null }
renderHook(() => useProactiveSpeech(avatarRef))
expect(bindSpeechAvatar).toHaveBeenCalledWith(avatarRef)
})
it('should enqueue any audio received via onProactiveSpeech', () => {
renderHook(() => useProactiveSpeech({ current: null }))
const audio = new ArrayBuffer(4)
onProactiveSpeechCallback?.(audio)
expect(enqueueSpeech).toHaveBeenCalledWith(audio)
})
})
@@ -0,0 +1,224 @@
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())
})
})