chore(cleanup): remove old SQLite coach pipeline

The entire local-SQLite Coach teaching pipeline (objective/level/plan/module
agents, course-build stepper, written-exercise and drawing windows, review
scheduler, screen/camera vision capture for blockage detection, and their
renderer views) is retired: it will be replaced by a brand new 7-agent
pipeline living server-side in Max API/Postgres, built in a later step.

Removes src/main/coach/, the coach and vision skill definitions, the coach
renderer views and CourseBuildStepper, drawRoughShapes, useCameraCapture,
the camera-frame IPC bridge, and the shared coach/courseBuild/drawing
types. Strips the corresponding pipeline guard-rails, system-prompt
instructions and IPC handlers from openrouter.ts/index.ts/preload. Drops
the now-unused mermaid/roughjs dependencies.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
william
2026-10-31 19:22:46 +01:00
parent 9aa5abc121
commit 2363dc8164
80 changed files with 24 additions and 8753 deletions
@@ -1,62 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { EventEmitter } from 'node:events'
import { join } from 'node:path'
const writeFileSyncMock = vi.fn()
const readdirSyncMock = vi.fn(() => ['old.png', 'new.png'])
const statSyncMock = vi.fn((path: string) => ({
mtimeMs: path.includes('old') ? 0 : Date.now()
}))
const unlinkSyncMock = vi.fn()
vi.mock('fs', () => ({
writeFileSync: writeFileSyncMock,
readdirSync: readdirSyncMock,
statSync: statSyncMock,
unlinkSync: unlinkSyncMock
}))
const parentPort = new EventEmitter() as EventEmitter & { postMessage: (msg: unknown) => void }
parentPort.postMessage = vi.fn()
vi.mock('node:worker_threads', () => ({ parentPort }))
await import('../../src/main/coach/captureWorker')
describe('captureWorker (worker_thread message handler)', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('should write the given PNG buffer to disk and acknowledge success', () => {
const png = Buffer.from([1, 2, 3])
parentPort.emit('message', { filePath: 'C:\\captures\\shot.png', png })
expect(writeFileSyncMock).toHaveBeenCalledWith('C:\\captures\\shot.png', png)
expect(parentPort.postMessage).toHaveBeenCalledWith({
ok: true,
filePath: 'C:\\captures\\shot.png'
})
})
it('should report failure when writing fails', () => {
writeFileSyncMock.mockImplementationOnce(() => {
throw new Error('disk full')
})
parentPort.emit('message', { filePath: 'C:\\captures\\shot.png', png: Buffer.from([1]) })
expect(parentPort.postMessage).toHaveBeenCalledWith({ ok: false, error: 'disk full' })
})
it('should delete only files older than the cutoff when purging', () => {
const purgeDir = 'C:\\captures'
parentPort.emit('message', { purgeDir, cutoff: 1000 })
expect(unlinkSyncMock).toHaveBeenCalledTimes(1)
expect(unlinkSyncMock).toHaveBeenCalledWith(join(purgeDir, 'old.png'))
expect(parentPort.postMessage).toHaveBeenCalledWith({ ok: true })
})
it('should report failure when purging fails', () => {
readdirSyncMock.mockImplementationOnce(() => {
throw new Error('dir gone')
})
parentPort.emit('message', { purgeDir: 'C:\\captures', cutoff: 1000 })
expect(parentPort.postMessage).toHaveBeenCalledWith({ ok: false, error: 'dir gone' })
})
})
-194
View File
@@ -1,194 +0,0 @@
import { describe, it, expect, vi, beforeAll } from 'vitest'
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-coach-test-'))
vi.mock('electron', () => ({
app: { getPath: () => tempDir }
}))
// Importe apres le mock : getDb() lit app.getPath('userData') au premier appel et cree le fichier
// sqlite dans un dossier temporaire dedie a ce fichier de test (jamais la vraie base utilisateur).
const {
setSubjectObjective,
getSubjectObjective,
setSubjectLevel,
getSubjectLevel,
createModules,
listModules,
allModulesHaveContent,
modulesMissingContent,
setModuleTheory,
canWriteModuleContent,
saveAssessment,
hasAssessment,
hasMultipleDifficulties,
moduleDontKnowRatio,
upsertConceptStatus,
getProgress,
getCourseComplianceReport,
getResearchSummary
} = await import('../../src/main/coach/coachStore')
const VALID_CONTENT = [
'Accroche',
'Un vendeur doit calculer rapidement combien de tissu acheter pour un mur triangulaire. '.repeat(
16
),
'Developpement theorique',
'Idee centrale, analogie, definition formelle, exemple resolu et contre-exemple. '.repeat(35),
'Phase guidee',
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier.',
'Exercices progressifs',
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
'Exercice de debogage',
"Trouve l'erreur dans ce calcul errone et corrige-la.",
'Synthese',
'Resume final avec question de meta-cognition et test Feynman. '.repeat(15)
].join('\n\n')
describe('coachStore — objective', () => {
it('should return null for a subject objective that was never set', () => {
expect(getSubjectObjective('sujet-sans-objectif')).toBeNull()
})
it('should return null when the subject exists but its objective/research were never set', () => {
createModules('sujet-existant-sans-objectif', [{ name: 'Module unique' }])
expect(getSubjectObjective('sujet-existant-sans-objectif')).toBeNull()
expect(getResearchSummary('sujet-existant-sans-objectif')).toBeNull()
})
it('should persist and retrieve a subject objective', () => {
setSubjectObjective(
'algebre-test',
'Tu seras capable de resoudre une equation du premier degre'
)
expect(getSubjectObjective('algebre-test')).toBe(
'Tu seras capable de resoudre une equation du premier degre'
)
})
})
describe('coachStore — modules et verrouillage sequentiel', () => {
const subject = 'fractions-test'
it('should create modules with only the first one unlocked', () => {
createModules(subject, [{ name: 'Module A' }, { name: 'Module B' }])
const modules = listModules(subject)
expect(modules.map((m) => m.name)).toEqual(['Module A', 'Module B'])
expect(modules[0]?.locked).toBe(false)
expect(modules[1]?.locked).toBe(true)
})
it('should report missing content for every module before any is written', () => {
expect(allModulesHaveContent(subject)).toBe(false)
expect(modulesMissingContent(subject)).toEqual(['Module A', 'Module B'])
})
it('should allow writing module content before a subject level is recorded', () => {
expect(canWriteModuleContent(subject, 'Module A')).toEqual({ ok: true, blockedBy: null })
expect(canWriteModuleContent(subject, 'Module B')).toEqual({ ok: true, blockedBy: null })
})
it('should accept well-structured content and reflect it as no-longer-missing', () => {
expect(setModuleTheory(subject, 'Module A', VALID_CONTENT)).toBe(true)
expect(modulesMissingContent(subject)).toEqual(['Module B'])
})
it('should block writing a later module once a subject level is recorded and an earlier module is unfinished', () => {
setSubjectLevel(subject, 'debutant')
expect(getSubjectLevel(subject)).toBe('debutant')
const result = canWriteModuleContent(subject, 'Module B')
expect(result.ok).toBe(false)
expect(result.blockedBy).toBe('Module A')
})
})
describe("coachStore — evaluations et validation d'un module", () => {
const subject = 'geometrie-test'
const module = 'Module unique'
beforeAll(() => {
createModules(subject, [{ name: module }])
})
it('should report no assessment and a 100% "dont know" ratio before any is saved', () => {
expect(hasAssessment(subject, module, 'module')).toBe(false)
expect(moduleDontKnowRatio(subject, module)).toBe(1)
expect(hasMultipleDifficulties(subject, module)).toBe(false)
})
it('should track multiple distinct difficulties and a correct dont-know ratio after saving assessments', () => {
saveAssessment(
subject,
module,
'Question facile',
'short_answer',
null,
'reponse',
'module',
false,
'facile',
'prediction',
null
)
saveAssessment(
subject,
module,
'Question moyenne',
'short_answer',
null,
'je ne sais pas',
'module',
true,
'moyen',
'debogage',
'erreur de signe'
)
expect(hasAssessment(subject, module, 'module')).toBe(true)
expect(hasMultipleDifficulties(subject, module)).toBe(true)
expect(moduleDontKnowRatio(subject, module)).toBeCloseTo(0.5)
})
it('should default to false/1 (blocking) for a subject that does not exist at all', () => {
expect(hasMultipleDifficulties('sujet-totalement-inconnu', module)).toBe(false)
expect(moduleDontKnowRatio('sujet-totalement-inconnu', module)).toBe(1)
})
it('should persist multiple-choice options as JSON on the assessment', () => {
saveAssessment(
subject,
module,
'QCM',
'multiple_choice',
['A', 'B', 'C'],
'A',
'module',
false,
'difficile',
'qcm_cible',
null
)
expect(hasAssessment(subject, module, 'module')).toBe(true)
})
})
describe('coachStore — progression et conformite', () => {
it('should return an empty list when no subject exists yet', () => {
expect(getProgress('sujet-totalement-inconnu')).toEqual([])
})
it('should return null compliance for an unknown subject', () => {
expect(getCourseComplianceReport('sujet-totalement-inconnu')).toBeNull()
})
it('should include the source-documentation check in the compliance report for a known subject', () => {
upsertConceptStatus('conformite-test', 'Un concept', 'not_started')
const report = getCourseComplianceReport('conformite-test')
expect(report).not.toBeNull()
expect(report?.checks.some((c) => c.key === 'sources')).toBe(true)
})
})
@@ -1,88 +0,0 @@
import { describe, it, expect } from 'vitest'
import { validateModuleContent, missingContentSections } from '../../src/main/coach/coachStore'
function buildValidContent(): string {
return [
'Accroche',
'Un vendeur doit calculer rapidement combien de tissu acheter pour couvrir un mur triangulaire. '.repeat(
16
),
'Developpement theorique',
'Idee centrale, analogie, definition formelle, exemple resolu et contre-exemple. '.repeat(35),
'Phase guidee',
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier le resultat.',
'Exercices progressifs',
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
'Exercice de debogage',
"Trouve l'erreur dans ce calcul errone et corrige-la.",
'Synthese',
'Resume final avec question de meta-cognition et test Feynman. '.repeat(15)
].join('\n\n')
}
describe('missingContentSections()', () => {
it('should return every required section when content is empty', () => {
const missing = missingContentSections('')
expect(missing).toContain('Accroche')
expect(missing).toContain('Synthese')
expect(missing.length).toBe(6)
})
it('should return no missing section when all section headers are present', () => {
expect(missingContentSections(buildValidContent())).toEqual([])
})
})
describe('validateModuleContent()', () => {
it('should accept well-structured content meeting all requirements', () => {
expect(validateModuleContent(buildValidContent())).toEqual([])
})
it('should reject content with missing sections', () => {
const violations = validateModuleContent('Accroche\nTrop court.')
expect(violations.length).toBeGreaterThan(0)
expect(violations[0]).toMatch(/Sections manquantes/)
})
it('should accept accented "ETAPE"/"EXERCICE" headers (regression: accent-insensitive match)', () => {
const content = buildValidContent().replace('ETAPE', 'ÉTAPE').replace('EXERCICE', 'ÉXERCICE')
expect(validateModuleContent(content)).toEqual([])
})
it('should reject a "Phase guidee" section with fewer than 3 numbered steps', () => {
const content = buildValidContent().replace(
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier le resultat.',
'ETAPE 1 : identifier les donnees.'
)
const violations = validateModuleContent(content)
expect(violations.some((v) => /Phase guidee/.test(v))).toBe(true)
})
it('should reject an "Exercices progressifs" section with fewer than 6 numbered exercises', () => {
const content = buildValidContent().replace(
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
'EXERCICE 1 facile. EXERCICE 2 moyen.'
)
const violations = validateModuleContent(content)
expect(violations.some((v) => /Exercices progressifs/.test(v))).toBe(true)
})
it('should reject an "Exercice de debogage" section that never mentions an error', () => {
const content = buildValidContent().replace(
"Trouve l'erreur dans ce calcul errone et corrige-la.",
'Resous ce calcul.'
)
const violations = validateModuleContent(content)
expect(violations.some((v) => /debogage/.test(v))).toBe(true)
})
it('should reject a section shorter than its required minimum word count', () => {
const shortAccroche =
'Un vendeur doit calculer rapidement combien de tissu acheter pour couvrir un mur triangulaire. '.repeat(
16
)
const content = buildValidContent().replace(shortAccroche, 'Phrase courte.')
const violations = validateModuleContent(content)
expect(violations.some((v) => /Accroche.*trop courte/.test(v))).toBe(true)
})
})
@@ -26,12 +26,10 @@ vi.mock('../../../src/renderer/src/voice/useVoiceAssistant', () => ({ useVoiceAs
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()
@@ -46,10 +44,6 @@ const getAuthStatus = vi.fn(async (): Promise<{ loggedIn: boolean; email: string
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 () => {}
@@ -109,17 +103,6 @@ describe('<App />', () => {
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?.())
@@ -1,131 +0,0 @@
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')
)
})
})
@@ -1,111 +0,0 @@
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()
})
})
@@ -1,236 +0,0 @@
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()
})
})
@@ -1,32 +0,0 @@
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()
})
})
@@ -1,174 +0,0 @@
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)
})
})
@@ -1,51 +0,0 @@
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)
})
})
@@ -1,108 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const sendToRenderer = vi.fn()
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer }))
const { recordCourseBuildTool, clearCourseBuild } =
await import('../../src/main/coach/courseBuildStepper')
interface Payload {
subject: string
steps: { key: string; status: string; detail?: string }[]
}
function lastPayload(): Payload {
const call = sendToRenderer.mock.calls.at(-1) as [string, Payload] | undefined
if (!call) throw new Error('sendToRenderer was never called')
return call[1]
}
describe('courseBuildStepper', () => {
beforeEach(() => {
sendToRenderer.mockClear()
})
it('should ignore a tool call with no subject', () => {
recordCourseBuildTool('research_topic', {})
expect(sendToRenderer).not.toHaveBeenCalled()
})
it('should ignore an unrecognized tool name', () => {
recordCourseBuildTool('unknown_tool', { subject: 'algebre' })
expect(sendToRenderer).not.toHaveBeenCalled()
})
it('should mark recherche done and plan active after research_topic, with source count', () => {
recordCourseBuildTool('research_topic', { subject: 'algebre', sources: [{}, {}, {}] })
const payload = lastPayload()
expect(payload.subject).toBe('algebre')
const recherche = payload.steps.find((s) => s.key === 'recherche')
const plan = payload.steps.find((s) => s.key === 'plan')
expect(recherche?.status).toBe('done')
expect(recherche?.detail).toBe('3 source(s)')
expect(plan?.status).toBe('active')
})
it('should mark plan done and redaction active after generate_course_plan with modules', () => {
recordCourseBuildTool('generate_course_plan', {
subject: 'algebre',
modules: [{ name: 'A' }, { name: 'B' }]
})
const payload = lastPayload()
const plan = payload.steps.find((s) => s.key === 'plan')
const redaction = payload.steps.find((s) => s.key === 'redaction')
expect(plan?.status).toBe('done')
expect(redaction?.status).toBe('active')
expect(redaction?.detail).toBe('0/2')
})
it('should mark redaction done and evaluation_initiale active once every module is written', () => {
recordCourseBuildTool('write_module_content', { subject: 'algebre' })
let payload = lastPayload()
expect(payload.steps.find((s) => s.key === 'redaction')?.detail).toBe('1/2')
expect(payload.steps.find((s) => s.key === 'redaction')?.status).toBe('active')
recordCourseBuildTool('write_module_content', { subject: 'algebre' })
payload = lastPayload()
expect(payload.steps.find((s) => s.key === 'redaction')?.status).toBe('done')
expect(payload.steps.find((s) => s.key === 'evaluation_initiale')?.status).toBe('active')
})
it('should mark evaluation_initiale done and niveau active on an initial assessment', () => {
recordCourseBuildTool('ask_written_exercise', { subject: 'algebre', kind: 'initial' })
const payload = lastPayload()
expect(payload.steps.find((s) => s.key === 'evaluation_initiale')?.status).toBe('done')
expect(payload.steps.find((s) => s.key === 'niveau')?.status).toBe('active')
})
it('should not progress the "niveau" step on a non-initial assessment', () => {
recordCourseBuildTool('ask_written_exercise', { subject: 'algebre', kind: 'module' })
const payload = lastPayload()
expect(payload.steps.find((s) => s.key === 'niveau')?.status).toBe('active')
})
it('should mark niveau done after record_subject_level', () => {
recordCourseBuildTool('record_subject_level', { subject: 'algebre' })
const payload = lastPayload()
expect(payload.steps.find((s) => s.key === 'niveau')?.status).toBe('done')
})
it('should mark revision done on a second generate_course_plan call after the level is recorded', () => {
recordCourseBuildTool('generate_course_plan', { subject: 'algebre', modules: [{ name: 'A' }] })
const payload = lastPayload()
expect(payload.steps.find((s) => s.key === 'revision')?.status).toBe('done')
})
it('should reset the stepper state when a different subject starts', () => {
recordCourseBuildTool('research_topic', { subject: 'geometrie', sources: [] })
const payload = lastPayload()
expect(payload.subject).toBe('geometrie')
expect(payload.steps.find((s) => s.key === 'niveau')?.status).toBe('pending')
})
it('should clear the stepper state and notify the renderer with null', () => {
sendToRenderer.mockClear()
clearCourseBuild()
expect(sendToRenderer).toHaveBeenCalledWith('course-build-step', null)
})
})
-155
View File
@@ -1,155 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { EventEmitter } from 'node:events'
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
class FakeWebContents extends EventEmitter {
send = vi.fn()
isLoading = vi.fn(() => false)
}
class FakeBrowserWindow extends EventEmitter {
webContents = new FakeWebContents()
show = vi.fn()
moveTop = vi.fn()
focus = vi.fn()
setAlwaysOnTop = vi.fn()
maximize = vi.fn()
loadURL = vi.fn()
loadFile = vi.fn()
destroyed = false
isDestroyed(): boolean {
return this.destroyed
}
}
let lastWindow: FakeBrowserWindow | null = null
const ipcMainListeners = new Map<string, Set<(...args: unknown[]) => void>>()
const ipcMain = {
on: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
if (!ipcMainListeners.has(event)) ipcMainListeners.set(event, new Set())
ipcMainListeners.get(event)?.add(handler)
}),
removeListener: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
ipcMainListeners.get(event)?.delete(handler)
})
}
function fireIpc(event: string, ...args: unknown[]): void {
for (const handler of ipcMainListeners.get(event) ?? []) handler(...args)
}
function createBrowserWindow(): FakeBrowserWindow {
const window = new FakeBrowserWindow()
lastWindow = window
return window
}
vi.mock('electron', () => ({
BrowserWindow: vi.fn(createBrowserWindow),
ipcMain
}))
const { openDrawingWindow, revealShape, renderMermaid, playCaption } =
await import('../../src/main/coach/drawingWindow')
describe('openDrawingWindow()', () => {
beforeEach(() => {
vi.clearAllMocks()
ipcMainListeners.clear()
})
it('should create the window, load it and send init-drawing once ready', async () => {
await openDrawingWindow('Mon titre', 700, 500)
expect(lastWindow?.show).toHaveBeenCalled()
expect(lastWindow?.webContents.send).toHaveBeenCalledWith('init-drawing', {
title: 'Mon titre',
width: 700,
height: 500
})
})
it('should reuse the existing window on a second call rather than creating a new one', async () => {
await openDrawingWindow('Titre 1', 700, 500)
const firstWindow = lastWindow
await openDrawingWindow('Titre 2', 700, 500)
expect(lastWindow).toBe(firstWindow)
})
})
describe('revealShape()', () => {
beforeEach(async () => {
vi.clearAllMocks()
ipcMainListeners.clear()
await openDrawingWindow('Titre', 700, 500)
})
it('should resolve once the renderer acknowledges the reveal with the matching request id', async () => {
const promise = revealShape({ type: 'circle', x: 1, y: 1 }, null)
const sentPayload = lastWindow?.webContents.send.mock.calls.find(
(c) => c[0] === 'reveal-shape'
)?.[1] as { requestId: string }
fireIpc('shape-reveal-done', {}, sentPayload.requestId)
await expect(promise).resolves.toBeUndefined()
})
it('should resolve immediately when there is no open window', async () => {
lastWindow!.destroyed = true
await expect(revealShape({ type: 'circle', x: 1, y: 1 }, null)).resolves.toBeUndefined()
})
it('should resolve after the timeout even without an acknowledgement', async () => {
vi.useFakeTimers()
const promise = revealShape({ type: 'circle', x: 1, y: 1 }, null, 1000)
await vi.advanceTimersByTimeAsync(1000)
await expect(promise).resolves.toBeUndefined()
vi.useRealTimers()
})
})
describe('renderMermaid()', () => {
beforeEach(async () => {
vi.clearAllMocks()
ipcMainListeners.clear()
await openDrawingWindow('Titre', 700, 500)
})
it('should resolve when the renderer reports a successful render', async () => {
const promise = renderMermaid('Cycle', 'graph LR; A --> B')
await Promise.resolve()
await Promise.resolve()
const sentPayload = lastWindow?.webContents.send.mock.calls.find(
(c) => c[0] === 'render-mermaid'
)?.[1] as { requestId: string }
fireIpc('mermaid-render-done', {}, sentPayload.requestId, true)
await expect(promise).resolves.toBeUndefined()
})
it('should reject with the renderer-provided error on a failed render', async () => {
const promise = renderMermaid('Cycle', 'graph LR; A --> B')
await Promise.resolve()
await Promise.resolve()
const sentPayload = lastWindow?.webContents.send.mock.calls.find(
(c) => c[0] === 'render-mermaid'
)?.[1] as { requestId: string }
fireIpc('mermaid-render-done', {}, sentPayload.requestId, false, 'syntaxe invalide')
await expect(promise).rejects.toThrow('syntaxe invalide')
})
})
describe('playCaption()', () => {
beforeEach(async () => {
vi.clearAllMocks()
ipcMainListeners.clear()
await openDrawingWindow('Titre', 700, 500)
})
it('should resolve once the renderer acknowledges the caption is done', async () => {
const audio = new ArrayBuffer(4)
const promise = playCaption(audio)
const sentPayload = lastWindow?.webContents.send.mock.calls.find(
(c) => c[0] === 'play-caption'
)?.[1] as { requestId: string }
fireIpc('caption-done', {}, sentPayload.requestId)
await expect(promise).resolves.toBeUndefined()
})
})
@@ -1,124 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { EventEmitter } from 'node:events'
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
class FakeWebContents extends EventEmitter {
send = vi.fn()
isLoading = vi.fn(() => false)
}
class FakeBrowserWindow extends EventEmitter {
webContents = new FakeWebContents()
show = vi.fn()
moveTop = vi.fn()
focus = vi.fn()
setAlwaysOnTop = vi.fn()
maximize = vi.fn()
loadURL = vi.fn()
loadFile = vi.fn()
close = vi.fn()
destroyed = false
isDestroyed(): boolean {
return this.destroyed
}
}
let lastWindow: FakeBrowserWindow | null = null
let nextWindowStartsLoading = false
function createBrowserWindow(): FakeBrowserWindow {
const window = new FakeBrowserWindow()
if (nextWindowStartsLoading) {
window.webContents.isLoading.mockReturnValue(true)
nextWindowStartsLoading = false
}
lastWindow = window
return window
}
const ipcMainListeners = new Map<string, Set<(...args: unknown[]) => void>>()
const ipcMain = {
on: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
if (!ipcMainListeners.has(event)) ipcMainListeners.set(event, new Set())
ipcMainListeners.get(event)?.add(handler)
}),
removeListener: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
ipcMainListeners.get(event)?.delete(handler)
})
}
function fireIpc(event: string, ...args: unknown[]): void {
for (const handler of ipcMainListeners.get(event) ?? []) handler(...args)
}
vi.mock('electron', () => ({
BrowserWindow: vi.fn(createBrowserWindow),
ipcMain
}))
const { requestWrittenAnswers } = await import('../../src/main/coach/exerciseWindow')
describe('requestWrittenAnswers()', () => {
beforeEach(() => {
// Reinitialise le singleton interne du module (win = null) en simulant la fermeture de la
// fenetre precedente, pour qu'un nouveau test reparte toujours d'une fenetre fraiche.
lastWindow?.emit('closed')
vi.clearAllMocks()
ipcMainListeners.clear()
lastWindow = null
})
it('should send the question list to the renderer and show the window', async () => {
const promise = requestWrittenAnswers([{ question: 'Q1', type: 'free_text', options: null }])
expect(lastWindow?.show).toHaveBeenCalled()
expect(lastWindow?.webContents.send).toHaveBeenCalledWith(
'ask-written-form',
expect.objectContaining({
items: [{ id: '0', question: 'Q1', type: 'free_text', options: null }]
})
)
const sentPayload = lastWindow?.webContents.send.mock.calls[0]?.[1] as { requestId: string }
fireIpc('written-form-result', {}, sentPayload.requestId, [{ id: '0', answer: 'ma reponse' }])
await expect(promise).resolves.toEqual(['ma reponse'])
})
it('should resolve with nulls for items missing from the submitted answers', async () => {
const promise = requestWrittenAnswers([
{ question: 'Q1', type: 'free_text', options: null },
{ question: 'Q2', type: 'free_text', options: null }
])
const sentPayload = lastWindow?.webContents.send.mock.calls[0]?.[1] as { requestId: string }
fireIpc('written-form-result', {}, sentPayload.requestId, [{ id: '0', answer: 'reponse 1' }])
await expect(promise).resolves.toEqual(['reponse 1', null])
})
it('should ignore a submission for a different request id', () => {
void requestWrittenAnswers([{ question: 'Q1', type: 'free_text', options: null }])
fireIpc('written-form-result', {}, 'un-autre-id', [{ id: '0', answer: 'ignore' }])
expect(lastWindow?.close).not.toHaveBeenCalled()
})
it('should resolve with all nulls when the window is closed before submission', async () => {
const promise = requestWrittenAnswers([{ question: 'Q1', type: 'free_text', options: null }])
lastWindow?.emit('closed')
await expect(promise).resolves.toEqual([null])
})
it('should resolve with all nulls when the timeout elapses with no submission', async () => {
vi.useFakeTimers()
const promise = requestWrittenAnswers(
[{ question: 'Q1', type: 'free_text', options: null }],
1000
)
await vi.advanceTimersByTimeAsync(1000)
await expect(promise).resolves.toEqual([null])
vi.useRealTimers()
})
it('should wait for did-finish-load before sending the form when the page is still loading', () => {
nextWindowStartsLoading = true
void requestWrittenAnswers([{ question: 'Q1', type: 'free_text', options: null }])
expect(lastWindow?.webContents.send).not.toHaveBeenCalled()
lastWindow?.webContents.emit('did-finish-load')
expect(lastWindow?.webContents.send).toHaveBeenCalled()
})
})
-72
View File
@@ -24,16 +24,6 @@ vi.mock('../../src/main/ai/elevenlabs', () => ({ synthesizeSpeech }))
const sendToRenderer = vi.fn()
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer }))
const getSubjectLevel = vi.fn((): string | null => null)
vi.mock('../../src/main/coach/coachStore', () => ({ getSubjectLevel }))
const recordCourseBuildTool = vi.fn()
const clearCourseBuild = vi.fn()
vi.mock('../../src/main/coach/courseBuildStepper', () => ({
recordCourseBuildTool,
clearCourseBuild
}))
const { getAssistantReply } = await import('../../src/main/ai/openrouter')
function okResponse(body: unknown): Response {
@@ -65,7 +55,6 @@ describe('getAssistantReply()', () => {
vi.clearAllMocks()
vi.stubGlobal('fetch', vi.fn())
currentSkills = []
getSubjectLevel.mockReturnValue(null)
process.env.OPENROUTER_API_KEY = 'test-key'
setCurrentUserEmail('test@example.com')
})
@@ -198,64 +187,3 @@ describe('getAssistantReply()', () => {
await expect(getAssistantReply('boucle indefiniment')).rejects.toThrow(/Trop d'appels d'outils/)
}, 20000)
})
describe('getAssistantReply() — garde-fous du pipeline Coach', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubGlobal('fetch', vi.fn())
getSubjectLevel.mockReturnValue(null)
process.env.OPENROUTER_API_KEY = 'test-key'
setCurrentUserEmail('test@example.com')
currentSkills = [
{
name: 'research_topic',
description: '',
parameters: {},
execute: vi.fn(async () => 'Recherche enregistree.')
}
]
})
it('should force a retry toward generate_course_plan when research_topic was called but not the plan', async () => {
const executeGeneratePlan = vi.fn(async () => 'Plan enregistre.')
currentSkills.push({
name: 'generate_course_plan',
description: '',
parameters: {},
execute: executeGeneratePlan
})
// Des que le nudge a ete pousse une fois (verifie par l'appel ci-dessous), on simule que le
// niveau vient d'etre enregistre pour ne pas enchainer sur tous les nudges suivants du pipeline
// (plan -> contenu -> evaluation) : seul le declenchement de CE nudge precis est teste ici.
getSubjectLevel.mockImplementation(() =>
executeGeneratePlan.mock.calls.length > 0 ? 'debutant' : null
)
vi.mocked(fetch)
.mockResolvedValueOnce(okResponse(toolCallMessage('research_topic', { subject: 'algebre' })))
.mockResolvedValueOnce(okResponse(textMessage("J'ai fini pour l'instant.")))
.mockResolvedValueOnce(
okResponse(toolCallMessage('generate_course_plan', { subject: 'algebre' }))
)
.mockResolvedValueOnce(okResponse(textMessage('Plan en cours.')))
const reply = await getAssistantReply('apprends-moi algebre')
expect(executeGeneratePlan).toHaveBeenCalled()
expect(reply).toBe('Plan en cours.')
})
it('should force a retry when the model announces an action at round 0 without calling any tool', async () => {
// "subject" est volontairement omis : on isole ici le garde-fou "annonce au round 0", pas celui
// du pipeline (recherche -> plan), qui se redeclencherait sinon des que trackedSubject est fixe.
vi.mocked(fetch)
.mockResolvedValueOnce(
okResponse(
textMessage("Je vais t'apprendre la trigonometrie ! Commencons par une recherche.")
)
)
.mockResolvedValueOnce(okResponse(toolCallMessage('research_topic', {})))
.mockResolvedValueOnce(okResponse(textMessage('Recherche terminee, module prepare.')))
const reply = await getAssistantReply('apprends-moi la trigonometrie')
expect(reply).toBe('Recherche terminee, module prepare.')
})
})
@@ -1,22 +0,0 @@
import { describe, it, expect } from 'vitest'
import { PRESET_GENERATORS } from '../../src/main/coach/presets'
describe('PRESET_GENERATORS', () => {
it('should register a generator for every documented preset name', () => {
const expectedNames = [
'right_triangle',
'triangle',
'regular_polygon',
'circle_sector',
'venn_diagram',
'coordinate_axes'
]
for (const name of expectedNames) {
expect(PRESET_GENERATORS.get(name)).toBeTypeOf('function')
}
})
it('should return undefined for an unknown preset name', () => {
expect(PRESET_GENERATORS.get('inexistant')).toBeUndefined()
})
})
@@ -1,134 +0,0 @@
import { describe, it, expect } from 'vitest'
import { buildCircleSector } from '../../src/main/coach/presets/circleSector'
import { buildCoordinateAxes } from '../../src/main/coach/presets/coordinateAxes'
import { buildRegularPolygon } from '../../src/main/coach/presets/regularPolygon'
import { buildRightTriangle } from '../../src/main/coach/presets/rightTriangle'
import { buildTriangle } from '../../src/main/coach/presets/triangle'
import { buildVennDiagram } from '../../src/main/coach/presets/vennDiagram'
describe('buildCircleSector()', () => {
it('should return one arc shape per slice, with angles summing to 360 degrees', () => {
const shapes = buildCircleSector({
slices: [
{ value: 50, label: 'A' },
{ value: 50, label: 'B' }
]
})
expect(shapes).toHaveLength(2)
expect(shapes[0]?.startAngle).toBe(-90)
expect(shapes[1]?.endAngle).toBe(270)
})
it('should ignore slices with a zero or negative value', () => {
const shapes = buildCircleSector({ slices: [{ value: 0 }, { value: -5 }, { value: 10 }] })
expect(shapes).toHaveLength(1)
})
it('should return an empty array when there are no valid slices', () => {
expect(buildCircleSector({ slices: [] })).toEqual([])
expect(buildCircleSector({})).toEqual([])
})
})
describe('buildCoordinateAxes()', () => {
it('should always return the two perpendicular axis arrows plus axis labels', () => {
const shapes = buildCoordinateAxes({})
const arrows = shapes.filter((s) => s.type === 'arrow')
expect(arrows).toHaveLength(2)
expect(arrows[0]?.y).toBe(arrows[0]?.y2)
expect(arrows[1]?.x).toBe(arrows[1]?.x2)
})
it('should add a circle for each valid point provided', () => {
const shapes = buildCoordinateAxes({
points: [
{ x: 1, y: 2, label: 'P' },
{ x: 3, y: 4 }
]
})
const circles = shapes.filter((s) => s.type === 'circle')
expect(circles).toHaveLength(2)
expect(circles[0]?.label).toBe('P')
})
it('should ignore non-object entries in the points array', () => {
const shapes = buildCoordinateAxes({ points: [null, 'invalid', { x: 1, y: 1 }] })
expect(shapes.filter((s) => s.type === 'circle')).toHaveLength(1)
})
})
describe('buildRegularPolygon()', () => {
it('should return exactly as many line segments as sides requested', () => {
const shapes = buildRegularPolygon({ sides: 5 })
expect(shapes).toHaveLength(5)
expect(shapes.every((s) => s.type === 'line')).toBe(true)
})
it('should clamp the number of sides between 3 and 12', () => {
expect(buildRegularPolygon({ sides: 1 })).toHaveLength(3)
expect(buildRegularPolygon({ sides: 100 })).toHaveLength(12)
})
it('should attach the provided labels/captions by index', () => {
const shapes = buildRegularPolygon({ sides: 3, labels: ['a', 'b', 'c'] })
expect(shapes.map((s) => s.label)).toEqual(['a', 'b', 'c'])
})
})
describe('buildRightTriangle()', () => {
it('should return the three sides, the right-angle marker and the angle arc', () => {
const shapes = buildRightTriangle({})
expect(shapes.filter((s) => s.type === 'line')).toHaveLength(3)
expect(shapes.some((s) => s.type === 'rect')).toBe(true)
expect(shapes.some((s) => s.type === 'arc')).toBe(true)
})
it('should use the default labels when none are provided', () => {
const shapes = buildRightTriangle({})
const labels = shapes.map((s) => s.label)
expect(labels).toContain('Adjacent')
expect(labels).toContain('Opposé')
expect(labels).toContain('Hypoténuse')
})
it('should use custom labels when provided', () => {
const shapes = buildRightTriangle({ adjacentLabel: 'Cote A' })
expect(shapes.some((s) => s.label === 'Cote A')).toBe(true)
})
})
describe('buildTriangle()', () => {
it('should return the three sides of the triangle', () => {
const shapes = buildTriangle({})
expect(shapes.filter((s) => s.type === 'line')).toHaveLength(3)
})
it('should include an apex text label when apexLabel is provided', () => {
const shapes = buildTriangle({ apexLabel: 'A' })
expect(shapes.some((s) => s.type === 'text' && s.content === 'A')).toBe(true)
})
it('should omit the apex text shape when no apexLabel is provided', () => {
const shapes = buildTriangle({})
expect(shapes.some((s) => s.type === 'text')).toBe(false)
})
})
describe('buildVennDiagram()', () => {
it('should return 2 circles by default', () => {
const shapes = buildVennDiagram({})
expect(shapes).toHaveLength(2)
expect(shapes.every((s) => s.type === 'circle')).toBe(true)
})
it('should return 3 circles when 3 labels are given', () => {
const shapes = buildVennDiagram({ labels: ['A', 'B', 'C'] })
expect(shapes).toHaveLength(3)
expect(shapes.map((s) => s.label)).toEqual(['A', 'B', 'C'])
})
it('should clamp to at most 3 circles even with more labels', () => {
const shapes = buildVennDiagram({ labels: ['A', 'B', 'C', 'D', 'E'] })
expect(shapes).toHaveLength(3)
})
})
@@ -1,45 +0,0 @@
import { describe, it, expect } from 'vitest'
import { num, str, strOrUndefined } from '../../src/main/coach/presets/utils'
describe('num()', () => {
it('should parse a numeric value within range', () => {
expect(num(5, 0, 0, 10)).toBe(5)
})
it('should return the fallback for a non-finite value', () => {
expect(num('abc', 42)).toBe(42)
expect(num(undefined, 42)).toBe(42)
expect(num(NaN, 42)).toBe(42)
})
it('should clamp a value above the max', () => {
expect(num(100, 0, 0, 10)).toBe(10)
})
it('should clamp a value below the min', () => {
expect(num(-100, 0, 0, 10)).toBe(0)
})
})
describe('str()', () => {
it('should return the trimmed string when given a non-empty string', () => {
expect(str(' hello ')).toBe('hello')
})
it('should return the fallback for a non-string or blank value', () => {
expect(str(42)).toBe('')
expect(str(' ')).toBe('')
expect(str(undefined, 'defaut')).toBe('defaut')
})
})
describe('strOrUndefined()', () => {
it('should return the trimmed string when given a non-empty string', () => {
expect(strOrUndefined(' hello ')).toBe('hello')
})
it('should return undefined for a non-string or blank value', () => {
expect(strOrUndefined(42)).toBeUndefined()
expect(strOrUndefined(' ')).toBeUndefined()
})
})
@@ -1,87 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { EventEmitter } from 'node:events'
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
class FakeWebContents extends EventEmitter {
send = vi.fn()
isLoading = vi.fn(() => false)
}
class FakeBrowserWindow extends EventEmitter {
webContents = new FakeWebContents()
show = vi.fn()
moveTop = vi.fn()
focus = vi.fn()
setAlwaysOnTop = vi.fn()
maximize = vi.fn()
loadURL = vi.fn()
loadFile = vi.fn()
destroyed = false
isDestroyed(): boolean {
return this.destroyed
}
}
let lastWindow: FakeBrowserWindow | null = null
let nextWindowStartsLoading = false
function createBrowserWindow(): FakeBrowserWindow {
const window = new FakeBrowserWindow()
if (nextWindowStartsLoading) {
window.webContents.isLoading.mockReturnValue(true)
nextWindowStartsLoading = false
}
lastWindow = window
return window
}
vi.mock('electron', () => ({ BrowserWindow: vi.fn(createBrowserWindow) }))
const { openCoachProgressWindow } = await import('../../src/main/coach/progressWindow')
describe('openCoachProgressWindow()', () => {
beforeEach(() => {
lastWindow?.emit('closed')
vi.clearAllMocks()
lastWindow = null
})
it('should create and maximize a new window', () => {
openCoachProgressWindow()
expect(lastWindow?.maximize).toHaveBeenCalled()
expect(lastWindow?.setAlwaysOnTop).toHaveBeenCalled()
})
it('should reuse and re-show the existing window on a second call', () => {
openCoachProgressWindow()
const firstWindow = lastWindow
openCoachProgressWindow()
expect(lastWindow).toBe(firstWindow)
expect(firstWindow?.show).toHaveBeenCalledTimes(1)
})
it('should send navigate-to-module immediately when the page is already loaded', () => {
openCoachProgressWindow({ subject: 'algebre', module: 'Fractions' })
expect(lastWindow?.webContents.send).toHaveBeenCalledWith('navigate-to-module', {
subject: 'algebre',
module: 'Fractions'
})
})
it('should wait for did-finish-load before navigating when the page is still loading', () => {
nextWindowStartsLoading = true
openCoachProgressWindow({ subject: 'algebre', module: 'Fractions' })
expect(lastWindow?.webContents.send).not.toHaveBeenCalled()
lastWindow?.webContents.emit('did-finish-load')
expect(lastWindow?.webContents.send).toHaveBeenCalled()
})
it('should navigate on an already-open window reused for a second target', () => {
openCoachProgressWindow()
openCoachProgressWindow({ subject: 'geometrie', module: 'Triangles' })
expect(lastWindow?.webContents.send).toHaveBeenCalledWith('navigate-to-module', {
subject: 'geometrie',
module: 'Triangles'
})
})
})
@@ -1,54 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const NotificationShow = vi.fn()
class NotificationMock {
show = NotificationShow
constructor(public options: { title: string; body: string }) {}
}
vi.mock('electron', () => ({ Notification: NotificationMock }))
const synthesizeSpeech = vi.fn(async () => Buffer.from([1, 2, 3]))
vi.mock('../../src/main/ai/elevenlabs', () => ({ synthesizeSpeech }))
const sendToRenderer = vi.fn()
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer }))
interface DueReview {
conceptId: number
subject: string
concept: string
}
const getDueReviews = vi.fn((): DueReview[] => [])
const markReminded = vi.fn()
vi.mock('../../src/main/coach/coachStore', () => ({ getDueReviews, markReminded }))
const { startReviewScheduler } = await import('../../src/main/coach/reviewScheduler')
describe('startReviewScheduler()', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.useFakeTimers()
})
it('should not notify anything when no review is due', async () => {
getDueReviews.mockReturnValue([])
startReviewScheduler()
await vi.advanceTimersByTimeAsync(5 * 60 * 1000)
expect(NotificationShow).not.toHaveBeenCalled()
vi.useRealTimers()
})
it('should show a notification, speak and mark reviews as reminded when due', async () => {
getDueReviews.mockReturnValue([
{ conceptId: 1, subject: 'algebre', concept: 'equations' },
{ conceptId: 2, subject: 'algebre', concept: 'fractions' }
])
startReviewScheduler()
await vi.advanceTimersByTimeAsync(5 * 60 * 1000)
expect(NotificationShow).toHaveBeenCalled()
expect(sendToRenderer).toHaveBeenCalledWith('proactive-speech', expect.anything())
expect(markReminded).toHaveBeenCalledWith(1)
expect(markReminded).toHaveBeenCalledWith(2)
vi.useRealTimers()
})
})
@@ -1,246 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-askexercise-test-'))
vi.mock('electron', () => ({
app: { getPath: () => tempDir }
}))
const requestWrittenAnswers = vi.fn(
async (items: { question: string }[]): Promise<(string | null)[]> =>
items.map(() => 'une reponse')
)
vi.mock('../../src/main/coach/exerciseWindow', () => ({ requestWrittenAnswers }))
const {
setResearchSummary,
createModules,
setModuleTheory,
setSubjectLevel,
upsertConceptStatus,
getModuleOrderIndex,
unlockNextModule
} = await import('../../src/main/coach/coachStore')
const { askWrittenExercise } = await import('../../src/main/skills/coach/askWrittenExercise')
const VALID_CONTENT = [
'Accroche',
'Un vendeur doit calculer rapidement combien de tissu acheter pour un mur triangulaire. '.repeat(
16
),
'Developpement theorique',
'Idee centrale, analogie, definition formelle, exemple resolu et contre-exemple. '.repeat(35),
'Phase guidee',
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier.',
'Exercices progressifs',
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
'Exercice de debogage',
"Trouve l'erreur dans ce calcul errone et corrige-la.",
'Synthese',
'Resume final avec question de meta-cognition et test Feynman. '.repeat(15)
].join('\n\n')
describe('ask_written_exercise — kind="initial"', () => {
const subject = 'geographie-initial-test'
it('should refuse missing questions array', async () => {
await expect(
askWrittenExercise.execute({ subject, kind: 'initial', questions: [] })
).rejects.toThrow(/questions manquantes/)
})
it('should refuse when no course plan exists yet', async () => {
await expect(
askWrittenExercise.execute({
subject,
kind: 'initial',
questions: [{ question: 'Q ?', type: 'free_text', concept: 'Module A' }]
})
).rejects.toThrow(/Aucun plan de cours ecrit/)
})
it('should refuse when module content is missing', async () => {
setResearchSummary(subject, JSON.stringify({ sources: [] }))
createModules(subject, [{ name: 'Module A' }, { name: 'Module B' }])
const { setSubjectObjective } = await import('../../src/main/coach/coachStore')
setSubjectObjective(subject, 'Tu seras capable de situer un pays sur une carte')
await expect(
askWrittenExercise.execute({
subject,
kind: 'initial',
questions: [
{ question: 'Q A ?', type: 'free_text', concept: 'Module A' },
{ question: 'Q B ?', type: 'free_text', concept: 'Module B' }
]
})
).rejects.toThrow(/contenu de certains modules/)
})
it('should refuse when question coverage does not exactly match the modules', async () => {
setModuleTheory(subject, 'Module A', VALID_CONTENT)
setModuleTheory(subject, 'Module B', VALID_CONTENT)
await expect(
askWrittenExercise.execute({
subject,
kind: 'initial',
questions: [{ question: 'Q A ?', type: 'free_text', concept: 'Module A' }]
})
).rejects.toThrow(/Modules non couverts/)
})
it('should refuse a concept not matching any real module', async () => {
await expect(
askWrittenExercise.execute({
subject,
kind: 'initial',
questions: [
{ question: 'Q ?', type: 'free_text', concept: 'Module A' },
{ question: 'Q2 ?', type: 'free_text', concept: 'Module Fantome' }
]
})
).rejects.toThrow(/Concepts invalides/)
})
it('should accept exactly one question per module and save the assessments', async () => {
const result = await askWrittenExercise.execute({
subject,
kind: 'initial',
questions: [
{ question: 'Q A ?', type: 'free_text', concept: 'Module A' },
{ question: 'Q B ?', type: 'free_text', concept: 'Module B' }
]
})
expect(result).toMatch(/Formulaire soumis/)
})
it('should refuse a second initial evaluation once the level is already recorded', async () => {
setSubjectLevel(subject, 'debutant')
await expect(
askWrittenExercise.execute({
subject,
kind: 'initial',
questions: [{ question: 'Q ?', type: 'free_text', concept: 'Module A' }]
})
).rejects.toThrow(/deja enregistre/)
})
})
describe('ask_written_exercise — kind="final"', () => {
const subject = 'final-test'
it('should refuse when not all modules are acquired yet', async () => {
createModules(subject, [{ name: 'Seul module' }])
await expect(
askWrittenExercise.execute({
subject,
kind: 'final',
questions: [{ question: 'Q finale ?', type: 'free_text', difficulty: 'difficile' }]
})
).rejects.toThrow(/ne sont pas encore valides/)
})
it('should refuse a final evaluation with no demanding question', async () => {
const orderIndex = getModuleOrderIndex(subject, 'Seul module')
upsertConceptStatus(subject, 'Seul module', 'acquired')
if (orderIndex !== null) unlockNextModule(subject, orderIndex)
await expect(
askWrittenExercise.execute({
subject,
kind: 'final',
questions: [{ question: 'Q facile ?', type: 'free_text', difficulty: 'facile' }]
})
).rejects.toThrow(/exigeante/)
})
it('should accept a final evaluation with at least one demanding question', async () => {
const result = await askWrittenExercise.execute({
subject,
kind: 'final',
questions: [{ question: 'Q difficile ?', type: 'free_text', difficulty: 'difficile' }]
})
expect(result).toMatch(/Formulaire soumis/)
})
it('should also accept a demanding exerciseStyle without difficulty="difficile"', async () => {
const result = await askWrittenExercise.execute({
subject,
kind: 'final',
questions: [{ question: 'Projet ?', type: 'free_text', exerciseStyle: 'projet' }]
})
expect(result).toMatch(/Formulaire soumis/)
})
})
describe('ask_written_exercise — validation generale', () => {
it('should refuse an invalid kind', async () => {
await expect(
askWrittenExercise.execute({
subject: 'autre-sujet',
kind: 'invalide',
questions: [{ question: 'Q ?', type: 'free_text' }]
})
).rejects.toThrow(/kind invalide/)
})
it('should refuse a multiple_choice question without enough options', async () => {
await expect(
askWrittenExercise.execute({
subject: 'autre-sujet',
kind: 'module',
questions: [{ question: 'Q ?', type: 'multiple_choice', options: ['A'] }]
})
).rejects.toThrow(/options manquantes/)
})
it('should refuse an invalid difficulty value', async () => {
await expect(
askWrittenExercise.execute({
subject: 'autre-sujet',
kind: 'module',
questions: [{ question: 'Q ?', type: 'free_text', difficulty: 'impossible' }]
})
).rejects.toThrow(/difficulty invalide/)
})
it('should refuse an invalid exerciseStyle value', async () => {
await expect(
askWrittenExercise.execute({
subject: 'autre-sujet',
kind: 'module',
questions: [{ question: 'Q ?', type: 'free_text', exerciseStyle: 'inexistant' }]
})
).rejects.toThrow(/exerciseStyle invalide/)
})
it('should normalize an accented exerciseStyle value', async () => {
const result = await askWrittenExercise.execute({
subject: 'autre-sujet',
kind: 'module',
questions: [{ question: 'Q ?', type: 'free_text', exerciseStyle: 'problème_ouvert' }]
})
expect(result).toMatch(/Formulaire soumis/)
})
it('should record a "dont know" answer distinctly from a real answer', async () => {
requestWrittenAnswers.mockResolvedValueOnce(['Je ne sais pas'])
const result = await askWrittenExercise.execute({
subject: 'autre-sujet',
kind: 'module',
questions: [{ question: 'Q ?', type: 'free_text' }]
})
expect(result).toMatch(/lacune enregistree/)
})
it('should report a missing answer when the window closes without one', async () => {
requestWrittenAnswers.mockResolvedValueOnce([null])
const result = await askWrittenExercise.execute({
subject: 'autre-sujet',
kind: 'module',
questions: [{ question: 'Q ?', type: 'free_text' }]
})
expect(result).toMatch(/pas de reponse/)
})
})
@@ -1,182 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-skills-misc-test-'))
vi.mock('electron', () => ({
app: { getPath: () => tempDir }
}))
const openCoachProgressWindow = vi.fn()
vi.mock('../../src/main/coach/progressWindow', () => ({ openCoachProgressWindow }))
const {
setResearchSummary,
createModules,
setModuleTheory,
saveAssessment,
unlockNextModule,
upsertConceptStatus,
getModuleOrderIndex
} = await import('../../src/main/coach/coachStore')
const { recordSubjectLevel } = await import('../../src/main/skills/coach/recordSubjectLevel')
const { trackConceptMastery } = await import('../../src/main/skills/coach/trackConceptMastery')
const { completeSubject } = await import('../../src/main/skills/coach/completeSubject')
const { openModuleForUser } = await import('../../src/main/skills/coach/openModuleForUser')
const { getCoursePlan } = await import('../../src/main/skills/coach/getCoursePlan')
const VALID_CONTENT = [
'Accroche',
'Un vendeur doit calculer rapidement combien de tissu acheter pour un mur triangulaire. '.repeat(
16
),
'Developpement theorique',
'Idee centrale, analogie, definition formelle, exemple resolu et contre-exemple. '.repeat(35),
'Phase guidee',
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier.',
'Exercices progressifs',
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
'Exercice de debogage',
"Trouve l'erreur dans ce calcul errone et corrige-la.",
'Synthese',
'Resume final avec question de meta-cognition et test Feynman. '.repeat(15)
].join('\n\n')
describe('record_subject_level', () => {
const subject = 'chimie-test'
it('should refuse when no assessment exists yet for the subject', async () => {
await expect(recordSubjectLevel.execute({ subject, level: 'debutant' })).rejects.toThrow(
/Aucune evaluation/
)
})
it('should record the level once an assessment exists', async () => {
saveAssessment(subject, null, 'Q ?', 'free_text', null, 'R', 'initial', false, null, null, null)
const result = await recordSubjectLevel.execute({ subject, level: 'debutant' })
expect(result).toMatch(/debutant/)
})
})
describe('track_concept_mastery', () => {
const subject = 'physique-test'
const concept = 'Loi d-ohm'
it('should allow a progress-only status without any assessment', async () => {
const result = await trackConceptMastery.execute({ subject, concept, status: 'in_progress' })
expect(result).toMatch(/in_progress/)
})
it('should refuse an evaluative status ("acquired") without a prior assessment', async () => {
await expect(
trackConceptMastery.execute({ subject, concept, status: 'acquired' })
).rejects.toThrow(/Aucune evaluation/)
})
it('should accept an evaluative status once an assessment exists for that concept', async () => {
saveAssessment(
subject,
concept,
'Q ?',
'free_text',
null,
'R',
'module',
false,
null,
null,
null
)
const result = await trackConceptMastery.execute({ subject, concept, status: 'acquired' })
expect(result).toMatch(/acquired/)
})
it('should reject an invalid status value', async () => {
await expect(
trackConceptMastery.execute({ subject, concept, status: 'invalide' })
).rejects.toThrow(/status invalide/)
})
})
describe('open_module_for_user', () => {
const subject = 'histoire-test'
it('should throw when the module does not exist', async () => {
await expect(openModuleForUser.execute({ subject, module: 'Module fantome' })).rejects.toThrow(
/introuvable/
)
})
it('should refuse to open a locked module', async () => {
createModules(subject, [{ name: 'Module 1' }, { name: 'Module 2' }])
await expect(openModuleForUser.execute({ subject, module: 'Module 2' })).rejects.toThrow(
/verrouille/
)
})
it('should refuse to open a module whose content was never written', async () => {
await expect(openModuleForUser.execute({ subject, module: 'Module 1' })).rejects.toThrow(
/pas encore ecrit/
)
})
it('should open an unlocked module with written content', async () => {
setModuleTheory(subject, 'Module 1', VALID_CONTENT)
openCoachProgressWindow.mockClear()
const result = await openModuleForUser.execute({ subject, module: 'Module 1' })
expect(result).toMatch(/ouvert/)
expect(openCoachProgressWindow).toHaveBeenCalledWith({ subject, module: 'Module 1' })
})
})
describe('complete_subject', () => {
const subject = 'biologie-test'
it('should refuse when modules are not all acquired yet', async () => {
createModules(subject, [{ name: 'Seul module' }])
await expect(completeSubject.execute({ subject })).rejects.toThrow(/pas encore valides/)
})
it('should refuse when all modules are acquired but no final assessment exists', async () => {
const orderIndex = getModuleOrderIndex(subject, 'Seul module')
upsertConceptStatus(subject, 'Seul module', 'acquired')
if (orderIndex !== null) unlockNextModule(subject, orderIndex)
await expect(completeSubject.execute({ subject })).rejects.toThrow(/evaluation finale/)
})
it('should mark the subject as mastered once modules are acquired and a final assessment exists', async () => {
saveAssessment(
subject,
null,
'Q finale ?',
'free_text',
null,
'R',
'final',
false,
'difficile',
null,
null
)
const result = await completeSubject.execute({ subject })
expect(result).toMatch(/maitrise/)
})
})
describe('get_course_plan', () => {
it('should report no existing plan for a brand new subject', async () => {
const result = await getCoursePlan.execute({ subject: 'sujet-jamais-vu-xyz' })
expect(result).toMatch(/Aucun plan de cours/)
})
it('should summarize research/module state for a subject already in progress', async () => {
const subject = 'plan-existant-test'
setResearchSummary(subject, JSON.stringify({ sources: [] }))
createModules(subject, [{ name: 'Module unique' }])
const result = await getCoursePlan.execute({ subject })
expect(result).toMatch(/Recherche deja effectuee/)
expect(result).toMatch(/Module unique/)
})
})
@@ -1,130 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-skills-test-'))
vi.mock('electron', () => ({
app: { getPath: () => tempDir }
}))
vi.mock('../../src/main/coach/exerciseWindow', () => ({
requestWrittenAnswers: vi.fn(async (items: { question: string }[]) =>
items.map(() => 'une reponse')
)
}))
const { setResearchSummary } = await import('../../src/main/coach/coachStore')
const { generateCoursePlan } = await import('../../src/main/skills/coach/generateCoursePlan')
const { writeModuleContent } = await import('../../src/main/skills/coach/writeModuleContent')
const { completeModule } = await import('../../src/main/skills/coach/completeModule')
const { askWrittenExercise } = await import('../../src/main/skills/coach/askWrittenExercise')
const VALID_CONTENT = [
'Accroche',
'Un vendeur doit calculer rapidement combien de tissu acheter pour un mur triangulaire. '.repeat(
16
),
'Developpement theorique',
'Idee centrale, analogie, definition formelle, exemple resolu et contre-exemple. '.repeat(35),
'Phase guidee',
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier.',
'Exercices progressifs',
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
'Exercice de debogage',
"Trouve l'erreur dans ce calcul errone et corrige-la.",
'Synthese',
'Resume final avec question de meta-cognition et test Feynman. '.repeat(15)
].join('\n\n')
const SUBJECT = 'trigonometrie-pipeline-test'
describe('generate_course_plan', () => {
it('should refuse when no research exists yet for the subject', async () => {
await expect(
generateCoursePlan.execute({
subject: 'sujet-jamais-recherche',
objective: 'Tu seras capable de calculer un sinus dans un triangle rectangle',
modules: [{ name: 'Module 1' }]
})
).rejects.toThrow(/Aucune recherche/)
})
it('should refuse when the objective is missing', async () => {
setResearchSummary(SUBJECT, JSON.stringify({ sources: [] }))
await expect(
generateCoursePlan.execute({ subject: SUBJECT, objective: '', modules: [{ name: 'A' }] })
).rejects.toThrow(/objective manquant/)
})
it('should create the course plan once research and objective are present', async () => {
const result = await generateCoursePlan.execute({
subject: SUBJECT,
objective: 'Tu seras capable de calculer un sinus dans un triangle rectangle',
modules: [{ name: 'Module A' }, { name: 'Module B' }]
})
expect(result).toMatch(/Module A/)
expect(result).toMatch(/Module B/)
})
})
describe('write_module_content', () => {
it('should reject content missing required sections', async () => {
await expect(
writeModuleContent.execute({ subject: SUBJECT, module: 'Module A', content: 'Trop court.' })
).rejects.toThrow(/Contenu invalide/)
})
it('should accept well-structured content for the first (unlocked) module', async () => {
const result = await writeModuleContent.execute({
subject: SUBJECT,
module: 'Module A',
content: VALID_CONTENT
})
expect(result).toMatch(/enregistre/)
})
})
describe('complete_module', () => {
it('should refuse when no assessment exists yet for the module', async () => {
await expect(completeModule.execute({ subject: SUBJECT, module: 'Module A' })).rejects.toThrow(
/Aucune evaluation/
)
})
it('should refuse when only a single difficulty level was used', async () => {
await askWrittenExercise.execute({
subject: SUBJECT,
kind: 'module',
questions: [
{
question: 'Question facile ?',
type: 'free_text',
concept: 'Module A',
difficulty: 'facile'
}
]
})
await expect(completeModule.execute({ subject: SUBJECT, module: 'Module A' })).rejects.toThrow(
/niveau de difficulte/
)
})
it('should validate the module once at least two difficulty levels were used and answers were correct', async () => {
await askWrittenExercise.execute({
subject: SUBJECT,
kind: 'module',
questions: [
{
question: 'Question difficile ?',
type: 'free_text',
concept: 'Module A',
difficulty: 'difficile'
}
]
})
const result = await completeModule.execute({ subject: SUBJECT, module: 'Module A' })
expect(result).toMatch(/valide/)
})
})
@@ -1,137 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-drawing-test-'))
vi.mock('electron', () => ({
app: { getPath: () => tempDir }
}))
const openDrawingWindow = vi.fn(async () => {})
const revealShape = vi.fn(async () => {})
const renderMermaid = vi.fn(async () => {})
const playCaption = vi.fn(async () => {})
vi.mock('../../src/main/coach/drawingWindow', () => ({
openDrawingWindow,
revealShape,
renderMermaid,
playCaption
}))
const synthesizeSpeech = vi.fn(async () => Buffer.from('audio'))
vi.mock('../../src/main/ai/elevenlabs', () => ({ synthesizeSpeech }))
const { getModuleDetail, createModules } = await import('../../src/main/coach/coachStore')
const { drawSchema } = await import('../../src/main/skills/coach/drawSchema')
const { drawFlowDiagram } = await import('../../src/main/skills/coach/drawFlowDiagram')
describe('draw_schema', () => {
it('should refuse when no valid shape is given', async () => {
await expect(drawSchema.execute({ title: 'Test', shapes: [] })).rejects.toThrow(
/Aucune forme valide/
)
})
it('should refuse when no shape has a caption', async () => {
await expect(
drawSchema.execute({
title: 'Test',
shapes: [{ type: 'circle', x: 10, y: 10, radius: 5 }]
})
).rejects.toThrow(/Aucune caption/)
})
it('should refuse an unknown preset name', async () => {
await expect(
drawSchema.execute({
title: 'Test',
shapes: [{ type: 'preset', preset: 'inexistant', caption: 'voila' }]
})
).rejects.toThrow(/Preset inconnu/)
})
it('should draw a manual shape with a caption, calling the drawing window and speech synthesis', async () => {
openDrawingWindow.mockClear()
revealShape.mockClear()
synthesizeSpeech.mockClear()
const result = await drawSchema.execute({
title: 'Mon dessin',
shapes: [{ type: 'circle', x: 10, y: 10, radius: 5, caption: 'Voici un cercle' }]
})
expect(result).toMatch(/termine/)
expect(openDrawingWindow).toHaveBeenCalledWith('Mon dessin', 700, 500)
expect(synthesizeSpeech).toHaveBeenCalledWith('Voici un cercle')
expect(revealShape).toHaveBeenCalled()
})
it('should expand a geometry preset into real shapes', async () => {
const result = await drawSchema.execute({
title: 'Triangle',
shapes: [
{
type: 'preset',
preset: 'right_triangle',
presetParams: { adjacentCaption: 'Le cote vertical' }
}
]
})
expect(result).toMatch(/termine/)
})
it('should persist the drawing to the module when subject and module are both given', async () => {
createModules('dessin-subject-test', [{ name: 'Module dessin' }])
await drawSchema.execute({
title: 'Sauvegarde',
subject: 'dessin-subject-test',
module: 'Module dessin',
shapes: [{ type: 'circle', x: 1, y: 1, radius: 1, caption: 'un cercle' }]
})
const detail = getModuleDetail('dessin-subject-test', 'Module dessin')
expect(detail?.diagrams).toHaveLength(1)
})
})
describe('draw_flow_diagram', () => {
it('should refuse missing mermaid code', async () => {
await expect(
drawFlowDiagram.execute({ title: 'Cycle', mermaid: '', captions: ['une etape'] })
).rejects.toThrow(/mermaid manquant/)
})
it('should refuse when no caption is provided', async () => {
await expect(
drawFlowDiagram.execute({ title: 'Cycle', mermaid: 'graph LR; A --> B', captions: [] })
).rejects.toThrow(/Aucune caption/)
})
it('should render the diagram and narrate each caption in sequence', async () => {
renderMermaid.mockClear()
playCaption.mockClear()
const result = await drawFlowDiagram.execute({
title: 'Cycle de l-eau',
mermaid: 'graph LR; Evaporation --> Condensation',
captions: ['Premiere etape', 'Deuxieme etape']
})
expect(result).toMatch(/affiche/)
expect(renderMermaid).toHaveBeenCalledWith(
'Cycle de l-eau',
'graph LR; Evaporation --> Condensation'
)
expect(playCaption).toHaveBeenCalledTimes(2)
})
it('should persist the diagram to the module when subject and module are both given', async () => {
createModules('diagramme-subject-test', [{ name: 'Module diagramme' }])
await drawFlowDiagram.execute({
title: 'Sauvegarde',
subject: 'diagramme-subject-test',
module: 'Module diagramme',
mermaid: 'graph LR; A --> B',
captions: ['une etape']
})
const detail = getModuleDetail('diagramme-subject-test', 'Module diagramme')
expect(detail?.diagrams).toHaveLength(1)
})
})
@@ -1,105 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-research-test-'))
vi.mock('electron', () => ({
app: { getPath: () => tempDir }
}))
const { getResearchSummary } = await import('../../src/main/coach/coachStore')
const { researchTopic } = await import('../../src/main/skills/coach/researchTopic')
function buildSources(count: number, level = 1): { title: string; url: string; level: number }[] {
return Array.from({ length: count }, (_, i) => ({
title: `Source ${i + 1}`,
url: `https://example.edu/source-${i + 1}`,
level
}))
}
const BASE_ARGS = {
subject: 'trigonometrie-recherche-test',
subjectDomain: 'math_science',
definition: 'La trigonometrie etudie les relations entre angles et longueurs.',
usageToday: 'Utilisee en architecture, navigation, physique.',
whyUsedToday: 'Permet de calculer des distances inaccessibles directement.',
practicalCases: 'Calcul de la hauteur d-un batiment via son ombre.',
application: 'Mesurer un angle puis appliquer sinus/cosinus/tangente.',
prerequisites: 'Connaitre le theoreme de Pythagore et les triangles rectangles.',
keyConcepts: ['sinus', 'cosinus', 'tangente', 'hypotenuse', 'angle'],
commonErrors: [
'confondre sinus et cosinus',
'oublier de convertir en radians',
'mauvais triangle de reference'
],
feynmanExplanation:
'Imagine une echelle contre un mur : la trigonometrie dit comment l-angle change la hauteur atteinte.'
}
describe('research_topic', () => {
it('should reject an invalid subjectDomain', async () => {
await expect(
researchTopic.execute({
...BASE_ARGS,
subjectDomain: 'domaine-inconnu',
sources: buildSources(5)
})
).rejects.toThrow(/subjectDomain invalide/)
})
it('should reject a source with an invalid URL', async () => {
await expect(
researchTopic.execute({
...BASE_ARGS,
sources: [{ title: 'Source', url: 'pas-une-url', level: 1 }]
})
).rejects.toThrow(/URL valide/)
})
it('should reject when fewer sources than the domain minimum are provided', async () => {
await expect(researchTopic.execute({ ...BASE_ARGS, sources: buildSources(3) })).rejects.toThrow(
/Au moins 5 sources/
)
})
it('should reject when every source is level 4 only', async () => {
await expect(
researchTopic.execute({ ...BASE_ARGS, sources: buildSources(5, 4) })
).rejects.toThrow(/niveau 1, 2 ou 3/)
})
it('should reject fewer than 5 key concepts', async () => {
await expect(
researchTopic.execute({ ...BASE_ARGS, sources: buildSources(5), keyConcepts: ['a', 'b'] })
).rejects.toThrow(/keyConcepts/)
})
it('should reject fewer than 3 common errors', async () => {
await expect(
researchTopic.execute({ ...BASE_ARGS, sources: buildSources(5), commonErrors: ['a'] })
).rejects.toThrow(/commonErrors/)
})
it('should require a higher minimum source count for medicine_law_finance', async () => {
await expect(
researchTopic.execute({
...BASE_ARGS,
subjectDomain: 'medicine_law_finance',
sources: buildSources(5)
})
).rejects.toThrow(/Au moins 10 sources/)
})
it('should accept a fully valid research payload and persist it', async () => {
const result = await researchTopic.execute({ ...BASE_ARGS, sources: buildSources(5) })
expect(result).toMatch(/enregistree/)
const stored = getResearchSummary(BASE_ARGS.subject)
expect(stored).not.toBeNull()
const parsed = JSON.parse(stored ?? '{}') as { sources: unknown[]; subjectDomain: string }
expect(parsed.sources).toHaveLength(5)
expect(parsed.subjectDomain).toBe('math_science')
})
})
@@ -5,14 +5,10 @@ import { join } from 'node:path'
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-vision-meeting-test-'))
const getSources = vi.fn(async () => [{ thumbnail: { toPNG: () => Buffer.from([1, 2, 3]) } }])
const requestCameraFrame = vi.fn(async () => 'data:image/png;base64,abc')
vi.mock('electron', () => ({
app: { getPath: () => tempDir },
desktopCapturer: { getSources },
screen: { getPrimaryDisplay: () => ({ size: { width: 1920, height: 1080 } }) }
app: { getPath: () => tempDir }
}))
vi.mock('../../src/main/windowBridge', () => ({ requestCameraFrame, sendToRenderer: vi.fn() }))
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer: vi.fn() }))
// pdf-parse/index.js execute du code de demo au chargement quand `module.parent` est absent (cas du
// loader de Vitest), ce qui tente de lire un fichier de test inexistant : on le mocke entierement
@@ -23,11 +19,6 @@ vi.mock('mammoth', () => ({
default: { extractRawText: vi.fn(async () => ({ value: 'Texte extrait du docx' })) }
}))
const analyzeImage = vi.fn(async (_dataUrl: string, question: string) => `Reponse a: ${question}`)
vi.mock('../../src/main/ai/vision', () => ({ analyzeImage }))
const { analyzeScreen } = await import('../../src/main/skills/vision/analyzeScreen')
const { watchCamera } = await import('../../src/main/skills/vision/watchCamera')
const { searchWeb } = await import('../../src/main/skills/web/searchWeb')
const { getLastMeetingSummarySkill } =
await import('../../src/main/skills/meeting/getLastMeetingSummary')
@@ -36,36 +27,6 @@ const { extractText } = await import('../../src/main/skills/documents/extractTex
beforeEach(() => {
vi.clearAllMocks()
getSources.mockResolvedValue([{ thumbnail: { toPNG: () => Buffer.from([1, 2, 3]) } }])
requestCameraFrame.mockResolvedValue('data:image/png;base64,abc')
analyzeImage.mockImplementation(
async (_dataUrl: string, question: string) => `Reponse a: ${question}`
)
})
describe('analyze_screen', () => {
it('should capture the screen and ask the vision model with a default question', async () => {
const result = await analyzeScreen.execute({})
expect(result).toMatch(/Decris ce que tu vois a l'ecran/)
})
it('should throw when no screen source is detected', async () => {
getSources.mockResolvedValueOnce([])
await expect(analyzeScreen.execute({ question: 'test' })).rejects.toThrow(/Aucun ecran/)
})
})
describe('watch_camera', () => {
it('should request a camera frame and ask the vision model', async () => {
const result = await watchCamera.execute({ question: "Qu'est-ce que c'est ?" })
expect(result).toMatch(/Qu'est-ce que c'est/)
expect(requestCameraFrame).toHaveBeenCalled()
})
it('should use a default question when none is given', async () => {
const result = await watchCamera.execute({})
expect(result).toMatch(/Decris ce que tu vois/)
})
})
describe('search_web', () => {
-42
View File
@@ -1,42 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { analyzeImage } from '../../src/main/ai/vision'
describe('analyzeImage()', () => {
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn())
process.env.OPENROUTER_API_KEY = 'test-key'
})
it('should return the model answer when the API call succeeds', async () => {
vi.mocked(fetch).mockResolvedValue({
ok: true,
json: () =>
Promise.resolve({ choices: [{ message: { content: 'Une tasse de cafe sur un bureau.' } }] })
} as Response)
const result = await analyzeImage('data:image/png;base64,abc', "Qu'est-ce que tu vois ?")
expect(result).toBe('Une tasse de cafe sur un bureau.')
})
it('should return a fallback message when the response has no content', async () => {
vi.mocked(fetch).mockResolvedValue({
ok: true,
json: () => Promise.resolve({ choices: [{ message: {} }] })
} as Response)
const result = await analyzeImage('data:image/png;base64,abc', 'Question ?')
expect(result).toMatch(/n'ai pas reussi/)
})
it('should throw a descriptive error when the API call fails', async () => {
vi.mocked(fetch).mockResolvedValue({
ok: false,
status: 429,
text: () => Promise.resolve('Rate limited')
} as Response)
await expect(analyzeImage('data:image/png;base64,abc', 'Question ?')).rejects.toThrow(
/vision.*429/
)
})
})
@@ -1,59 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-visioncapture-test-'))
const getSources = vi.fn(async () => [{ thumbnail: { toPNG: () => Buffer.from([1, 2, 3]) } }])
vi.mock('electron', () => ({
app: { getPath: () => tempDir },
desktopCapturer: { getSources },
screen: { getPrimaryDisplay: () => ({ size: { width: 100, height: 100 } }) }
}))
class WorkerMock {
postMessage = vi.fn()
on = vi.fn()
}
vi.mock('node:worker_threads', () => ({ Worker: WorkerMock }))
const { startVisionCapture, stopVisionCapture, getRecentCaptures } =
await import('../../src/main/coach/visionCapture')
describe('visionCapture', () => {
beforeEach(() => {
vi.useFakeTimers()
})
it('should return an empty list of captures before any capture happens', () => {
expect(getRecentCaptures(5)).toEqual([])
})
it('should capture a screenshot on every tick once started', async () => {
startVisionCapture()
await vi.advanceTimersByTimeAsync(1000)
expect(getSources).toHaveBeenCalled()
stopVisionCapture()
vi.useRealTimers()
})
it('should not start a second interval when already running', async () => {
getSources.mockClear()
startVisionCapture()
startVisionCapture()
await vi.advanceTimersByTimeAsync(1000)
expect(getSources).toHaveBeenCalledTimes(1)
stopVisionCapture()
vi.useRealTimers()
})
it('should stop capturing once stopped', async () => {
getSources.mockClear()
startVisionCapture()
stopVisionCapture()
await vi.advanceTimersByTimeAsync(5000)
expect(getSources).not.toHaveBeenCalled()
vi.useRealTimers()
})
})
+2 -74
View File
@@ -1,13 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { describe, it, expect, vi } from 'vitest'
const ipcMainOn = vi.fn()
const ipcMainRemoveListener = vi.fn()
vi.mock('electron', () => ({
ipcMain: { on: ipcMainOn, removeListener: ipcMainRemoveListener }
}))
const { setMainWindow, sendToRenderer, requestCameraFrame } =
await import('../../src/main/windowBridge')
const { setMainWindow, sendToRenderer } = await import('../../src/main/windowBridge')
describe('sendToRenderer()', () => {
it('should do nothing when no main window has been set', () => {
@@ -21,68 +14,3 @@ describe('sendToRenderer()', () => {
expect(send).toHaveBeenCalledWith('some-channel', 'a', 'b')
})
})
describe('requestCameraFrame()', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('should reject immediately when no main window is available', async () => {
setMainWindow(null as never)
await expect(requestCameraFrame()).rejects.toThrow(/Fenetre indisponible/)
})
it('should resolve with the data URL once the renderer responds for the matching request', async () => {
const send = vi.fn()
setMainWindow({ webContents: { send } } as never)
const promise = requestCameraFrame(1000)
const requestId = send.mock.calls[0]?.[1] as string
const handler = ipcMainOn.mock.calls.find((c) => c[0] === 'camera-frame-result')?.[1] as (
event: unknown,
id: string,
dataUrl: string | null
) => void
handler({}, requestId, 'data:image/png;base64,abc')
await expect(promise).resolves.toBe('data:image/png;base64,abc')
})
it('should reject when the renderer responds with null (camera unavailable)', async () => {
const send = vi.fn()
setMainWindow({ webContents: { send } } as never)
const promise = requestCameraFrame(1000)
const requestId = send.mock.calls[0]?.[1] as string
const handler = ipcMainOn.mock.calls.find((c) => c[0] === 'camera-frame-result')?.[1] as (
event: unknown,
id: string,
dataUrl: string | null
) => void
handler({}, requestId, null)
await expect(promise).rejects.toThrow(/Impossible d'acceder a la camera/)
})
it('should ignore a response for a different request id', async () => {
const send = vi.fn()
setMainWindow({ webContents: { send } } as never)
const promise = requestCameraFrame(1000)
const handler = ipcMainOn.mock.calls.find((c) => c[0] === 'camera-frame-result')?.[1] as (
event: unknown,
id: string,
dataUrl: string | null
) => void
handler({}, 'un-autre-id', 'data:image/png;base64,ignore')
const handlerAgain = ipcMainOn.mock.calls.find((c) => c[0] === 'camera-frame-result')?.[1] as (
event: unknown,
id: string,
dataUrl: string | null
) => void
const requestId = send.mock.calls[0]?.[1] as string
handlerAgain({}, requestId, 'data:image/png;base64,bon')
await expect(promise).resolves.toBe('data:image/png;base64,bon')
})
})