feat: add CI/CD, code quality, testing and security hardening
CI / quality (push) Failing after 6m22s
CI / quality (push) Failing after 6m22s
Implements Max_Code_Quality_CICD_Production.md: TypeScript strict mode, ESLint flat config with type-checking and security plugin, Prettier, Husky + lint-staged, Vitest with 80%+ coverage (473 tests), Playwright e2e, Electron security hardening (contextIsolation, CSP, IPC validation), electron-builder + electron-updater, Dockerfile, Gitea Actions CI/release workflows, and SonarQube docker-compose setup. Also fixes two real bugs found while writing tests: unawaited clipboard promises and a mermaid container ref timing issue in CoachDrawingView. Fixes lint-staged on Windows/Node 24 by invoking eslint/prettier via `node <bin>.js` instead of their .cmd shims, which Node's child_process now refuses to spawn without shell:true. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
1959ddb41a
commit
e9690a49f9
@@ -0,0 +1,25 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { asString } from '../../src/main/skills/argUtils'
|
||||
|
||||
describe('asString()', () => {
|
||||
it('should return the value unchanged when it is already a string', () => {
|
||||
expect(asString('bonjour')).toBe('bonjour')
|
||||
})
|
||||
|
||||
it('should return the empty string by default when the value is not a string', () => {
|
||||
expect(asString(undefined)).toBe('')
|
||||
expect(asString(null)).toBe('')
|
||||
expect(asString(42)).toBe('')
|
||||
expect(asString({ foo: 'bar' })).toBe('')
|
||||
})
|
||||
|
||||
it('should return the provided fallback when the value is not a string', () => {
|
||||
expect(asString(undefined, 'module')).toBe('module')
|
||||
expect(asString(123, 'defaut')).toBe('defaut')
|
||||
})
|
||||
|
||||
it('should never coerce a non-string value via toString (no "[object Object]" leak)', () => {
|
||||
const result = asString({ toString: () => 'should not appear' })
|
||||
expect(result).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,433 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { EventEmitter } from 'node:events'
|
||||
|
||||
// jsdom n'implemente pas innerText (pas de mise en page reelle) : le code de production (destine a
|
||||
// un vrai Chromium via executeJavaScript) s'appuie dessus. On le fait correspondre a textContent
|
||||
// pour ce test, suffisant pour du texte simple sans mise en forme complexe.
|
||||
Object.defineProperty(HTMLElement.prototype, 'innerText', {
|
||||
get(): string {
|
||||
return (this as HTMLElement).textContent ?? ''
|
||||
},
|
||||
set(value: string) {
|
||||
;(this as HTMLElement).textContent = value
|
||||
},
|
||||
configurable: true
|
||||
})
|
||||
|
||||
// jsdom n'implemente pas scrollIntoView (pas de mise en page reelle) non plus.
|
||||
Element.prototype.scrollIntoView = vi.fn()
|
||||
|
||||
// jsdom n'implemente pas non plus l'API legacy window.find() (recherche de texte dans la page) :
|
||||
// implementation minimaliste suffisante pour le test (recherche globale, premiere occurrence,
|
||||
// selectionne le noeud texte correspondant).
|
||||
;(window as unknown as { find: (text: string) => boolean }).find = (text: string): boolean => {
|
||||
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT)
|
||||
let node: Node | null
|
||||
while ((node = walker.nextNode())) {
|
||||
const index = (node.textContent ?? '').indexOf(text)
|
||||
if (index >= 0) {
|
||||
const range = document.createRange()
|
||||
range.setStart(node, index)
|
||||
range.setEnd(node, index + text.length)
|
||||
const selection = window.getSelection()
|
||||
selection?.removeAllRanges()
|
||||
selection?.addRange(range)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// executeJavaScript recoit le code sous forme de chaine ( `(${fn.toString()})(args)` ) : l'evaluer
|
||||
// reellement ici (environnement jsdom) execute le vrai code de manipulation DOM contre le vrai
|
||||
// `document` de jsdom, ce qui donne a la fois une vraie couverture ET un vrai test de comportement,
|
||||
// plutot que de mocker la valeur de retour a la main pour chaque fonction.
|
||||
class FakeWebContents extends EventEmitter {
|
||||
executeJavaScript = vi.fn(async (code: string): Promise<unknown> => eval(code) as unknown)
|
||||
getTitle = vi.fn(() => 'Titre de la page')
|
||||
navigationHistory = { canGoBack: vi.fn(() => true), goBack: vi.fn() }
|
||||
}
|
||||
|
||||
class FakeBrowserWindow extends EventEmitter {
|
||||
webContents = new FakeWebContents()
|
||||
show = vi.fn()
|
||||
maximize = vi.fn()
|
||||
loadURL = vi.fn()
|
||||
destroyed = false
|
||||
isDestroyed(): boolean {
|
||||
return this.destroyed
|
||||
}
|
||||
}
|
||||
|
||||
let lastWindow: FakeBrowserWindow | null = null
|
||||
function createBrowserWindow(): FakeBrowserWindow {
|
||||
const window = new FakeBrowserWindow()
|
||||
lastWindow = window
|
||||
return window
|
||||
}
|
||||
|
||||
vi.mock('electron', () => ({ BrowserWindow: vi.fn(createBrowserWindow) }))
|
||||
|
||||
const {
|
||||
navigateTo,
|
||||
goBack,
|
||||
readPageText,
|
||||
clickElementByText,
|
||||
fillField,
|
||||
collectTranslatableElements,
|
||||
applyTranslations,
|
||||
highlightText,
|
||||
dismissCookieBannerInPage,
|
||||
clickByTextInPage,
|
||||
fillFieldInPage,
|
||||
collectInPage,
|
||||
applyInPage,
|
||||
highlightInPage
|
||||
} = await import('../../src/main/browser/browserWindow')
|
||||
|
||||
function finishLoad(): void {
|
||||
lastWindow?.webContents.emit('did-finish-load')
|
||||
}
|
||||
|
||||
describe('navigateTo()', () => {
|
||||
beforeEach(() => {
|
||||
lastWindow?.emit('closed')
|
||||
vi.clearAllMocks()
|
||||
lastWindow = null
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
it('should create the window, load the URL and return the page title', async () => {
|
||||
const promise = navigateTo('https://example.com')
|
||||
finishLoad()
|
||||
const title = await promise
|
||||
expect(title).toBe('Titre de la page')
|
||||
expect(lastWindow?.show).toHaveBeenCalled()
|
||||
expect(lastWindow?.loadURL).toHaveBeenCalledWith('https://example.com')
|
||||
})
|
||||
|
||||
it('should reject when the page fails to load', async () => {
|
||||
const promise = navigateTo('https://example.com')
|
||||
lastWindow?.webContents.emit('did-fail-load', {}, 404, 'Not Found')
|
||||
await expect(promise).rejects.toThrow(/Echec de chargement/)
|
||||
})
|
||||
|
||||
it('should dismiss a cookie banner by clicking the matching button', async () => {
|
||||
document.body.innerHTML = '<button>Tout accepter</button><p>Contenu reel</p>'
|
||||
const promise = navigateTo('https://example.com')
|
||||
finishLoad()
|
||||
await promise
|
||||
expect(document.querySelector('button')?.textContent).toBe('Tout accepter')
|
||||
})
|
||||
|
||||
it('should not click anything when no cookie banner phrase matches', async () => {
|
||||
document.body.innerHTML = '<button>Parametres avances</button>'
|
||||
const clicked = vi.fn()
|
||||
document.querySelector('button')?.addEventListener('click', clicked)
|
||||
const promise = navigateTo('https://example.com')
|
||||
finishLoad()
|
||||
await promise
|
||||
expect(clicked).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should not fail navigation when the cookie-dismiss script injection itself fails', async () => {
|
||||
const promise = navigateTo('https://example.com')
|
||||
lastWindow!.webContents.executeJavaScript = vi.fn(async () => {
|
||||
throw new Error('injection blocked')
|
||||
})
|
||||
finishLoad()
|
||||
await expect(promise).resolves.toBe('Titre de la page')
|
||||
})
|
||||
})
|
||||
|
||||
describe('goBack()', () => {
|
||||
beforeEach(() => {
|
||||
lastWindow?.emit('closed')
|
||||
vi.clearAllMocks()
|
||||
lastWindow = null
|
||||
})
|
||||
|
||||
it('should throw when no browser window is open', async () => {
|
||||
await expect(goBack()).rejects.toThrow(/Aucun navigateur ouvert/)
|
||||
})
|
||||
|
||||
it('should return false when there is no previous page', async () => {
|
||||
const navPromise = navigateTo('https://example.com')
|
||||
finishLoad()
|
||||
await navPromise
|
||||
lastWindow!.webContents.navigationHistory.canGoBack.mockReturnValue(false)
|
||||
expect(await goBack()).toBe(false)
|
||||
})
|
||||
|
||||
it('should go back and wait for the page to finish loading', async () => {
|
||||
const navPromise = navigateTo('https://example.com')
|
||||
finishLoad()
|
||||
await navPromise
|
||||
const backPromise = goBack()
|
||||
finishLoad()
|
||||
expect(await backPromise).toBe(true)
|
||||
expect(lastWindow?.webContents.navigationHistory.goBack).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('page interaction functions (require an open window)', () => {
|
||||
beforeEach(async () => {
|
||||
lastWindow?.emit('closed')
|
||||
vi.clearAllMocks()
|
||||
lastWindow = null
|
||||
document.body.innerHTML = ''
|
||||
const navPromise = navigateTo('https://example.com')
|
||||
finishLoad()
|
||||
await navPromise
|
||||
})
|
||||
|
||||
it('readPageText() should throw when no browser window is open', async () => {
|
||||
lastWindow?.emit('closed')
|
||||
await expect(readPageText()).rejects.toThrow(/Aucun navigateur ouvert/)
|
||||
})
|
||||
|
||||
it('readPageText() should return the trimmed body text', async () => {
|
||||
document.body.innerHTML = '<p>Bonjour le monde</p>'
|
||||
const text = await readPageText()
|
||||
expect(text).toContain('Bonjour le monde')
|
||||
})
|
||||
|
||||
it('clickElementByText() should click a visible button matching the text and return true', async () => {
|
||||
document.body.innerHTML = '<button>Connexion</button>'
|
||||
const clicked = vi.fn()
|
||||
document.querySelector('button')?.addEventListener('click', clicked)
|
||||
const result = await clickElementByText('Connexion')
|
||||
expect(result).toBe(true)
|
||||
expect(clicked).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clickElementByText() should return false when nothing matches', async () => {
|
||||
document.body.innerHTML = '<button>Autre chose</button>'
|
||||
expect(await clickElementByText('Introuvable')).toBe(false)
|
||||
})
|
||||
|
||||
it('clickElementByText() should fall back to a partial (includes) match', async () => {
|
||||
document.body.innerHTML = '<a href="#">Voir tous les articles</a>'
|
||||
expect(await clickElementByText('articles')).toBe(true)
|
||||
})
|
||||
|
||||
it('clickElementByText() should match a submit input by its value attribute', async () => {
|
||||
document.body.innerHTML = '<input type="submit" value="Envoyer" />'
|
||||
expect(await clickElementByText('Envoyer')).toBe(true)
|
||||
})
|
||||
|
||||
it('fillField() should fill a matching input by its name/placeholder/label', async () => {
|
||||
document.body.innerHTML = '<input name="email" placeholder="Votre email" />'
|
||||
const result = await fillField('email', 'test@example.com', false)
|
||||
expect(result).toBe(true)
|
||||
expect((document.querySelector('input') as HTMLInputElement).value).toBe('test@example.com')
|
||||
})
|
||||
|
||||
it('fillField() should return false when no matching field is found', async () => {
|
||||
document.body.innerHTML = '<input name="phone" />'
|
||||
expect(await fillField('adresse', 'x', false)).toBe(false)
|
||||
})
|
||||
|
||||
it('fillField() should match a field by its associated <label>', async () => {
|
||||
document.body.innerHTML = '<label for="champ1">Numero de telephone</label><input id="champ1" />'
|
||||
expect(await fillField('telephone', '0600000000', false)).toBe(true)
|
||||
})
|
||||
|
||||
it('fillField() should fill a textarea too', async () => {
|
||||
document.body.innerHTML = '<textarea name="message"></textarea>'
|
||||
expect(await fillField('message', 'Bonjour', false)).toBe(true)
|
||||
expect((document.querySelector('textarea') as HTMLTextAreaElement).value).toBe('Bonjour')
|
||||
})
|
||||
|
||||
it('fillField() should submit the enclosing form when submit is requested', async () => {
|
||||
document.body.innerHTML = '<form><input name="q" /></form>'
|
||||
const form = document.querySelector('form') as HTMLFormElement
|
||||
const requestSubmit = vi.fn()
|
||||
form.requestSubmit = requestSubmit
|
||||
await fillField('q', 'recherche', true)
|
||||
expect(requestSubmit).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fillField() should dispatch an Enter keydown when submitting a field with no form', async () => {
|
||||
document.body.innerHTML = '<input name="q" />'
|
||||
const input = document.querySelector('input')!
|
||||
const keydown = vi.fn()
|
||||
input.addEventListener('keydown', keydown)
|
||||
await fillField('q', 'recherche', true)
|
||||
expect(keydown).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('collectTranslatableElements() should collect visible leaf text nodes', async () => {
|
||||
document.body.innerHTML = '<p>Un paragraphe</p><div><span>Imbrique</span></div>'
|
||||
const elements = await collectTranslatableElements()
|
||||
expect(elements.length).toBeGreaterThan(0)
|
||||
expect(elements.some((e) => e.text === 'Un paragraphe')).toBe(true)
|
||||
})
|
||||
|
||||
it('applyTranslations() should replace the text of tagged elements', async () => {
|
||||
document.body.innerHTML = '<p>Original</p>'
|
||||
const [element] = await collectTranslatableElements()
|
||||
await applyTranslations([{ id: element!.id, text: 'Traduit' }])
|
||||
expect(document.querySelector('p')?.textContent).toBe('Traduit')
|
||||
})
|
||||
|
||||
it('highlightText() should return false when the text is not found on the page', async () => {
|
||||
document.body.innerHTML = '<p>Contenu quelconque</p>'
|
||||
expect(await highlightText('texte introuvable')).toBe(false)
|
||||
})
|
||||
|
||||
it('highlightText() should return false for an empty search string', async () => {
|
||||
expect(await highlightText(' ')).toBe(false)
|
||||
})
|
||||
|
||||
it('highlightText() should wrap the matching text in a <mark> element', async () => {
|
||||
document.body.innerHTML = '<p>Le prix est de 42 euros aujourd-hui</p>'
|
||||
const found = await highlightText('42 euros')
|
||||
expect(found).toBe(true)
|
||||
expect(document.querySelector('mark')?.textContent).toBe('42 euros')
|
||||
})
|
||||
|
||||
it('collectTranslatableElements() should skip elements with empty text', async () => {
|
||||
document.body.innerHTML = '<p> </p><p>Texte reel</p>'
|
||||
const elements = await collectTranslatableElements()
|
||||
expect(elements.map((e) => e.text)).toEqual(['Texte reel'])
|
||||
})
|
||||
})
|
||||
|
||||
// Appels directs des fonctions injectees dans la page (exportees pour etre testables) : memes
|
||||
// fonctions que celles envoyees a executeJavaScript via .toString(), executees ici directement
|
||||
// contre le vrai `document` de jsdom pour une couverture de branches complete.
|
||||
describe('dismissCookieBannerInPage()', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
it('should click the first matching phrase and return it', () => {
|
||||
document.body.innerHTML = '<button>Tout accepter</button>'
|
||||
expect(dismissCookieBannerInPage(['tout accepter'])).toBe('tout accepter')
|
||||
})
|
||||
|
||||
it('should return null when no phrase matches any element', () => {
|
||||
document.body.innerHTML = '<button>Parametres</button>'
|
||||
expect(dismissCookieBannerInPage(['tout accepter', 'accepter'])).toBeNull()
|
||||
})
|
||||
|
||||
it('should match a [role="button"] or an anchor, not only <button>', () => {
|
||||
document.body.innerHTML = '<a role="button">J\'accepte</a>'
|
||||
expect(dismissCookieBannerInPage(["j'accepte"])).toBe("j'accepte")
|
||||
})
|
||||
})
|
||||
|
||||
describe('clickByTextInPage()', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
it('should return false when there are no candidate elements at all', () => {
|
||||
expect(clickByTextInPage('rien')).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false when candidates exist but none match', () => {
|
||||
document.body.innerHTML = '<button>Autre chose</button>'
|
||||
expect(clickByTextInPage('Introuvable')).toBe(false)
|
||||
})
|
||||
|
||||
it('should prefer an exact match over a partial one when both exist', () => {
|
||||
document.body.innerHTML = '<button>Suivant</button><button>Suivant encore</button>'
|
||||
expect(clickByTextInPage('Suivant')).toBe(true)
|
||||
expect((document.querySelectorAll('button')[0] as HTMLElement).onclick).toBeNull()
|
||||
})
|
||||
|
||||
it('should match an input[type="button"] by its value attribute', () => {
|
||||
document.body.innerHTML = '<input type="button" value="Annuler" />'
|
||||
expect(clickByTextInPage('Annuler')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fillFieldInPage()', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
it('should return false when there are no input/textarea elements at all', () => {
|
||||
expect(fillFieldInPage('email', 'x', false)).toBe(false)
|
||||
})
|
||||
|
||||
it('should match by aria-label', () => {
|
||||
document.body.innerHTML = '<input aria-label="Code postal" />'
|
||||
expect(fillFieldInPage('code postal', '75000', false)).toBe(true)
|
||||
})
|
||||
|
||||
it('should match by id', () => {
|
||||
document.body.innerHTML = '<input id="search-box" />'
|
||||
expect(fillFieldInPage('search', 'chaussures', false)).toBe(true)
|
||||
})
|
||||
|
||||
it('should fall back to form.submit() when requestSubmit is unavailable', () => {
|
||||
document.body.innerHTML = '<form><input name="q" /></form>'
|
||||
const form = document.querySelector('form') as HTMLFormElement
|
||||
;(form as unknown as { requestSubmit: unknown }).requestSubmit = undefined
|
||||
const submit = vi.fn()
|
||||
form.submit = submit
|
||||
fillFieldInPage('q', 'recherche', true)
|
||||
expect(submit).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('collectInPage()', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
it('should respect the given limit', () => {
|
||||
document.body.innerHTML = '<p>Un</p><p>Deux</p><p>Trois</p>'
|
||||
expect(collectInPage(2)).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('should skip a non-leaf element containing nested block content', () => {
|
||||
document.body.innerHTML = '<div><p>Paragraphe interne</p></div>'
|
||||
const results = collectInPage(150)
|
||||
expect(results.some((r) => r.text === 'Paragraphe interne')).toBe(true)
|
||||
})
|
||||
|
||||
it('should return an empty array when the page has no matching elements', () => {
|
||||
document.body.innerHTML = '<svg></svg>'
|
||||
expect(collectInPage(150)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyInPage()', () => {
|
||||
it('should do nothing for an id that does not exist on the page', () => {
|
||||
document.body.innerHTML = '<p>Original</p>'
|
||||
expect(() => applyInPage([{ id: 'inexistant', text: 'Nouveau' }])).not.toThrow()
|
||||
expect(document.querySelector('p')?.textContent).toBe('Original')
|
||||
})
|
||||
})
|
||||
|
||||
describe('highlightInPage()', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
it('should return false for an empty target string', () => {
|
||||
expect(highlightInPage('')).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false when window.find reports no match', () => {
|
||||
document.body.innerHTML = '<p>Rien ici</p>'
|
||||
expect(highlightInPage('absent')).toBe(false)
|
||||
})
|
||||
|
||||
it('should wrap the matching text node in a <mark> and scroll it into view', () => {
|
||||
document.body.innerHTML = '<p>Le prix est de 42 euros aujourd-hui</p>'
|
||||
expect(highlightInPage('42 euros')).toBe(true)
|
||||
expect(document.querySelector('mark')?.textContent).toBe('42 euros')
|
||||
})
|
||||
|
||||
it('should return false when a match is found but the selection has no range', () => {
|
||||
const getSelectionSpy = vi.spyOn(window, 'getSelection').mockReturnValue(null)
|
||||
document.body.innerHTML = '<p>Un texte a trouver ici</p>'
|
||||
expect(highlightInPage('trouver')).toBe(false)
|
||||
getSelectionSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { EventEmitter } from 'node:events'
|
||||
|
||||
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', () => {
|
||||
parentPort.emit('message', { purgeDir: 'C:\\captures', cutoff: 1000 })
|
||||
expect(unlinkSyncMock).toHaveBeenCalledTimes(1)
|
||||
expect(unlinkSyncMock).toHaveBeenCalledWith('C:\\captures\\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' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,194 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, act, fireEvent, waitFor } from '@testing-library/react'
|
||||
import type { VoiceState } from '../../../src/renderer/src/voice/useVoiceAssistant'
|
||||
|
||||
vi.mock('../../../src/renderer/src/components/AvatarViewer', () => ({
|
||||
default: ({ onReady }: { onReady: (handle: unknown) => void }) => {
|
||||
onReady({ playAnimation: vi.fn(), playAnimationByName: vi.fn(), animationNames: [] })
|
||||
return <div data-testid="avatar-viewer" />
|
||||
}
|
||||
}))
|
||||
|
||||
let capturedOnStateChange: ((state: VoiceState) => void) | undefined
|
||||
let capturedOnError: ((message: string) => void) | undefined
|
||||
const useVoiceAssistant = vi.fn(
|
||||
(
|
||||
_ref: unknown,
|
||||
_enabled: boolean,
|
||||
onStateChange?: (state: VoiceState) => void,
|
||||
onError?: (message: string) => void
|
||||
) => {
|
||||
capturedOnStateChange = onStateChange
|
||||
capturedOnError = onError
|
||||
}
|
||||
)
|
||||
vi.mock('../../../src/renderer/src/voice/useVoiceAssistant', () => ({ useVoiceAssistant }))
|
||||
vi.mock('../../../src/renderer/src/voice/useProactiveSpeech', () => ({
|
||||
useProactiveSpeech: vi.fn()
|
||||
}))
|
||||
vi.mock('../../../src/renderer/src/voice/useCameraCapture', () => ({ useCameraCapture: vi.fn() }))
|
||||
vi.mock('../../../src/renderer/src/voice/useMeetingRecorder', () => ({
|
||||
useMeetingRecorder: vi.fn()
|
||||
}))
|
||||
|
||||
let onCourseBuildStepCb: ((state: unknown) => void) | undefined
|
||||
let onUpdateAvailableCb: (() => void) | undefined
|
||||
let onUpdateReadyCb: (() => void) | undefined
|
||||
const sendDroppedFiles = vi.fn()
|
||||
const getPathForFile = vi.fn(() => 'C:\\fichier.txt')
|
||||
const showContextMenu = vi.fn()
|
||||
const getWindowBounds = vi.fn(async () => ({ x: 0, y: 0, width: 100, height: 100 }))
|
||||
const setWindowPosition = vi.fn()
|
||||
|
||||
function setupWindowApi(): void {
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
onCourseBuildStep: vi.fn((cb: (s: unknown) => void) => {
|
||||
onCourseBuildStepCb = cb
|
||||
return () => {}
|
||||
}),
|
||||
onUpdateAvailable: vi.fn((cb: () => void) => {
|
||||
onUpdateAvailableCb = cb
|
||||
return () => {}
|
||||
}),
|
||||
onUpdateReady: vi.fn((cb: () => void) => {
|
||||
onUpdateReadyCb = cb
|
||||
return () => {}
|
||||
}),
|
||||
onToggleListening: vi.fn(() => () => {}),
|
||||
onToggleMeetingTranscription: vi.fn(() => () => {}),
|
||||
onProactiveSpeech: vi.fn(() => () => {}),
|
||||
getPathForFile,
|
||||
sendDroppedFiles,
|
||||
showContextMenu,
|
||||
getWindowBounds,
|
||||
setWindowPosition
|
||||
}
|
||||
}
|
||||
|
||||
const { default: App } = await import('../../../src/renderer/src/App')
|
||||
|
||||
describe('<App />', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setupWindowApi()
|
||||
})
|
||||
|
||||
it('should render the avatar viewer', () => {
|
||||
render(<App />)
|
||||
expect(screen.getByTestId('avatar-viewer')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should show the thinking indicator while processing', () => {
|
||||
render(<App />)
|
||||
act(() => capturedOnStateChange?.('processing'))
|
||||
expect(screen.getByText('Max reflechit...')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should show a voice error banner and clear it when a new state arrives', () => {
|
||||
vi.useFakeTimers()
|
||||
render(<App />)
|
||||
act(() => capturedOnError?.('Erreur reseau'))
|
||||
expect(screen.getByText(/Erreur reseau/)).toBeInTheDocument()
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(5000)
|
||||
})
|
||||
expect(screen.queryByText(/Erreur reseau/)).not.toBeInTheDocument()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should hide the error banner once recording starts again', () => {
|
||||
render(<App />)
|
||||
act(() => capturedOnError?.('Erreur reseau'))
|
||||
expect(screen.getByText(/Erreur reseau/)).toBeInTheDocument()
|
||||
act(() => capturedOnStateChange?.('recording'))
|
||||
expect(screen.queryByText(/Erreur reseau/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display the course build stepper once a state arrives', () => {
|
||||
render(<App />)
|
||||
act(() =>
|
||||
onCourseBuildStepCb?.({
|
||||
subject: 'algebre',
|
||||
steps: [{ key: 'recherche', label: 'Recherche', status: 'done' }]
|
||||
})
|
||||
)
|
||||
expect(screen.getByText(/algebre/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display the update banner when an update is available, then ready', () => {
|
||||
render(<App />)
|
||||
act(() => onUpdateAvailableCb?.())
|
||||
expect(screen.getByText(/telechargement en cours/)).toBeInTheDocument()
|
||||
act(() => onUpdateReadyCb?.())
|
||||
expect(screen.getByText(/prochaine fermeture/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should forward dropped files to the main process', () => {
|
||||
render(<App />)
|
||||
const container = screen.getByTestId('avatar-viewer').parentElement!
|
||||
fireEvent.drop(container, { dataTransfer: { files: [{ name: 'a.txt' }] } })
|
||||
expect(getPathForFile).toHaveBeenCalled()
|
||||
expect(sendDroppedFiles).toHaveBeenCalledWith(['C:\\fichier.txt'])
|
||||
})
|
||||
|
||||
it('should not call sendDroppedFiles when nothing is dropped', () => {
|
||||
render(<App />)
|
||||
const container = screen.getByTestId('avatar-viewer').parentElement!
|
||||
fireEvent.drop(container, { dataTransfer: { files: [] } })
|
||||
expect(sendDroppedFiles).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should request the context menu with the current listening/transcribing state', () => {
|
||||
render(<App />)
|
||||
const container = screen.getByTestId('avatar-viewer').parentElement!
|
||||
fireEvent.contextMenu(container)
|
||||
expect(showContextMenu).toHaveBeenCalledWith(true, false)
|
||||
})
|
||||
|
||||
it('should start dragging the window on mouse down and stop on mouse up', async () => {
|
||||
render(<App />)
|
||||
const container = screen.getByTestId('avatar-viewer').parentElement!
|
||||
fireEvent.mouseDown(container, { button: 0, screenX: 10, screenY: 10 })
|
||||
await waitFor(() => expect(getWindowBounds).toHaveBeenCalled())
|
||||
|
||||
fireEvent.mouseMove(window, { screenX: 20, screenY: 15 })
|
||||
expect(setWindowPosition).toHaveBeenCalled()
|
||||
|
||||
fireEvent.mouseUp(window)
|
||||
setWindowPosition.mockClear()
|
||||
fireEvent.mouseMove(window, { screenX: 50, screenY: 50 })
|
||||
expect(setWindowPosition).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should ignore a non-primary mouse button for dragging', async () => {
|
||||
render(<App />)
|
||||
const container = screen.getByTestId('avatar-viewer').parentElement!
|
||||
fireEvent.mouseDown(container, { button: 2 })
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
expect(getWindowBounds).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,166 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, cleanup } from '@testing-library/react'
|
||||
|
||||
const disposeGeometry = vi.fn()
|
||||
const disposeMaterial = vi.fn()
|
||||
const disposeRenderer = vi.fn()
|
||||
const sceneAdd = vi.fn()
|
||||
let loadedMesh: FakeMesh | undefined
|
||||
|
||||
class FakeObject3D {
|
||||
frustumCulled = true
|
||||
traverse(cb: (obj: unknown) => void): void {
|
||||
if (loadedMesh) cb(loadedMesh)
|
||||
}
|
||||
}
|
||||
|
||||
class FakeMesh extends FakeObject3D {
|
||||
geometry = { dispose: disposeGeometry }
|
||||
material = { dispose: disposeMaterial }
|
||||
}
|
||||
|
||||
class FakeScene extends FakeObject3D {
|
||||
add = sceneAdd
|
||||
}
|
||||
|
||||
class FakeCamera {
|
||||
fov = 30
|
||||
aspect = 1
|
||||
position = { set: vi.fn() }
|
||||
updateProjectionMatrix = vi.fn()
|
||||
lookAt = vi.fn()
|
||||
}
|
||||
|
||||
class FakeRenderer {
|
||||
domElement = document.createElement('canvas')
|
||||
setPixelRatio = vi.fn()
|
||||
setClearColor = vi.fn()
|
||||
setSize = vi.fn()
|
||||
render = vi.fn()
|
||||
dispose = disposeRenderer
|
||||
}
|
||||
|
||||
class FakeAnimationAction {
|
||||
reset = vi.fn(() => this)
|
||||
fadeIn = vi.fn(() => this)
|
||||
fadeOut = vi.fn(() => this)
|
||||
play = vi.fn(() => this)
|
||||
}
|
||||
|
||||
class FakeAnimationMixer {
|
||||
update = vi.fn()
|
||||
clipAction = vi.fn(() => new FakeAnimationAction())
|
||||
}
|
||||
|
||||
class FakeVector3 {
|
||||
x = 0
|
||||
y = 0
|
||||
z = 0
|
||||
}
|
||||
|
||||
class FakeBox3 {
|
||||
max = { y: 2 }
|
||||
min = { y: 0 }
|
||||
setFromObject = vi.fn(() => this)
|
||||
getCenter = vi.fn(() => new FakeVector3())
|
||||
}
|
||||
|
||||
class FakeClock {
|
||||
getDelta = vi.fn(() => 0.016)
|
||||
}
|
||||
|
||||
vi.mock('three', () => ({
|
||||
Scene: FakeScene,
|
||||
PerspectiveCamera: FakeCamera,
|
||||
WebGLRenderer: FakeRenderer,
|
||||
HemisphereLight: vi.fn(),
|
||||
DirectionalLight: class {
|
||||
position = { set: vi.fn() }
|
||||
},
|
||||
AnimationMixer: FakeAnimationMixer,
|
||||
Box3: FakeBox3,
|
||||
Vector3: FakeVector3,
|
||||
Clock: FakeClock,
|
||||
Mesh: FakeMesh
|
||||
}))
|
||||
|
||||
const CLIPS = [
|
||||
{ name: 'talking' },
|
||||
{ name: 'bow' },
|
||||
{ name: 'clap' },
|
||||
{ name: 'fold_arms' },
|
||||
{ name: 'idle' }
|
||||
]
|
||||
|
||||
let gltfLoadCallback: ((gltf: unknown) => void) | undefined
|
||||
let gltfErrorCallback: ((error: unknown) => void) | undefined
|
||||
const loaderLoad = vi.fn(
|
||||
(
|
||||
_file: string,
|
||||
onLoad: (gltf: unknown) => void,
|
||||
_onProgress: unknown,
|
||||
onError: (error: unknown) => void
|
||||
) => {
|
||||
gltfLoadCallback = onLoad
|
||||
gltfErrorCallback = onError
|
||||
}
|
||||
)
|
||||
|
||||
vi.mock('three/examples/jsm/loaders/GLTFLoader.js', () => ({
|
||||
GLTFLoader: class {
|
||||
load = loaderLoad
|
||||
}
|
||||
}))
|
||||
|
||||
const { default: AvatarViewer } = await import('../../../src/renderer/src/components/AvatarViewer')
|
||||
|
||||
describe('<AvatarViewer />', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
loadedMesh = undefined
|
||||
vi.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 1)
|
||||
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('should render a container div', () => {
|
||||
const { container } = render(<AvatarViewer />)
|
||||
expect(container.querySelector('div')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should call onReady with a working handle once the model loads', () => {
|
||||
const onReady = vi.fn()
|
||||
render(<AvatarViewer onReady={onReady} />)
|
||||
gltfLoadCallback?.({ scene: new FakeScene(), animations: CLIPS })
|
||||
|
||||
expect(onReady).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ animationNames: ['talking', 'bow', 'clap', 'fold_arms', 'idle'] })
|
||||
)
|
||||
})
|
||||
|
||||
it('should play an animation by name via the handle given to onReady', () => {
|
||||
let handle: { playAnimationByName: (name: string) => void } | undefined
|
||||
render(<AvatarViewer onReady={(h) => (handle = h)} />)
|
||||
gltfLoadCallback?.({ scene: new FakeScene(), animations: CLIPS })
|
||||
|
||||
handle?.playAnimationByName('idle')
|
||||
// Pas d'assertion sur l'animation interne directement observable depuis l'exterieur, mais
|
||||
// l'appel ne doit pas lever d'exception et doit couvrir le chemin de recherche par nom.
|
||||
expect(() => handle?.playAnimationByName('inexistante')).not.toThrow()
|
||||
})
|
||||
|
||||
it('should log an error when the model fails to load', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
render(<AvatarViewer />)
|
||||
gltfErrorCallback?.(new Error('404'))
|
||||
expect(errorSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should dispose geometry, material and renderer resources on unmount', () => {
|
||||
loadedMesh = new FakeMesh()
|
||||
render(<AvatarViewer />)
|
||||
cleanup()
|
||||
expect(disposeGeometry).toHaveBeenCalled()
|
||||
expect(disposeMaterial).toHaveBeenCalled()
|
||||
expect(disposeRenderer).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,131 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor, act } from '@testing-library/react'
|
||||
|
||||
const drawShape = vi.fn()
|
||||
vi.mock('../../../src/renderer/src/components/drawRoughShapes', () => ({ drawShape }))
|
||||
|
||||
const roughCanvas = vi.fn(() => ({}))
|
||||
vi.mock('roughjs', () => ({ default: { canvas: roughCanvas } }))
|
||||
|
||||
const mermaidRender = vi.fn(async () => ({ svg: '<svg></svg>' }))
|
||||
const mermaidInitialize = vi.fn()
|
||||
vi.mock('mermaid', () => ({
|
||||
default: { initialize: mermaidInitialize, render: mermaidRender }
|
||||
}))
|
||||
|
||||
interface InitDrawingPayload {
|
||||
title: string
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
interface RevealShapePayload {
|
||||
requestId: string
|
||||
shape: { type: string }
|
||||
audio: ArrayBuffer | null
|
||||
}
|
||||
interface RenderMermaidPayload {
|
||||
requestId: string
|
||||
title: string
|
||||
mermaidCode: string
|
||||
}
|
||||
interface PlayCaptionPayload {
|
||||
requestId: string
|
||||
audio: ArrayBuffer
|
||||
}
|
||||
|
||||
const listeners: {
|
||||
onInitDrawing?: (payload: InitDrawingPayload) => void
|
||||
onRevealShape?: (payload: RevealShapePayload) => void
|
||||
onRenderMermaid?: (payload: RenderMermaidPayload) => void
|
||||
onPlayCaption?: (payload: PlayCaptionPayload) => void
|
||||
} = {}
|
||||
|
||||
function setupWindowApi(): void {
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
onInitDrawing: vi.fn((cb: (payload: InitDrawingPayload) => void) => {
|
||||
listeners.onInitDrawing = cb
|
||||
return () => {}
|
||||
}),
|
||||
onRevealShape: vi.fn((cb: (payload: RevealShapePayload) => void) => {
|
||||
listeners.onRevealShape = cb
|
||||
return () => {}
|
||||
}),
|
||||
onRenderMermaid: vi.fn((cb: (payload: RenderMermaidPayload) => void) => {
|
||||
listeners.onRenderMermaid = cb
|
||||
return () => {}
|
||||
}),
|
||||
onPlayCaption: vi.fn((cb: (payload: PlayCaptionPayload) => void) => {
|
||||
listeners.onPlayCaption = cb
|
||||
return () => {}
|
||||
}),
|
||||
acknowledgeShapeReveal: vi.fn(),
|
||||
acknowledgeMermaidRendered: vi.fn(),
|
||||
acknowledgeCaptionDone: vi.fn()
|
||||
}
|
||||
}
|
||||
|
||||
const { default: CoachDrawingView } =
|
||||
await import('../../../src/renderer/src/components/CoachDrawingView')
|
||||
|
||||
describe('<CoachDrawingView />', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setupWindowApi()
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(
|
||||
{} as CanvasRenderingContext2D
|
||||
)
|
||||
})
|
||||
|
||||
it('should show a waiting message before any drawing is initialized', () => {
|
||||
render(<CoachDrawingView />)
|
||||
expect(screen.getByText(/En attente/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display the title once a drawing is initialized', () => {
|
||||
render(<CoachDrawingView />)
|
||||
act(() => listeners.onInitDrawing?.({ title: 'Mon dessin', width: 700, height: 500 }))
|
||||
expect(screen.getByText('Mon dessin')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should draw a revealed shape and acknowledge it when there is no audio', () => {
|
||||
render(<CoachDrawingView />)
|
||||
act(() => listeners.onInitDrawing?.({ title: 'Mon dessin', width: 700, height: 500 }))
|
||||
const api = (window as unknown as { api: { acknowledgeShapeReveal: ReturnType<typeof vi.fn> } })
|
||||
.api
|
||||
act(() =>
|
||||
listeners.onRevealShape?.({ requestId: 'r1', shape: { type: 'circle' }, audio: null })
|
||||
)
|
||||
expect(drawShape).toHaveBeenCalled()
|
||||
expect(api.acknowledgeShapeReveal).toHaveBeenCalledWith('r1')
|
||||
})
|
||||
|
||||
it('should switch to mermaid mode and render the diagram on success, waiting for the container to mount', async () => {
|
||||
render(<CoachDrawingView />)
|
||||
act(() =>
|
||||
listeners.onRenderMermaid?.({
|
||||
requestId: 'r2',
|
||||
title: 'Cycle de l-eau',
|
||||
mermaidCode: 'graph LR; A --> B'
|
||||
})
|
||||
)
|
||||
expect(screen.getByText('Cycle de l-eau')).toBeInTheDocument()
|
||||
const api = (
|
||||
window as unknown as { api: { acknowledgeMermaidRendered: ReturnType<typeof vi.fn> } }
|
||||
).api
|
||||
await waitFor(() => expect(api.acknowledgeMermaidRendered).toHaveBeenCalledWith('r2', true))
|
||||
})
|
||||
|
||||
it('should report a mermaid render failure', async () => {
|
||||
mermaidRender.mockRejectedValueOnce(new Error('syntaxe invalide'))
|
||||
render(<CoachDrawingView />)
|
||||
act(() =>
|
||||
listeners.onRenderMermaid?.({ requestId: 'r3', title: 'Echec', mermaidCode: 'invalide' })
|
||||
)
|
||||
const api = (
|
||||
window as unknown as { api: { acknowledgeMermaidRendered: ReturnType<typeof vi.fn> } }
|
||||
).api
|
||||
await waitFor(() =>
|
||||
expect(api.acknowledgeMermaidRendered).toHaveBeenCalledWith('r3', false, 'syntaxe invalide')
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, act } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { ExerciseForm } from '../../../src/shared/coach'
|
||||
|
||||
let onFormCallback: ((form: ExerciseForm) => void) | undefined
|
||||
const submitWrittenForm = vi.fn()
|
||||
|
||||
function setupWindowApi(): void {
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
onAskWrittenForm: vi.fn((cb: (form: ExerciseForm) => void) => {
|
||||
onFormCallback = cb
|
||||
return () => {}
|
||||
}),
|
||||
submitWrittenForm
|
||||
}
|
||||
}
|
||||
|
||||
const { default: CoachExerciseView } =
|
||||
await import('../../../src/renderer/src/components/CoachExerciseView')
|
||||
|
||||
const FORM: ExerciseForm = {
|
||||
requestId: 'req-1',
|
||||
items: [
|
||||
{
|
||||
id: '0',
|
||||
question: 'Quelle est la capitale de la France ?',
|
||||
type: 'free_text',
|
||||
options: null
|
||||
},
|
||||
{ id: '1', question: 'Vrai ou faux : 2+2=4', type: 'true_false', options: null },
|
||||
{ id: '2', question: 'Choisis la bonne reponse', type: 'multiple_choice', options: ['A', 'B'] }
|
||||
]
|
||||
}
|
||||
|
||||
describe('<CoachExerciseView />', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setupWindowApi()
|
||||
})
|
||||
|
||||
it('should show a waiting message before any form is received', () => {
|
||||
render(<CoachExerciseView />)
|
||||
expect(screen.getByText(/En attente de questions/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display every question once a form is received', () => {
|
||||
render(<CoachExerciseView />)
|
||||
act(() => onFormCallback?.(FORM))
|
||||
expect(screen.getByText(/capitale de la France/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/2\+2=4/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/bonne reponse/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should keep the submit button disabled until every question is answered', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachExerciseView />)
|
||||
act(() => onFormCallback?.(FORM))
|
||||
|
||||
const submitButton = screen.getByText('Soumettre tout le formulaire')
|
||||
expect(submitButton).toBeDisabled()
|
||||
|
||||
await user.type(screen.getByRole('textbox'), 'Paris')
|
||||
await user.click(screen.getByText('Vrai'))
|
||||
await user.click(screen.getByText('A'))
|
||||
|
||||
expect(submitButton).toBeEnabled()
|
||||
})
|
||||
|
||||
it('should allow answering "Je ne sais pas" to satisfy a question', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachExerciseView />)
|
||||
act(() => onFormCallback?.({ requestId: 'req-2', items: [FORM.items[0]!] }))
|
||||
|
||||
const submitButton = screen.getByText('Soumettre tout le formulaire')
|
||||
expect(submitButton).toBeDisabled()
|
||||
await user.click(screen.getByText('Je ne sais pas'))
|
||||
expect(submitButton).toBeEnabled()
|
||||
})
|
||||
|
||||
it('should submit all answers and show the confirmation message', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachExerciseView />)
|
||||
act(() => onFormCallback?.(FORM))
|
||||
|
||||
await user.type(screen.getByRole('textbox'), 'Paris')
|
||||
await user.click(screen.getByText('Vrai'))
|
||||
await user.click(screen.getByText('A'))
|
||||
await user.click(screen.getByText('Soumettre tout le formulaire'))
|
||||
|
||||
expect(submitWrittenForm).toHaveBeenCalledWith('req-1', [
|
||||
{ id: '0', answer: 'Paris' },
|
||||
{ id: '1', answer: 'Vrai' },
|
||||
{ id: '2', answer: 'A' }
|
||||
])
|
||||
expect(screen.getByText(/Reponses envoyees a Max/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should reset state and show a fresh form when a second form arrives', () => {
|
||||
render(<CoachExerciseView />)
|
||||
act(() => onFormCallback?.(FORM))
|
||||
act(() =>
|
||||
onFormCallback?.({
|
||||
requestId: 'req-3',
|
||||
items: [{ id: '0', question: 'Autre question', type: 'free_text', options: null }]
|
||||
})
|
||||
)
|
||||
expect(screen.getByText(/Autre question/)).toBeInTheDocument()
|
||||
expect(screen.queryByText(/capitale de la France/)).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,236 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type {
|
||||
SubjectProgress,
|
||||
ModuleDetail,
|
||||
CourseComplianceReport
|
||||
} from '../../../src/shared/coach'
|
||||
|
||||
const drawShape = vi.fn()
|
||||
vi.mock('../../../src/renderer/src/components/drawRoughShapes', () => ({ drawShape }))
|
||||
vi.mock('roughjs', () => ({ default: { canvas: vi.fn(() => ({})) } }))
|
||||
const mermaidRender = vi.fn(async () => ({ svg: '<svg></svg>' }))
|
||||
vi.mock('mermaid', () => ({ default: { initialize: vi.fn(), render: mermaidRender } }))
|
||||
|
||||
let navigateCallback: ((payload: { subject: string; module: string }) => void) | undefined
|
||||
const getCoachProgress = vi.fn()
|
||||
const getModuleDetail = vi.fn()
|
||||
const getCourseCompliance = vi.fn(async (): Promise<CourseComplianceReport | null> => null)
|
||||
const requestModuleEvaluation = vi.fn()
|
||||
|
||||
function setupWindowApi(): void {
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
getCoachProgress,
|
||||
getModuleDetail,
|
||||
getCourseCompliance,
|
||||
requestModuleEvaluation,
|
||||
onNavigateToModule: vi.fn((cb: (payload: { subject: string; module: string }) => void) => {
|
||||
navigateCallback = cb
|
||||
return () => {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const { default: CoachProgressView } =
|
||||
await import('../../../src/renderer/src/components/CoachProgressView')
|
||||
|
||||
const SUBJECT: SubjectProgress = {
|
||||
subject: 'algebre',
|
||||
level: 'debutant',
|
||||
status: 'in_progress',
|
||||
objective: 'Tu seras capable de resoudre une equation',
|
||||
lastSessionAt: new Date().toISOString(),
|
||||
concepts: [
|
||||
{
|
||||
name: 'Module A',
|
||||
status: 'acquired',
|
||||
lastReviewedAt: new Date().toISOString(),
|
||||
nextReviewAt: null,
|
||||
locked: false,
|
||||
orderIndex: 0
|
||||
},
|
||||
{
|
||||
name: 'Module B',
|
||||
status: 'not_started',
|
||||
lastReviewedAt: new Date().toISOString(),
|
||||
nextReviewAt: null,
|
||||
locked: true,
|
||||
orderIndex: 1
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const MODULE_DETAIL: ModuleDetail = {
|
||||
name: 'Module A',
|
||||
status: 'acquired',
|
||||
locked: false,
|
||||
theorySummary: 'Contenu du module.',
|
||||
assessments: [
|
||||
{
|
||||
question: 'Question 1 ?',
|
||||
answer: 'Reponse',
|
||||
dontKnow: false,
|
||||
difficulty: 'facile',
|
||||
exerciseStyle: 'prediction',
|
||||
targetsCommonError: null,
|
||||
createdAt: new Date().toISOString()
|
||||
}
|
||||
],
|
||||
diagrams: []
|
||||
}
|
||||
|
||||
describe('<CoachProgressView />', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setupWindowApi()
|
||||
getCoachProgress.mockResolvedValue([SUBJECT])
|
||||
getModuleDetail.mockResolvedValue(MODULE_DETAIL)
|
||||
getCourseCompliance.mockResolvedValue(null)
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
|
||||
clearRect: vi.fn()
|
||||
} as unknown as CanvasRenderingContext2D)
|
||||
})
|
||||
|
||||
it('should show a loading state before subjects arrive', () => {
|
||||
getCoachProgress.mockReturnValue(new Promise(() => {}))
|
||||
render(<CoachProgressView />)
|
||||
expect(screen.getByText('Chargement...')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should list the loaded subjects', async () => {
|
||||
render(<CoachProgressView />)
|
||||
expect(await screen.findByText('algebre')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should show an empty state when there are no subjects yet', async () => {
|
||||
getCoachProgress.mockResolvedValue([])
|
||||
render(<CoachProgressView />)
|
||||
expect(await screen.findByText(/Aucun sujet d.apprentissage/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should navigate to the modules view and list each module', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
expect(screen.getByText('Module A')).toBeInTheDocument()
|
||||
expect(screen.getByText('Module B')).toBeInTheDocument()
|
||||
expect(screen.getByText(/Niveau : debutant/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/resoudre une equation/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should disable a locked module button', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
expect(screen.getByText('Module B').closest('button')).toBeDisabled()
|
||||
})
|
||||
|
||||
it('should show the compliance checklist once loaded', async () => {
|
||||
getCourseCompliance.mockResolvedValue({
|
||||
subject: 'algebre',
|
||||
checks: [
|
||||
{ key: 'sources', label: 'Recherche sourcee', ok: true, detail: 'ok' },
|
||||
{ key: 'objective', label: 'Objectif mesurable', ok: false, detail: 'manquant' }
|
||||
]
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await waitFor(() => expect(screen.getByText(/1\/2/)).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('should navigate to a module detail view and show its content', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
expect(await screen.findByText('Contenu du module.')).toBeInTheDocument()
|
||||
expect(screen.getByText('Question 1 ?')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should show the "evaluer ce module" button for an unlocked, unacquired module', async () => {
|
||||
getModuleDetail.mockResolvedValue({ ...MODULE_DETAIL, status: 'in_progress' })
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
const evalButton = await screen.findByText('Evaluer ce module')
|
||||
await user.click(evalButton)
|
||||
expect(requestModuleEvaluation).toHaveBeenCalledWith('algebre', 'Module A')
|
||||
})
|
||||
|
||||
it('should not show the evaluation button once the module is acquired', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
await screen.findByText('Contenu du module.')
|
||||
expect(screen.queryByText('Evaluer ce module')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should navigate directly to a module detail view on an incoming navigate-to-module event', async () => {
|
||||
render(<CoachProgressView />)
|
||||
await waitFor(() => expect(navigateCallback).toBeDefined())
|
||||
navigateCallback?.({ subject: 'algebre', module: 'Module A' })
|
||||
expect(await screen.findByText('Contenu du module.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render a shapes diagram for a module', async () => {
|
||||
getModuleDetail.mockResolvedValue({
|
||||
...MODULE_DETAIL,
|
||||
diagrams: [
|
||||
{
|
||||
kind: 'shapes',
|
||||
title: 'Mon schema',
|
||||
data: { title: 'Mon schema', width: 400, height: 300, shapes: [] },
|
||||
createdAt: new Date().toISOString()
|
||||
}
|
||||
]
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
expect(await screen.findByText('Mon schema')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render a mermaid diagram for a module', async () => {
|
||||
getModuleDetail.mockResolvedValue({
|
||||
...MODULE_DETAIL,
|
||||
diagrams: [
|
||||
{
|
||||
kind: 'mermaid',
|
||||
title: 'Mon diagramme',
|
||||
data: { mermaidCode: 'graph LR; A --> B' },
|
||||
createdAt: new Date().toISOString()
|
||||
}
|
||||
]
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
expect(await screen.findByText('Mon diagramme')).toBeInTheDocument()
|
||||
await waitFor(() => expect(mermaidRender).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('should go back from the module view to the modules list', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
await screen.findByText('Contenu du module.')
|
||||
await user.click(screen.getByText(/Retour aux modules/))
|
||||
expect(screen.getByText('Module A')).toBeInTheDocument()
|
||||
expect(screen.getByText('Module B')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should go back from the modules view to the subjects list', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText(/Retour aux sujets/))
|
||||
expect(await screen.findByText('algebre')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import CourseBuildStepper from '../../../src/renderer/src/components/CourseBuildStepper'
|
||||
import type { CourseBuildState } from '../../../src/shared/courseBuild'
|
||||
|
||||
const STATE: CourseBuildState = {
|
||||
subject: 'algebre',
|
||||
steps: [
|
||||
{ key: 'recherche', label: 'Recherche approfondie', status: 'done', detail: '5 source(s)' },
|
||||
{ key: 'plan', label: 'Objectif et plan de modules', status: 'active' },
|
||||
{ key: 'redaction', label: 'Redaction des modules', status: 'pending' }
|
||||
]
|
||||
}
|
||||
|
||||
describe('<CourseBuildStepper />', () => {
|
||||
it('should display the subject name', () => {
|
||||
render(<CourseBuildStepper state={STATE} />)
|
||||
expect(screen.getByText(/algebre/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display every step label', () => {
|
||||
render(<CourseBuildStepper state={STATE} />)
|
||||
expect(screen.getByText('Recherche approfondie')).toBeInTheDocument()
|
||||
expect(screen.getByText('Objectif et plan de modules')).toBeInTheDocument()
|
||||
expect(screen.getByText('Redaction des modules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display the detail text only for steps that have one', () => {
|
||||
render(<CourseBuildStepper state={STATE} />)
|
||||
expect(screen.getByText('5 source(s)')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import ThinkingIndicator from '../../../src/renderer/src/components/ThinkingIndicator'
|
||||
|
||||
describe('<ThinkingIndicator />', () => {
|
||||
it('should display the "Max reflechit..." message', () => {
|
||||
render(<ThinkingIndicator />)
|
||||
expect(screen.getByText('Max reflechit...')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import UpdateBanner from '../../../src/renderer/src/components/UpdateBanner'
|
||||
|
||||
describe('<UpdateBanner />', () => {
|
||||
it('should show a downloading message when status is "available"', () => {
|
||||
render(<UpdateBanner status="available" />)
|
||||
expect(screen.getByText(/telechargement en cours/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should show an install-on-restart message when status is "ready"', () => {
|
||||
render(<UpdateBanner status="ready" />)
|
||||
expect(screen.getByText(/prochaine fermeture/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import VoiceErrorBanner from '../../../src/renderer/src/components/VoiceErrorBanner'
|
||||
|
||||
describe('<VoiceErrorBanner />', () => {
|
||||
it('should display the given error message', () => {
|
||||
render(<VoiceErrorBanner message="ElevenLabs injoignable" />)
|
||||
expect(screen.getByText(/ElevenLabs injoignable/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should prefix the message with "Erreur"', () => {
|
||||
render(<VoiceErrorBanner message="Reseau indisponible" />)
|
||||
expect(screen.getByText(/^Erreur :/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import {
|
||||
boxesOverlap,
|
||||
findFreeLabelPosition,
|
||||
drawArrowHead,
|
||||
drawShape,
|
||||
type LabelBox
|
||||
} from '../../../src/renderer/src/components/drawRoughShapes'
|
||||
import type { RoughCanvas } from 'roughjs/bin/canvas'
|
||||
|
||||
function fakeCtx(): {
|
||||
ctx: CanvasRenderingContext2D
|
||||
fillText: ReturnType<typeof vi.fn>
|
||||
beginPath: ReturnType<typeof vi.fn>
|
||||
fill: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
const fillText = vi.fn()
|
||||
const beginPath = vi.fn()
|
||||
const fill = vi.fn()
|
||||
const ctx = {
|
||||
measureText: vi.fn(() => ({ width: 40 })),
|
||||
save: vi.fn(),
|
||||
restore: vi.fn(),
|
||||
beginPath,
|
||||
moveTo: vi.fn(),
|
||||
lineTo: vi.fn(),
|
||||
closePath: vi.fn(),
|
||||
fill,
|
||||
fillText,
|
||||
fillStyle: '',
|
||||
font: ''
|
||||
} as unknown as CanvasRenderingContext2D
|
||||
return { ctx, fillText, beginPath, fill }
|
||||
}
|
||||
|
||||
function fakeRoughCanvas(): {
|
||||
rc: RoughCanvas
|
||||
rectangle: ReturnType<typeof vi.fn>
|
||||
circle: ReturnType<typeof vi.fn>
|
||||
line: ReturnType<typeof vi.fn>
|
||||
curve: ReturnType<typeof vi.fn>
|
||||
arc: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
const rectangle = vi.fn()
|
||||
const circle = vi.fn()
|
||||
const line = vi.fn()
|
||||
const curve = vi.fn()
|
||||
const arc = vi.fn()
|
||||
const rc = { rectangle, circle, line, curve, arc } as unknown as RoughCanvas
|
||||
return { rc, rectangle, circle, line, curve, arc }
|
||||
}
|
||||
|
||||
describe('boxesOverlap()', () => {
|
||||
it('should detect overlapping boxes', () => {
|
||||
const a: LabelBox = { x: 0, y: 0, width: 10, height: 10 }
|
||||
const b: LabelBox = { x: 5, y: 5, width: 10, height: 10 }
|
||||
expect(boxesOverlap(a, b)).toBe(true)
|
||||
})
|
||||
|
||||
it('should detect non-overlapping boxes', () => {
|
||||
const a: LabelBox = { x: 0, y: 0, width: 10, height: 10 }
|
||||
const b: LabelBox = { x: 100, y: 100, width: 10, height: 10 }
|
||||
expect(boxesOverlap(a, b)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('findFreeLabelPosition()', () => {
|
||||
it('should return the starting position when nothing is placed yet', () => {
|
||||
const { ctx } = fakeCtx()
|
||||
const box = findFreeLabelPosition(ctx, 'Label', 10, 30, [])
|
||||
expect(box).toEqual({ x: 10, y: 14, width: 40, height: 16 })
|
||||
})
|
||||
|
||||
it('should shift downward to avoid an already-placed overlapping box', () => {
|
||||
const { ctx } = fakeCtx()
|
||||
const placed: LabelBox[] = [{ x: 10, y: 14, width: 40, height: 16 }]
|
||||
const box = findFreeLabelPosition(ctx, 'Label', 10, 30, placed)
|
||||
expect(box.y).toBeGreaterThan(14)
|
||||
})
|
||||
|
||||
it('should fall back to the last attempted position after 20 attempts if always overlapping', () => {
|
||||
const { ctx } = fakeCtx()
|
||||
const placed: LabelBox[] = Array.from({ length: 25 }, (_, i) => ({
|
||||
x: 10,
|
||||
y: 14 + i * 16,
|
||||
width: 40,
|
||||
height: 16
|
||||
}))
|
||||
const box = findFreeLabelPosition(ctx, 'Label', 10, 30, placed)
|
||||
expect(box).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('drawArrowHead()', () => {
|
||||
it('should draw a filled triangle at the arrow tip', () => {
|
||||
const { ctx, beginPath, fill } = fakeCtx()
|
||||
drawArrowHead(ctx, 0, 0, 10, 10, '#000')
|
||||
expect(beginPath).toHaveBeenCalled()
|
||||
expect(fill).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('drawShape()', () => {
|
||||
it('should draw a rectangle', () => {
|
||||
const { rc, rectangle } = fakeRoughCanvas()
|
||||
const { ctx } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'rect', x: 1, y: 2, width: 10, height: 20 }, [])
|
||||
expect(rectangle).toHaveBeenCalledWith(1, 2, 10, 20, expect.anything())
|
||||
})
|
||||
|
||||
it('should draw a circle', () => {
|
||||
const { rc, circle } = fakeRoughCanvas()
|
||||
const { ctx } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'circle', x: 1, y: 2, radius: 5 }, [])
|
||||
expect(circle).toHaveBeenCalledWith(1, 2, 10, expect.anything())
|
||||
})
|
||||
|
||||
it('should draw a line and position its label at the segment midpoint', () => {
|
||||
const { rc, line } = fakeRoughCanvas()
|
||||
const { ctx, fillText } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'line', x: 0, y: 0, x2: 10, y2: 0, label: 'AB' }, [])
|
||||
expect(line).toHaveBeenCalledWith(0, 0, 10, 0, expect.anything())
|
||||
expect(fillText).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should draw an arrow with an arrowhead', () => {
|
||||
const { rc, line } = fakeRoughCanvas()
|
||||
const { ctx, fill } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'arrow', x: 0, y: 0, x2: 10, y2: 10 }, [])
|
||||
expect(line).toHaveBeenCalled()
|
||||
expect(fill).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should draw a stroke curve only when at least 2 points are given', () => {
|
||||
const { rc, curve } = fakeRoughCanvas()
|
||||
const { ctx } = fakeCtx()
|
||||
drawShape(
|
||||
rc,
|
||||
ctx,
|
||||
{
|
||||
type: 'stroke',
|
||||
points: [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 1 }
|
||||
]
|
||||
},
|
||||
[]
|
||||
)
|
||||
expect(curve).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should not draw a stroke with fewer than 2 points', () => {
|
||||
const { rc, curve } = fakeRoughCanvas()
|
||||
const { ctx } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'stroke', points: [{ x: 0, y: 0 }] }, [])
|
||||
expect(curve).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should draw an arc', () => {
|
||||
const { rc, arc } = fakeRoughCanvas()
|
||||
const { ctx } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'arc', x: 0, y: 0, radius: 10, startAngle: 0, endAngle: 90 }, [])
|
||||
expect(arc).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should draw text content directly and record its label box', () => {
|
||||
const { rc } = fakeRoughCanvas()
|
||||
const { ctx, fillText } = fakeCtx()
|
||||
const placed: LabelBox[] = []
|
||||
drawShape(rc, ctx, { type: 'text', x: 0, y: 0, content: 'Bonjour' }, placed)
|
||||
expect(fillText).toHaveBeenCalledWith('Bonjour', 0, 0)
|
||||
expect(placed.length).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
let nextPlayShouldReject = false
|
||||
|
||||
class FakeAudio {
|
||||
onended: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
play = vi.fn(async () => {
|
||||
if (nextPlayShouldReject) {
|
||||
nextPlayShouldReject = false
|
||||
throw new Error('autoplay blocked')
|
||||
}
|
||||
})
|
||||
}
|
||||
let lastAudio: FakeAudio | null = null
|
||||
|
||||
function createAudio(): FakeAudio {
|
||||
const audio = new FakeAudio()
|
||||
lastAudio = audio
|
||||
return audio
|
||||
}
|
||||
vi.stubGlobal('Audio', vi.fn(createAudio))
|
||||
URL.createObjectURL = vi.fn(() => 'blob:fake')
|
||||
URL.revokeObjectURL = vi.fn()
|
||||
|
||||
const { enqueueSpeech, bindSpeechAvatar, setRestingAnimation } =
|
||||
await import('../../../src/renderer/src/voice/speechQueue')
|
||||
|
||||
describe('speechQueue', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
lastAudio = null
|
||||
})
|
||||
|
||||
it('should play the avatar talking animation while audio plays, then return to the resting animation', async () => {
|
||||
const playAnimationByName = vi.fn()
|
||||
bindSpeechAvatar({
|
||||
current: { playAnimationByName, animationNames: [], playAnimation: vi.fn() }
|
||||
})
|
||||
setRestingAnimation('idle')
|
||||
|
||||
const promise = enqueueSpeech(new ArrayBuffer(4))
|
||||
expect(playAnimationByName).toHaveBeenCalledWith('talking')
|
||||
|
||||
lastAudio?.onended?.()
|
||||
await promise
|
||||
expect(playAnimationByName).toHaveBeenCalledWith('idle')
|
||||
})
|
||||
|
||||
it('should play queued items sequentially, one at a time', async () => {
|
||||
const playAnimationByName = vi.fn()
|
||||
bindSpeechAvatar({
|
||||
current: { playAnimationByName, animationNames: [], playAnimation: vi.fn() }
|
||||
})
|
||||
|
||||
const first = enqueueSpeech(new ArrayBuffer(4))
|
||||
const firstAudio = lastAudio
|
||||
const second = enqueueSpeech(new ArrayBuffer(4))
|
||||
// Le second ne doit pas encore avoir cree son propre element audio : il attend son tour.
|
||||
expect(lastAudio).toBe(firstAudio)
|
||||
|
||||
firstAudio?.onended?.()
|
||||
await first
|
||||
lastAudio?.onended?.()
|
||||
await second
|
||||
})
|
||||
|
||||
it('should resolve and continue the queue when playback errors out', async () => {
|
||||
const promise = enqueueSpeech(new ArrayBuffer(4))
|
||||
lastAudio?.onerror?.()
|
||||
await expect(promise).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('should resolve and continue the queue when play() itself rejects', async () => {
|
||||
nextPlayShouldReject = true
|
||||
const promise = enqueueSpeech(new ArrayBuffer(4))
|
||||
await expect(promise).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('should work gracefully when no avatar has been bound yet', async () => {
|
||||
bindSpeechAvatar({ current: null })
|
||||
const promise = enqueueSpeech(new ArrayBuffer(4))
|
||||
lastAudio?.onended?.()
|
||||
await expect(promise).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
|
||||
let onCaptureCallback: ((requestId: string) => void) | undefined
|
||||
const sendCameraFrameResult = vi.fn()
|
||||
const onCaptureCameraFrame = vi.fn((cb: (requestId: string) => void) => {
|
||||
onCaptureCallback = cb
|
||||
return () => {}
|
||||
})
|
||||
|
||||
const stopTrack = vi.fn()
|
||||
const getUserMedia = vi.fn(async () => ({
|
||||
getTracks: () => [{ stop: stopTrack }]
|
||||
}))
|
||||
|
||||
const { useCameraCapture } = await import('../../../src/renderer/src/voice/useCameraCapture')
|
||||
|
||||
describe('useCameraCapture()', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
onCaptureCameraFrame,
|
||||
sendCameraFrameResult
|
||||
}
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia },
|
||||
configurable: true
|
||||
})
|
||||
vi.spyOn(HTMLMediaElement.prototype, 'play').mockResolvedValue()
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
|
||||
drawImage: vi.fn()
|
||||
} as unknown as CanvasRenderingContext2D)
|
||||
HTMLCanvasElement.prototype.toDataURL = vi.fn(() => 'data:image/png;base64,abc')
|
||||
})
|
||||
|
||||
it('should capture a frame and send it back on request', async () => {
|
||||
renderHook(() => useCameraCapture())
|
||||
onCaptureCallback?.('req-1')
|
||||
await vi.waitFor(() => expect(sendCameraFrameResult).toHaveBeenCalled())
|
||||
expect(sendCameraFrameResult).toHaveBeenCalledWith('req-1', 'data:image/png;base64,abc')
|
||||
expect(stopTrack).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should send null when the camera is unavailable', async () => {
|
||||
getUserMedia.mockRejectedValueOnce(new Error('no camera'))
|
||||
renderHook(() => useCameraCapture())
|
||||
onCaptureCallback?.('req-2')
|
||||
await vi.waitFor(() => expect(sendCameraFrameResult).toHaveBeenCalled())
|
||||
expect(sendCameraFrameResult).toHaveBeenCalledWith('req-2', null)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
|
||||
let onToggleCallback: ((transcribing: boolean) => void) | undefined
|
||||
const sendMeetingAudioChunk = vi.fn()
|
||||
const sendMeetingRecordingStopped = vi.fn()
|
||||
const onToggleMeetingTranscription = vi.fn((cb: (transcribing: boolean) => void) => {
|
||||
onToggleCallback = cb
|
||||
return () => {}
|
||||
})
|
||||
|
||||
function fakeStream(): MediaStream {
|
||||
const stop = vi.fn()
|
||||
return { getTracks: () => [{ stop }] } as unknown as MediaStream
|
||||
}
|
||||
|
||||
const getUserMedia = vi.fn(async () => fakeStream())
|
||||
const enumerateDevices = vi.fn(async () => [])
|
||||
|
||||
class FakeMediaRecorder {
|
||||
static instances: FakeMediaRecorder[] = []
|
||||
state: 'recording' | 'inactive' = 'recording'
|
||||
ondataavailable: ((event: { data: Blob }) => void) | null = null
|
||||
onstop: (() => void) | null = null
|
||||
constructor(
|
||||
public stream: MediaStream,
|
||||
public options: { mimeType: string }
|
||||
) {
|
||||
FakeMediaRecorder.instances.push(this)
|
||||
}
|
||||
start(): void {
|
||||
this.state = 'recording'
|
||||
}
|
||||
stop(): void {
|
||||
this.state = 'inactive'
|
||||
this.ondataavailable?.({ data: new Blob(['chunk'], { type: 'audio/webm' }) })
|
||||
this.onstop?.()
|
||||
}
|
||||
}
|
||||
|
||||
const { useMeetingRecorder } = await import('../../../src/renderer/src/voice/useMeetingRecorder')
|
||||
|
||||
describe('useMeetingRecorder()', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
FakeMediaRecorder.instances = []
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
onToggleMeetingTranscription,
|
||||
sendMeetingAudioChunk,
|
||||
sendMeetingRecordingStopped
|
||||
}
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia, enumerateDevices },
|
||||
configurable: true
|
||||
})
|
||||
vi.stubGlobal('MediaRecorder', FakeMediaRecorder)
|
||||
})
|
||||
|
||||
it('should start recording the microphone when transcription is toggled on', async () => {
|
||||
renderHook(() => useMeetingRecorder())
|
||||
onToggleCallback?.(true)
|
||||
await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(1))
|
||||
expect(getUserMedia).toHaveBeenCalledWith({ audio: true })
|
||||
})
|
||||
|
||||
it('should give up quietly when the microphone is unavailable, without ever starting a recorder', async () => {
|
||||
getUserMedia.mockRejectedValueOnce(new Error('no mic'))
|
||||
renderHook(() => useMeetingRecorder())
|
||||
onToggleCallback?.(true)
|
||||
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
|
||||
// Rien n'a jamais demarre : stopper ensuite ne doit ni planter ni envoyer de notification pour
|
||||
// une session qui n'a jamais existe.
|
||||
expect(() => onToggleCallback?.(false)).not.toThrow()
|
||||
expect(FakeMediaRecorder.instances.length).toBe(0)
|
||||
})
|
||||
|
||||
it('should send the recorded chunk and notify the main process when stopped', async () => {
|
||||
renderHook(() => useMeetingRecorder())
|
||||
onToggleCallback?.(true)
|
||||
await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(1))
|
||||
|
||||
onToggleCallback?.(false)
|
||||
await vi.waitFor(() => expect(sendMeetingAudioChunk).toHaveBeenCalled())
|
||||
expect(sendMeetingRecordingStopped).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should start a new segment automatically instead of stopping when not asked to stop', async () => {
|
||||
renderHook(() => useMeetingRecorder())
|
||||
onToggleCallback?.(true)
|
||||
await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(1))
|
||||
|
||||
FakeMediaRecorder.instances[0]?.stop()
|
||||
await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(2))
|
||||
expect(sendMeetingRecordingStopped).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
|
||||
const bindSpeechAvatar = vi.fn()
|
||||
const enqueueSpeech = vi.fn(async () => {})
|
||||
vi.mock('../../../src/renderer/src/voice/speechQueue', () => ({ bindSpeechAvatar, enqueueSpeech }))
|
||||
|
||||
let onProactiveSpeechCallback: ((audio: ArrayBuffer) => void) | undefined
|
||||
const onProactiveSpeech = vi.fn((cb: (audio: ArrayBuffer) => void) => {
|
||||
onProactiveSpeechCallback = cb
|
||||
return () => {}
|
||||
})
|
||||
|
||||
const { useProactiveSpeech } = await import('../../../src/renderer/src/voice/useProactiveSpeech')
|
||||
|
||||
describe('useProactiveSpeech()', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = { onProactiveSpeech }
|
||||
})
|
||||
|
||||
it('should bind the avatar ref to the shared speech queue', () => {
|
||||
const avatarRef = { current: null }
|
||||
renderHook(() => useProactiveSpeech(avatarRef))
|
||||
expect(bindSpeechAvatar).toHaveBeenCalledWith(avatarRef)
|
||||
})
|
||||
|
||||
it('should enqueue any audio received via onProactiveSpeech', () => {
|
||||
renderHook(() => useProactiveSpeech({ current: null }))
|
||||
const audio = new ArrayBuffer(4)
|
||||
onProactiveSpeechCallback?.(audio)
|
||||
expect(enqueueSpeech).toHaveBeenCalledWith(audio)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,224 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import type { VoiceTurnResult } from '../../../src/shared/voice'
|
||||
|
||||
const bindSpeechAvatar = vi.fn()
|
||||
const enqueueSpeech = vi.fn(async () => {})
|
||||
const setRestingAnimation = vi.fn()
|
||||
vi.mock('../../../src/renderer/src/voice/speechQueue', () => ({
|
||||
bindSpeechAvatar,
|
||||
enqueueSpeech,
|
||||
setRestingAnimation
|
||||
}))
|
||||
|
||||
let rafCallback: ((time: number) => void) | undefined
|
||||
function tick(): void {
|
||||
const cb = rafCallback
|
||||
rafCallback = undefined
|
||||
cb?.(performance.now())
|
||||
}
|
||||
|
||||
let loudness: 'loud' | 'quiet' = 'quiet'
|
||||
|
||||
class FakeAnalyser {
|
||||
fftSize = 1024
|
||||
getByteTimeDomainData(array: Uint8Array): void {
|
||||
array.fill(loudness === 'loud' ? 255 : 128)
|
||||
}
|
||||
}
|
||||
|
||||
class FakeAudioContext {
|
||||
close = vi.fn(async () => {})
|
||||
createMediaStreamSource = vi.fn(() => ({ connect: vi.fn() }))
|
||||
createAnalyser = vi.fn(() => new FakeAnalyser())
|
||||
}
|
||||
|
||||
function fakeStream(): MediaStream {
|
||||
const stop = vi.fn()
|
||||
const endedListeners: (() => void)[] = []
|
||||
return {
|
||||
getTracks: () => [{ stop }],
|
||||
getAudioTracks: () => [
|
||||
{
|
||||
addEventListener: (_event: string, cb: () => void) => endedListeners.push(cb),
|
||||
fireEnded: () => endedListeners.forEach((cb) => cb())
|
||||
}
|
||||
]
|
||||
} as unknown as MediaStream
|
||||
}
|
||||
|
||||
const getUserMedia = vi.fn(async () => fakeStream())
|
||||
const deviceChangeListeners: (() => void)[] = []
|
||||
|
||||
class FakeMediaRecorder {
|
||||
static instances: FakeMediaRecorder[] = []
|
||||
state: 'recording' | 'inactive' = 'recording'
|
||||
ondataavailable: ((event: { data: Blob }) => void) | null = null
|
||||
onstop: (() => void) | null = null
|
||||
constructor(public stream: MediaStream) {
|
||||
FakeMediaRecorder.instances.push(this)
|
||||
}
|
||||
start(): void {
|
||||
this.state = 'recording'
|
||||
}
|
||||
stop(): void {
|
||||
this.state = 'inactive'
|
||||
this.ondataavailable?.({ data: new Blob([new Uint8Array(2000)], { type: 'audio/webm' }) })
|
||||
this.onstop?.()
|
||||
}
|
||||
}
|
||||
|
||||
const sendVoiceTurn = vi.fn(async (): Promise<VoiceTurnResult> => ({
|
||||
ok: true,
|
||||
transcript: 'bonjour',
|
||||
reply: 'salut',
|
||||
audio: new ArrayBuffer(4)
|
||||
}))
|
||||
|
||||
const { useVoiceAssistant } = await import('../../../src/renderer/src/voice/useVoiceAssistant')
|
||||
|
||||
describe('useVoiceAssistant()', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
rafCallback = undefined
|
||||
loudness = 'quiet'
|
||||
deviceChangeListeners.length = 0
|
||||
FakeMediaRecorder.instances = []
|
||||
sendVoiceTurn.mockResolvedValue({
|
||||
ok: true,
|
||||
transcript: 'bonjour',
|
||||
reply: 'salut',
|
||||
audio: new ArrayBuffer(4)
|
||||
})
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = { sendVoiceTurn }
|
||||
vi.stubGlobal('AudioContext', FakeAudioContext)
|
||||
vi.stubGlobal('MediaRecorder', FakeMediaRecorder)
|
||||
vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => {
|
||||
rafCallback = cb
|
||||
return 1
|
||||
})
|
||||
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: {
|
||||
getUserMedia,
|
||||
addEventListener: vi.fn((_event: string, cb: () => void) => {
|
||||
deviceChangeListeners.push(cb)
|
||||
}),
|
||||
removeEventListener: vi.fn()
|
||||
},
|
||||
configurable: true
|
||||
})
|
||||
})
|
||||
|
||||
it('should immediately report idle and skip microphone access when disabled', () => {
|
||||
const onStateChange = vi.fn()
|
||||
renderHook(() => useVoiceAssistant({ current: null }, false, onStateChange))
|
||||
expect(onStateChange).toHaveBeenCalledWith('idle')
|
||||
expect(getUserMedia).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should request the microphone and bind the avatar when enabled', async () => {
|
||||
renderHook(() => useVoiceAssistant({ current: null }, true))
|
||||
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
|
||||
await vi.waitFor(() => expect(bindSpeechAvatar).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('should log and not throw when the microphone is unavailable', async () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
getUserMedia.mockRejectedValueOnce(new Error('no mic'))
|
||||
renderHook(() => useVoiceAssistant({ current: null }, true))
|
||||
await vi.waitFor(() => expect(errorSpy).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('should start recording once the audio level crosses the speech threshold', async () => {
|
||||
const onStateChange = vi.fn()
|
||||
renderHook(() => useVoiceAssistant({ current: null }, true, onStateChange))
|
||||
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
|
||||
|
||||
loudness = 'loud'
|
||||
tick()
|
||||
expect(onStateChange).toHaveBeenCalledWith('recording')
|
||||
expect(FakeMediaRecorder.instances.length).toBe(1)
|
||||
})
|
||||
|
||||
it('should discard a too-short utterance without sending it to the main process', async () => {
|
||||
const onStateChange = vi.fn()
|
||||
renderHook(() => useVoiceAssistant({ current: null }, true, onStateChange))
|
||||
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
|
||||
|
||||
loudness = 'loud'
|
||||
tick()
|
||||
// Arrete immediatement : duree ecoulee bien en dessous de MIN_SPEECH_MS.
|
||||
FakeMediaRecorder.instances[0]?.stop()
|
||||
await vi.waitFor(() => expect(onStateChange).toHaveBeenCalledWith('idle'))
|
||||
expect(sendVoiceTurn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should send a long-enough utterance and play back a successful reply', async () => {
|
||||
const onStateChange = vi.fn()
|
||||
renderHook(() => useVoiceAssistant({ current: null }, true, onStateChange))
|
||||
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
|
||||
|
||||
loudness = 'loud'
|
||||
tick()
|
||||
await new Promise((resolve) => setTimeout(resolve, 310))
|
||||
FakeMediaRecorder.instances[0]?.stop()
|
||||
|
||||
await vi.waitFor(() => expect(sendVoiceTurn).toHaveBeenCalled())
|
||||
await vi.waitFor(() => expect(enqueueSpeech).toHaveBeenCalled())
|
||||
expect(onStateChange).toHaveBeenCalledWith('speaking')
|
||||
})
|
||||
|
||||
it('should return to idle without error reporting when the turn is ignored (no wake word)', async () => {
|
||||
sendVoiceTurn.mockResolvedValue({ ok: 'ignored', transcript: '' })
|
||||
const onStateChange = vi.fn()
|
||||
const onError = vi.fn()
|
||||
renderHook(() => useVoiceAssistant({ current: null }, true, onStateChange, onError))
|
||||
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
|
||||
|
||||
loudness = 'loud'
|
||||
tick()
|
||||
await new Promise((resolve) => setTimeout(resolve, 310))
|
||||
FakeMediaRecorder.instances[0]?.stop()
|
||||
|
||||
await vi.waitFor(() => expect(sendVoiceTurn).toHaveBeenCalled())
|
||||
expect(onError).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should report an error and return to idle when the turn fails', async () => {
|
||||
sendVoiceTurn.mockResolvedValue({ ok: false, error: 'API indisponible' })
|
||||
const onError = vi.fn()
|
||||
renderHook(() => useVoiceAssistant({ current: null }, true, undefined, onError))
|
||||
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
|
||||
|
||||
loudness = 'loud'
|
||||
tick()
|
||||
await new Promise((resolve) => setTimeout(resolve, 310))
|
||||
FakeMediaRecorder.instances[0]?.stop()
|
||||
|
||||
await vi.waitFor(() => expect(onError).toHaveBeenCalledWith('API indisponible'))
|
||||
})
|
||||
|
||||
it('should stop tracks and close the audio context on unmount', async () => {
|
||||
const cancelAnimationFrame = vi
|
||||
.spyOn(window, 'cancelAnimationFrame')
|
||||
.mockImplementation(() => {})
|
||||
const { unmount } = renderHook(() => useVoiceAssistant({ current: null }, true))
|
||||
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
|
||||
unmount()
|
||||
expect(cancelAnimationFrame).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should restart the microphone when the audio device list changes', async () => {
|
||||
renderHook(() => useVoiceAssistant({ current: null }, true))
|
||||
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
|
||||
getUserMedia.mockClear()
|
||||
|
||||
vi.useFakeTimers()
|
||||
deviceChangeListeners[0]?.()
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
vi.useRealTimers()
|
||||
|
||||
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled())
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcribeAudio } from '../../src/main/ai/elevenlabs'
|
||||
|
||||
describe('transcribeAudio()', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
process.env.ELEVENLABS_API_KEY = 'test-key'
|
||||
})
|
||||
|
||||
it('should return the trimmed transcript when the API call succeeds', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ text: ' Bonjour Max ' })
|
||||
} as Response)
|
||||
|
||||
const result = await transcribeAudio(Buffer.from('audio'), 'audio/webm')
|
||||
expect(result).toBe('Bonjour Max')
|
||||
})
|
||||
|
||||
it('should return an empty string when the response has no text field', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({})
|
||||
} as Response)
|
||||
|
||||
const result = await transcribeAudio(Buffer.from('audio'), 'audio/webm')
|
||||
expect(result).toBe('')
|
||||
})
|
||||
|
||||
it('should throw a descriptive error when the API call fails', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: false,
|
||||
status: 401,
|
||||
text: () => Promise.resolve('Unauthorized')
|
||||
} as Response)
|
||||
|
||||
await expect(transcribeAudio(Buffer.from('audio'), 'audio/webm')).rejects.toThrow(
|
||||
/ElevenLabs STT.*401/
|
||||
)
|
||||
})
|
||||
|
||||
it('should throw when the API key is missing', async () => {
|
||||
delete process.env.ELEVENLABS_API_KEY
|
||||
await expect(transcribeAudio(Buffer.from('audio'), 'audio/webm')).rejects.toThrow(
|
||||
/ELEVENLABS_API_KEY/
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('electron', () => ({ app: { getPath: (name: string) => `C:\\Users\\test\\${name}` } }))
|
||||
|
||||
const execFileMock = vi.fn(
|
||||
(
|
||||
_cmd: string,
|
||||
_args: string[],
|
||||
_opts: unknown,
|
||||
cb?: (err: Error | null, result: { stdout: string; stderr: string }) => void
|
||||
) => {
|
||||
const callback = typeof _opts === 'function' ? (_opts as typeof cb) : cb
|
||||
callback?.(null, { stdout: '', stderr: '' })
|
||||
}
|
||||
)
|
||||
vi.mock('child_process', () => ({ execFile: execFileMock }))
|
||||
|
||||
const { findFileByName } = await import('../../src/main/skills/windows/lib/fileSearch')
|
||||
|
||||
function mockStdout(stdout: string): void {
|
||||
execFileMock.mockImplementation(
|
||||
(
|
||||
_cmd: string,
|
||||
_args: string[],
|
||||
optsOrCb: unknown,
|
||||
cb?: (err: Error | null, result: { stdout: string; stderr: string }) => void
|
||||
) => {
|
||||
const callback = typeof optsOrCb === 'function' ? (optsOrCb as typeof cb) : cb
|
||||
callback?.(null, { stdout, stderr: '' })
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
describe('findFileByName()', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('should return null when the name has no significant word', async () => {
|
||||
expect(await findFileByName(' ')).toBeNull()
|
||||
expect(execFileMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should return null when nothing is found', async () => {
|
||||
mockStdout('')
|
||||
expect(await findFileByName('fichier introuvable')).toBeNull()
|
||||
})
|
||||
|
||||
it('should return the found path, trimmed', async () => {
|
||||
mockStdout('C:\\Users\\test\\desktop\\rapport.docx\r\n')
|
||||
expect(await findFileByName('rapport')).toBe('C:\\Users\\test\\desktop\\rapport.docx')
|
||||
})
|
||||
|
||||
it('should pick the longest word as the primary search term', async () => {
|
||||
mockStdout('C:\\found.txt')
|
||||
await findFileByName("le rapport d'activite")
|
||||
const script = execFileMock.mock.calls[0]?.[1]?.[2] as string
|
||||
expect(script).toContain("'*activite*'")
|
||||
})
|
||||
|
||||
it('should ignore French stopwords when building significant words', async () => {
|
||||
mockStdout('')
|
||||
await findFileByName('le')
|
||||
expect(execFileMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
const execFileMock = vi.fn((_cmd: string, _args: string[], cb: (err: Error | null) => void) =>
|
||||
cb(null)
|
||||
)
|
||||
vi.mock('child_process', () => ({ execFile: execFileMock }))
|
||||
|
||||
const { pressVirtualKey } = await import('../../src/main/skills/windows/lib/sendVirtualKey')
|
||||
|
||||
describe('pressVirtualKey()', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('should invoke the PowerShell script once by default', async () => {
|
||||
await pressVirtualKey(0xaf)
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
const script = execFileMock.mock.calls[0]?.[1]?.[2] as string
|
||||
expect(script).toContain('175')
|
||||
expect(script).toContain('$i -lt 1')
|
||||
})
|
||||
|
||||
it('should bake the requested repeat count into the script', async () => {
|
||||
await pressVirtualKey(0xae, 5)
|
||||
const script = execFileMock.mock.calls[0]?.[1]?.[2] as string
|
||||
expect(script).toContain('$i -lt 5')
|
||||
})
|
||||
})
|
||||
|
||||
describe('systemPaths', () => {
|
||||
const originalSystemRoot = process.env.SystemRoot
|
||||
const originalWindir = process.env.windir
|
||||
|
||||
afterEach(() => {
|
||||
if (originalSystemRoot === undefined) delete process.env.SystemRoot
|
||||
else process.env.SystemRoot = originalSystemRoot
|
||||
if (originalWindir === undefined) delete process.env.windir
|
||||
else process.env.windir = originalWindir
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
it('should fall back to C:\\Windows when neither SystemRoot nor windir is set', async () => {
|
||||
delete process.env.SystemRoot
|
||||
delete process.env.windir
|
||||
vi.resetModules()
|
||||
const { POWERSHELL_EXE } = await import('../../src/main/skills/windows/lib/systemPaths')
|
||||
expect(POWERSHELL_EXE).toContain('C:\\Windows')
|
||||
})
|
||||
|
||||
it('should use SystemRoot when set', async () => {
|
||||
process.env.SystemRoot = 'D:\\CustomWindows'
|
||||
vi.resetModules()
|
||||
const { POWERSHELL_EXE } = await import('../../src/main/skills/windows/lib/systemPaths')
|
||||
expect(POWERSHELL_EXE).toContain('D:\\CustomWindows')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const NotificationShow = vi.fn()
|
||||
class NotificationMock {
|
||||
constructor(public options: { title: string; body: string }) {}
|
||||
show = NotificationShow
|
||||
}
|
||||
vi.mock('electron', () => ({ Notification: NotificationMock }))
|
||||
|
||||
const transcribeAudio = vi.fn(async () => 'Un segment transcrit.')
|
||||
const synthesizeSpeech = vi.fn(async () => Buffer.from([1, 2, 3]))
|
||||
vi.mock('../../src/main/ai/elevenlabs', () => ({ transcribeAudio, synthesizeSpeech }))
|
||||
|
||||
const sendToRenderer = vi.fn()
|
||||
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer }))
|
||||
|
||||
const summarizeMeeting = vi.fn(async () => 'Resume de la reunion.')
|
||||
vi.mock('../../src/main/meeting/summarize', () => ({ summarizeMeeting }))
|
||||
|
||||
const saveMeeting = vi.fn()
|
||||
vi.mock('../../src/main/meeting/meetingStore', () => ({ saveMeeting }))
|
||||
|
||||
const { startMeetingSession, enqueueMeetingAudioChunk, finishMeetingSession } =
|
||||
await import('../../src/main/meeting/meetingRecorder')
|
||||
|
||||
describe('meetingRecorder', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should do nothing when a chunk arrives without an active session', async () => {
|
||||
enqueueMeetingAudioChunk(Buffer.from('audio'), 'audio/webm')
|
||||
await finishMeetingSession()
|
||||
expect(transcribeAudio).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should notify when stopping a session with no speech detected', async () => {
|
||||
startMeetingSession()
|
||||
await finishMeetingSession()
|
||||
expect(NotificationShow).toHaveBeenCalled()
|
||||
expect(summarizeMeeting).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should transcribe queued chunks in order and summarize the full session', async () => {
|
||||
startMeetingSession()
|
||||
enqueueMeetingAudioChunk(Buffer.from('audio1'), 'audio/webm')
|
||||
enqueueMeetingAudioChunk(Buffer.from('audio2'), 'audio/webm')
|
||||
await finishMeetingSession()
|
||||
|
||||
expect(transcribeAudio).toHaveBeenCalledTimes(2)
|
||||
expect(summarizeMeeting).toHaveBeenCalledWith('Un segment transcrit.\nUn segment transcrit.')
|
||||
expect(saveMeeting).toHaveBeenCalledWith(
|
||||
'Un segment transcrit.\nUn segment transcrit.',
|
||||
'Resume de la reunion.'
|
||||
)
|
||||
expect(sendToRenderer).toHaveBeenCalledWith('proactive-speech', expect.anything())
|
||||
})
|
||||
|
||||
it('should skip a segment whose transcription fails, without aborting the session', async () => {
|
||||
transcribeAudio.mockRejectedValueOnce(new Error('echec reseau'))
|
||||
startMeetingSession()
|
||||
enqueueMeetingAudioChunk(Buffer.from('audio1'), 'audio/webm')
|
||||
enqueueMeetingAudioChunk(Buffer.from('audio2'), 'audio/webm')
|
||||
await finishMeetingSession()
|
||||
expect(summarizeMeeting).toHaveBeenCalledWith('Un segment transcrit.')
|
||||
})
|
||||
|
||||
it('should notify a failure when summarizing throws', async () => {
|
||||
summarizeMeeting.mockRejectedValueOnce(new Error('echec resume'))
|
||||
startMeetingSession()
|
||||
enqueueMeetingAudioChunk(Buffer.from('audio1'), 'audio/webm')
|
||||
await finishMeetingSession()
|
||||
expect(NotificationShow).toHaveBeenCalled()
|
||||
expect(saveMeeting).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should do nothing when finishing a session that was already finished', async () => {
|
||||
startMeetingSession()
|
||||
await finishMeetingSession()
|
||||
NotificationShow.mockClear()
|
||||
await finishMeetingSession()
|
||||
expect(NotificationShow).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { getMode, setMode } from '../../src/main/mode/modeState'
|
||||
import { getModesForSkill } from '../../src/main/skills/modeMap'
|
||||
|
||||
describe('modeState', () => {
|
||||
beforeEach(() => setMode('basic'))
|
||||
|
||||
it('should default to basic mode', () => {
|
||||
expect(getMode()).toBe('basic')
|
||||
})
|
||||
|
||||
it('should persist the mode after setMode()', () => {
|
||||
setMode('coach')
|
||||
expect(getMode()).toBe('coach')
|
||||
setMode('assistant')
|
||||
expect(getMode()).toBe('assistant')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getModesForSkill()', () => {
|
||||
it('should return the modes registered for a known skill', () => {
|
||||
expect(getModesForSkill('search_web')).toEqual(['basic', 'coach', 'assistant'])
|
||||
expect(getModesForSkill('open_app')).toEqual(['basic', 'assistant'])
|
||||
expect(getModesForSkill('draw_schema')).toEqual(['coach'])
|
||||
})
|
||||
|
||||
it('should return an empty array and warn for an unregistered skill', () => {
|
||||
expect(getModesForSkill('skill_totalement_inconnu')).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,260 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
|
||||
|
||||
interface FakeSkill {
|
||||
name: string
|
||||
description: string
|
||||
parameters: object
|
||||
execute: (args: Record<string, unknown>) => Promise<string>
|
||||
}
|
||||
|
||||
let currentSkills: FakeSkill[] = []
|
||||
const getSkillsForMode = vi.fn(() => currentSkills)
|
||||
vi.mock('../../src/main/skills', () => ({ getSkillsForMode }))
|
||||
|
||||
let currentMode: 'basic' | 'coach' | 'assistant' = 'basic'
|
||||
const getMode = vi.fn(() => currentMode)
|
||||
vi.mock('../../src/main/mode/modeState', () => ({ getMode }))
|
||||
|
||||
const getMemoriesText = vi.fn(() => '')
|
||||
const getMood = vi.fn(() => 0)
|
||||
vi.mock('../../src/main/memory/store', () => ({ getMemoriesText, getMood }))
|
||||
|
||||
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 }))
|
||||
|
||||
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 {
|
||||
return { ok: true, json: () => Promise.resolve(body) } as Response
|
||||
}
|
||||
|
||||
function textMessage(content: string): unknown {
|
||||
return { choices: [{ message: { role: 'assistant', content } }] }
|
||||
}
|
||||
|
||||
function toolCallMessage(name: string, args: Record<string, unknown>, content = ''): unknown {
|
||||
return {
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
role: 'assistant',
|
||||
content,
|
||||
tool_calls: [
|
||||
{ id: 'call-1', type: 'function', function: { name, arguments: JSON.stringify(args) } }
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
describe('getAssistantReply()', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
currentSkills = []
|
||||
currentMode = 'basic'
|
||||
getSubjectLevel.mockReturnValue(null)
|
||||
process.env.OPENROUTER_API_KEY = 'test-key'
|
||||
})
|
||||
|
||||
it('should throw when the API key is missing', async () => {
|
||||
delete process.env.OPENROUTER_API_KEY
|
||||
await expect(getAssistantReply('Bonjour')).rejects.toThrow(/OPENROUTER_API_KEY/)
|
||||
})
|
||||
|
||||
it('should return a direct text reply when the model calls no tool', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(okResponse(textMessage('Bonjour, comment puis-je aider ?')))
|
||||
const reply = await getAssistantReply('Salut Max')
|
||||
expect(reply).toBe('Bonjour, comment puis-je aider ?')
|
||||
})
|
||||
|
||||
it('should execute a requested tool and use its result for the follow-up reply', async () => {
|
||||
const execute = vi.fn(async () => 'Notepad ouvert.')
|
||||
currentSkills = [
|
||||
{ name: 'open_notepad', description: 'ouvre notepad', parameters: {}, execute }
|
||||
]
|
||||
vi.mocked(fetch)
|
||||
.mockResolvedValueOnce(okResponse(toolCallMessage('open_notepad', {})))
|
||||
.mockResolvedValueOnce(okResponse(textMessage("C'est fait, le bloc-notes est ouvert.")))
|
||||
|
||||
const reply = await getAssistantReply('ouvre le bloc-notes')
|
||||
expect(execute).toHaveBeenCalled()
|
||||
expect(reply).toBe("C'est fait, le bloc-notes est ouvert.")
|
||||
})
|
||||
|
||||
it('should report an unknown/unauthorized tool without crashing', async () => {
|
||||
currentSkills = []
|
||||
vi.mocked(fetch)
|
||||
.mockResolvedValueOnce(okResponse(toolCallMessage('outil_interdit', {})))
|
||||
.mockResolvedValueOnce(okResponse(textMessage('Compris.')))
|
||||
|
||||
const reply = await getAssistantReply('fais un truc interdit')
|
||||
expect(reply).toBe('Compris.')
|
||||
})
|
||||
|
||||
it('should report a tool execution failure without crashing the turn', async () => {
|
||||
const execute = vi.fn(async () => {
|
||||
throw new Error('disque plein')
|
||||
})
|
||||
currentSkills = [
|
||||
{ name: 'create_file', description: 'cree un fichier', parameters: {}, execute }
|
||||
]
|
||||
vi.mocked(fetch)
|
||||
.mockResolvedValueOnce(okResponse(toolCallMessage('create_file', { name: 'test' })))
|
||||
.mockResolvedValueOnce(okResponse(textMessage('Echec note.')))
|
||||
|
||||
const reply = await getAssistantReply('cree un fichier')
|
||||
expect(reply).toBe('Echec note.')
|
||||
})
|
||||
|
||||
it('should transparently fall back to the secondary model when the primary one errors out', async () => {
|
||||
vi.mocked(fetch)
|
||||
.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 503,
|
||||
text: () => Promise.resolve('unavailable')
|
||||
} as Response)
|
||||
.mockResolvedValueOnce(okResponse(textMessage('Reponse du modele de secours.')))
|
||||
|
||||
const reply = await getAssistantReply('question')
|
||||
expect(reply).toBe('Reponse du modele de secours.')
|
||||
})
|
||||
|
||||
it('should treat a 200 response with no choices as a failure and try the other model', async () => {
|
||||
vi.mocked(fetch)
|
||||
.mockResolvedValueOnce(okResponse({}))
|
||||
.mockResolvedValueOnce(okResponse(textMessage('Ca marche quand meme.')))
|
||||
|
||||
const reply = await getAssistantReply('question')
|
||||
expect(reply).toBe('Ca marche quand meme.')
|
||||
})
|
||||
|
||||
it('should throw a clear error when both models fail', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: () => Promise.resolve('panne totale')
|
||||
} as Response)
|
||||
|
||||
await expect(getAssistantReply('question')).rejects.toThrow(/Aucun modele disponible/)
|
||||
})
|
||||
|
||||
it('should recover a fake tool call written as plain text instead of real tool_calls', async () => {
|
||||
const execute = vi.fn(async () => 'Notepad ouvert.')
|
||||
currentSkills = [
|
||||
{ name: 'open_notepad', description: 'ouvre notepad', parameters: {}, execute }
|
||||
]
|
||||
vi.mocked(fetch)
|
||||
.mockResolvedValueOnce(okResponse(textMessage('open_notepad\n{"text": "bonjour"}')))
|
||||
.mockResolvedValueOnce(okResponse(textMessage('Fait.')))
|
||||
|
||||
const reply = await getAssistantReply('ouvre le bloc-notes')
|
||||
expect(execute).toHaveBeenCalled()
|
||||
expect(reply).toBe('Fait.')
|
||||
})
|
||||
|
||||
it('should replace a leaked English boilerplate reply with the safe fallback message', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(
|
||||
okResponse(
|
||||
textMessage(
|
||||
'Use the results below to formulate an answer to the user question with additional information needed'
|
||||
)
|
||||
)
|
||||
)
|
||||
const reply = await getAssistantReply('question')
|
||||
expect(reply).toMatch(/bien avance avec toi/)
|
||||
})
|
||||
|
||||
it('should replace a degenerate (non-Latin) reply with the safe fallback message', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(
|
||||
okResponse(textMessage('的问题是什么呢我不知道该怎么办才好呢'))
|
||||
)
|
||||
const reply = await getAssistantReply('question')
|
||||
expect(reply).toMatch(/bien avance avec toi/)
|
||||
})
|
||||
|
||||
it('should throw once the tool-call round limit is exceeded', async () => {
|
||||
const execute = vi.fn(async () => 'ok')
|
||||
currentSkills = [{ name: 'loop_tool', description: 'boucle', parameters: {}, execute }]
|
||||
vi.mocked(fetch).mockImplementation(async () => okResponse(toolCallMessage('loop_tool', {})))
|
||||
|
||||
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())
|
||||
currentMode = 'coach'
|
||||
getSubjectLevel.mockReturnValue(null)
|
||||
process.env.OPENROUTER_API_KEY = 'test-key'
|
||||
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.')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,134 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,87 @@
|
||||
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'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,246 @@
|
||||
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/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,115 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
const clickElementByText = vi.fn(async (text: string) => text !== 'introuvable')
|
||||
const fillField = vi.fn(async (field: string) => field !== 'introuvable')
|
||||
const goBack = vi.fn(async () => true)
|
||||
const highlightText = vi.fn(async (text: string) => text !== 'introuvable')
|
||||
const navigateTo = vi.fn(async () => 'Titre de la page')
|
||||
const readPageText = vi.fn(async () => 'Contenu de la page')
|
||||
|
||||
vi.mock('../../src/main/browser/browserWindow', () => ({
|
||||
clickElementByText,
|
||||
fillField,
|
||||
goBack,
|
||||
highlightText,
|
||||
navigateTo,
|
||||
readPageText
|
||||
}))
|
||||
|
||||
const { clickBrowserElement } = await import('../../src/main/skills/browser/clickBrowserElement')
|
||||
const { fillBrowserField } = await import('../../src/main/skills/browser/fillBrowserField')
|
||||
const { goBackBrowser } = await import('../../src/main/skills/browser/goBackBrowser')
|
||||
const { highlightBrowserText } = await import('../../src/main/skills/browser/highlightBrowserText')
|
||||
const { navigateBrowser } = await import('../../src/main/skills/browser/navigateBrowser')
|
||||
const { readBrowserPage } = await import('../../src/main/skills/browser/readBrowserPage')
|
||||
|
||||
describe('click_browser_element', () => {
|
||||
it('should refuse an empty text', async () => {
|
||||
await expect(clickBrowserElement.execute({ text: '' })).rejects.toThrow(/text manquant/)
|
||||
})
|
||||
|
||||
it('should report success when the element is found and clicked', async () => {
|
||||
const result = await clickBrowserElement.execute({ text: 'Connexion' })
|
||||
expect(result).toMatch(/Clic effectue/)
|
||||
})
|
||||
|
||||
it('should report failure when no matching element is found', async () => {
|
||||
const result = await clickBrowserElement.execute({ text: 'introuvable' })
|
||||
expect(result).toMatch(/Echec/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fill_browser_field', () => {
|
||||
it('should refuse an empty field name', async () => {
|
||||
await expect(fillBrowserField.execute({ field: '', value: 'x' })).rejects.toThrow(
|
||||
/field manquant/
|
||||
)
|
||||
})
|
||||
|
||||
it('should report success and mention submission when requested', async () => {
|
||||
const result = await fillBrowserField.execute({
|
||||
field: 'email',
|
||||
value: 'a@b.com',
|
||||
submit: true
|
||||
})
|
||||
expect(result).toMatch(/rempli et formulaire valide/)
|
||||
})
|
||||
|
||||
it('should report failure when no matching field is found', async () => {
|
||||
const result = await fillBrowserField.execute({ field: 'introuvable', value: 'x' })
|
||||
expect(result).toMatch(/Echec/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('go_back_browser', () => {
|
||||
it('should report success when going back worked', async () => {
|
||||
const result = await goBackBrowser.execute({})
|
||||
expect(result).toMatch(/Retour/)
|
||||
})
|
||||
|
||||
it('should report failure when there is no previous page', async () => {
|
||||
goBack.mockResolvedValueOnce(false)
|
||||
const result = await goBackBrowser.execute({})
|
||||
expect(result).toMatch(/Echec/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('highlight_browser_text', () => {
|
||||
it('should refuse an empty text', async () => {
|
||||
await expect(highlightBrowserText.execute({ text: '' })).rejects.toThrow(/text manquant/)
|
||||
})
|
||||
|
||||
it('should report success when the text is found', async () => {
|
||||
const result = await highlightBrowserText.execute({ text: 'un passage' })
|
||||
expect(result).toMatch(/surligne/)
|
||||
})
|
||||
|
||||
it('should report failure when the text is not found', async () => {
|
||||
const result = await highlightBrowserText.execute({ text: 'introuvable' })
|
||||
expect(result).toMatch(/Echec/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('navigate_browser', () => {
|
||||
it('should refuse an empty URL', async () => {
|
||||
await expect(navigateBrowser.execute({ url: '' })).rejects.toThrow(/url manquante/)
|
||||
})
|
||||
|
||||
it('should navigate and report the page title', async () => {
|
||||
const result = await navigateBrowser.execute({ url: 'https://example.com' })
|
||||
expect(result).toMatch(/Titre de la page/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('read_browser_page', () => {
|
||||
it('should return the page text', async () => {
|
||||
const result = await readBrowserPage.execute({})
|
||||
expect(result).toBe('Contenu de la page')
|
||||
})
|
||||
|
||||
it('should report an empty/unreadable page', async () => {
|
||||
readPageText.mockResolvedValueOnce('')
|
||||
const result = await readBrowserPage.execute({})
|
||||
expect(result).toMatch(/vide ou n'a pas pu/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
const execFileMock = vi.fn((_cmd: string, _args: string[], cb: (err: Error | null) => void) =>
|
||||
cb(null)
|
||||
)
|
||||
vi.mock('child_process', () => ({ execFile: execFileMock }))
|
||||
|
||||
const { closeApp } = await import('../../src/main/skills/windows/closeApp')
|
||||
|
||||
describe('close_app', () => {
|
||||
it('should refuse to close an unrecognized application', async () => {
|
||||
const result = await closeApp.execute({ application: 'application-inexistante-xyz' })
|
||||
expect(result).toMatch(/non reconnue/)
|
||||
})
|
||||
|
||||
it('should refuse to close the Windows shell (explorer)', async () => {
|
||||
const result = await closeApp.execute({ application: 'explorateur de fichiers' })
|
||||
expect(result).toMatch(/pas autorise/)
|
||||
})
|
||||
|
||||
it('should close a recognized application by killing its process', async () => {
|
||||
const result = await closeApp.execute({ application: 'bloc-notes' })
|
||||
expect(result).toMatch(/ferme/)
|
||||
expect(execFileMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should try each override candidate for an app with multiple possible process names', async () => {
|
||||
execFileMock.mockClear()
|
||||
const result = await closeApp.execute({ application: 'calculatrice' })
|
||||
expect(result).toMatch(/ferme/)
|
||||
expect(execFileMock.mock.calls[0]?.[1]).toContain('CalculatorApp.exe')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,182 @@
|
||||
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/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,130 @@
|
||||
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/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { mkdtempSync, existsSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-documents-test-'))
|
||||
const openPath = vi.fn(async () => '')
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tempDir },
|
||||
shell: { openPath }
|
||||
}))
|
||||
|
||||
const { writeWordDocument } = await import('../../src/main/skills/windows/writeWordDocument')
|
||||
const { createPowerpoint } = await import('../../src/main/skills/windows/createPowerpoint')
|
||||
|
||||
describe('create_document', () => {
|
||||
it('should refuse empty content', async () => {
|
||||
await expect(writeWordDocument.execute({ title: 'Rapport', content: '' })).rejects.toThrow(
|
||||
/contenu manquant/
|
||||
)
|
||||
})
|
||||
|
||||
it('should write both a real .docx and .pdf file by default and open one of them', async () => {
|
||||
openPath.mockClear()
|
||||
const result = await writeWordDocument.execute({
|
||||
title: 'Rapport de test',
|
||||
content: 'Premiere ligne.\nDeuxieme ligne.'
|
||||
})
|
||||
expect(result).toMatch(/cree, enregistre et ouvert/)
|
||||
expect(existsSync(join(tempDir, 'Rapport de test.docx'))).toBe(true)
|
||||
expect(existsSync(join(tempDir, 'Rapport de test.pdf'))).toBe(true)
|
||||
expect(openPath).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should only write the requested format', async () => {
|
||||
const result = await writeWordDocument.execute({
|
||||
title: 'Uniquement PDF',
|
||||
content: 'Contenu',
|
||||
format: 'pdf'
|
||||
})
|
||||
expect(result).toMatch(/\.pdf/)
|
||||
expect(existsSync(join(tempDir, 'Uniquement PDF.docx'))).toBe(false)
|
||||
expect(existsSync(join(tempDir, 'Uniquement PDF.pdf'))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('create_powerpoint', () => {
|
||||
it('should refuse an empty slide list', async () => {
|
||||
await expect(createPowerpoint.execute({ title: 'Presentation', slides: [] })).rejects.toThrow(
|
||||
/diapositives manquantes/
|
||||
)
|
||||
})
|
||||
|
||||
it('should generate a real .pptx file from the given slides', async () => {
|
||||
openPath.mockClear()
|
||||
const result = await createPowerpoint.execute({
|
||||
title: 'Ma presentation',
|
||||
slides: [{ title: 'Introduction', content: 'Bienvenue' }, { title: 'Conclusion' }]
|
||||
})
|
||||
expect(result).toMatch(/creee, enregistree et ouverte/)
|
||||
expect(existsSync(join(tempDir, 'Ma presentation.pptx'))).toBe(true)
|
||||
expect(openPath).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,137 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
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-skillsindex-test-'))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tempDir },
|
||||
shell: { openPath: vi.fn(), openExternal: vi.fn() },
|
||||
clipboard: { readText: vi.fn(), writeText: vi.fn() },
|
||||
Notification: class {
|
||||
show = vi.fn()
|
||||
},
|
||||
desktopCapturer: { getSources: vi.fn(async () => []) },
|
||||
screen: { getPrimaryDisplay: () => ({ size: { width: 0, height: 0 } }) },
|
||||
BrowserWindow: class {
|
||||
static getAllWindows(): unknown[] {
|
||||
return []
|
||||
}
|
||||
on = vi.fn()
|
||||
webContents = { on: vi.fn(), send: vi.fn(), isLoading: () => false, once: vi.fn() }
|
||||
loadURL = vi.fn()
|
||||
loadFile = vi.fn()
|
||||
setAlwaysOnTop = vi.fn()
|
||||
maximize = vi.fn()
|
||||
},
|
||||
ipcMain: { on: vi.fn(), handle: vi.fn() },
|
||||
session: { defaultSession: { webRequest: { onHeadersReceived: vi.fn() } } }
|
||||
}))
|
||||
|
||||
// @electron-toolkit/utils fait lui-meme `require('electron')` en interne : hors runtime Electron,
|
||||
// le vrai paquet 'electron' exporte juste une chaine (chemin du binaire), ce qui casse l'interop
|
||||
// ESM/CJS pour tout import nomme ulterieur de 'electron' dans le graphe de modules. On le mocke
|
||||
// directement pour ne jamais toucher le vrai paquet.
|
||||
vi.mock('@electron-toolkit/utils', () => ({
|
||||
is: { dev: false },
|
||||
electronApp: { setAppUserModelId: vi.fn() },
|
||||
optimizer: { watchWindowShortcuts: vi.fn() }
|
||||
}))
|
||||
|
||||
const { loadSkills, getSkillsForMode, findSkill } = await import('../../src/main/skills')
|
||||
|
||||
describe('loadSkills()', () => {
|
||||
it('should load a non-empty list of skills without throwing', () => {
|
||||
const skills = loadSkills()
|
||||
expect(skills.length).toBeGreaterThan(20)
|
||||
})
|
||||
|
||||
it('should not register the same skill name twice', () => {
|
||||
const names = loadSkills().map((s) => s.name)
|
||||
expect(new Set(names).size).toBe(names.length)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getSkillsForMode()', () => {
|
||||
it('should include a coach-only skill in coach mode but not in basic mode', () => {
|
||||
const coachSkills = getSkillsForMode('coach').map((s) => s.name)
|
||||
const basicSkills = getSkillsForMode('basic').map((s) => s.name)
|
||||
expect(coachSkills).toContain('draw_schema')
|
||||
expect(basicSkills).not.toContain('draw_schema')
|
||||
})
|
||||
|
||||
it('should include a transversal skill in every mode', () => {
|
||||
for (const mode of ['basic', 'coach', 'assistant'] as const) {
|
||||
expect(getSkillsForMode(mode).map((s) => s.name)).toContain('search_web')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('findSkill()', () => {
|
||||
it('should find a registered skill by name', () => {
|
||||
expect(findSkill('search_web')?.name).toBe('search_web')
|
||||
})
|
||||
|
||||
it('should return undefined for an unknown skill name', () => {
|
||||
expect(findSkill('inexistant')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
const pressVirtualKey = vi.fn(async () => {})
|
||||
vi.mock('../../src/main/skills/windows/lib/sendVirtualKey', () => ({ pressVirtualKey }))
|
||||
|
||||
const { mediaControl } = await import('../../src/main/skills/windows/mediaControl')
|
||||
|
||||
describe('control_media_playback', () => {
|
||||
it('should send the play/pause media key', async () => {
|
||||
pressVirtualKey.mockClear()
|
||||
const result = await mediaControl.execute({ action: 'lecture_pause' })
|
||||
expect(result).toMatch(/lecture_pause/)
|
||||
expect(pressVirtualKey).toHaveBeenCalledWith(0xb3, 1)
|
||||
})
|
||||
|
||||
it('should send the next-track media key', async () => {
|
||||
pressVirtualKey.mockClear()
|
||||
await mediaControl.execute({ action: 'suivant' })
|
||||
expect(pressVirtualKey).toHaveBeenCalledWith(0xb0, 1)
|
||||
})
|
||||
|
||||
it('should throw on an invalid action', async () => {
|
||||
await expect(mediaControl.execute({ action: 'inconnue' })).rejects.toThrow(/action invalide/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
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-memory-test-'))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tempDir }
|
||||
}))
|
||||
|
||||
const { getMemoriesText, getMood } = await import('../../src/main/memory/store')
|
||||
const { rememberInfo } = await import('../../src/main/skills/memory/rememberInfo')
|
||||
const { forgetInfo } = await import('../../src/main/skills/memory/forgetInfo')
|
||||
const { adjustMoodSkill } = await import('../../src/main/skills/memory/adjustMood')
|
||||
|
||||
describe('remember_info', () => {
|
||||
it('should refuse an empty piece of information', async () => {
|
||||
await expect(rememberInfo.execute({ info: ' ' })).rejects.toThrow(/manquante/)
|
||||
})
|
||||
|
||||
it('should persist the information so it is retrievable later', async () => {
|
||||
const result = await rememberInfo.execute({ info: 'aime le cafe sans sucre' })
|
||||
expect(result).toMatch(/Retenu/)
|
||||
expect(getMemoriesText()).toMatch(/aime le cafe sans sucre/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('forget_info', () => {
|
||||
it('should refuse an empty query', async () => {
|
||||
await expect(forgetInfo.execute({ query: '' })).rejects.toThrow(/manquante/)
|
||||
})
|
||||
|
||||
it('should report when nothing matches the query', async () => {
|
||||
const result = await forgetInfo.execute({ query: 'inexistant-xyz' })
|
||||
expect(result).toMatch(/Aucune information/)
|
||||
})
|
||||
|
||||
it('should remove a previously remembered piece of information matching the query', async () => {
|
||||
await rememberInfo.execute({ info: 'deteste le lundi matin' })
|
||||
const result = await forgetInfo.execute({ query: 'lundi' })
|
||||
expect(result).toMatch(/oubliee/)
|
||||
expect(getMemoriesText()).not.toMatch(/lundi/)
|
||||
})
|
||||
|
||||
it('should clear every memory when the query is "tout"', async () => {
|
||||
await rememberInfo.execute({ info: 'un souvenir quelconque' })
|
||||
const result = await forgetInfo.execute({ query: 'tout' })
|
||||
expect(result).toMatch(/effacee/)
|
||||
expect(getMemoriesText()).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('adjust_mood', () => {
|
||||
it('should increase the mood score on a positive change', async () => {
|
||||
const before = getMood()
|
||||
await adjustMoodSkill.execute({ change: 'positif' })
|
||||
expect(getMood()).toBe(Math.min(3, before + 1))
|
||||
})
|
||||
|
||||
it('should decrease the mood score on a negative change', async () => {
|
||||
await adjustMoodSkill.execute({ change: 'negatif' })
|
||||
const before = getMood()
|
||||
await adjustMoodSkill.execute({ change: 'negatif' })
|
||||
expect(getMood()).toBe(Math.max(-3, before - 1))
|
||||
})
|
||||
|
||||
it('should never exceed the [-3, 3] bounds regardless of repeated changes', async () => {
|
||||
for (let i = 0; i < 10; i++) await adjustMoodSkill.execute({ change: 'positif' })
|
||||
expect(getMood()).toBe(3)
|
||||
for (let i = 0; i < 10; i++) await adjustMoodSkill.execute({ change: 'negatif' })
|
||||
expect(getMood()).toBe(-3)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
const execMock = vi.fn((_cmd: string, cb: (err: Error | null) => void) => cb(null))
|
||||
vi.mock('child_process', () => ({ exec: execMock }))
|
||||
|
||||
const { openApp } = await import('../../src/main/skills/windows/openApp')
|
||||
|
||||
describe('open_app', () => {
|
||||
it('should report an unrecognized application without running any command', async () => {
|
||||
execMock.mockClear()
|
||||
const result = await openApp.execute({ application: 'application-inexistante-xyz' })
|
||||
expect(result).toMatch(/non reconnue/)
|
||||
expect(execMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should open a recognized application by its registered executable', async () => {
|
||||
execMock.mockClear()
|
||||
const result = await openApp.execute({ application: 'bloc-notes' })
|
||||
expect(result).toMatch(/ouvert/)
|
||||
expect(execMock.mock.calls[0]?.[0]).toContain('notepad.exe')
|
||||
})
|
||||
|
||||
it('should be case- and whitespace-insensitive when matching the application name', async () => {
|
||||
execMock.mockClear()
|
||||
const result = await openApp.execute({ application: ' CALCULATRICE ' })
|
||||
expect(result).toMatch(/ouvert/)
|
||||
expect(execMock.mock.calls[0]?.[0]).toContain('calc.exe')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,105 @@
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
vi.mock('os', () => ({
|
||||
totalmem: () => 16 * 1024 ** 3,
|
||||
freemem: () => 4 * 1024 ** 3
|
||||
}))
|
||||
|
||||
const { systemMemory } = await import('../../src/main/skills/windows/systemMemory')
|
||||
|
||||
describe('check_system_memory', () => {
|
||||
it('should report used/total/free memory in GB computed from os.totalmem/freemem', async () => {
|
||||
const result = await systemMemory.execute({})
|
||||
expect(result).toBe('Memoire RAM : 12.0 Go utilises sur 16.0 Go (4.0 Go libres).')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
const pressVirtualKey = vi.fn(async () => {})
|
||||
vi.mock('../../src/main/skills/windows/lib/sendVirtualKey', () => ({ pressVirtualKey }))
|
||||
|
||||
const { systemVolume } = await import('../../src/main/skills/windows/systemVolume')
|
||||
|
||||
describe('control_volume', () => {
|
||||
it('should mute with a single key press regardless of steps', async () => {
|
||||
pressVirtualKey.mockClear()
|
||||
const result = await systemVolume.execute({ action: 'couper', steps: 10 })
|
||||
expect(result).toMatch(/coupe/)
|
||||
expect(pressVirtualKey).toHaveBeenCalledWith(0xad, 1)
|
||||
})
|
||||
|
||||
it('should increase volume using the default 5 steps when none is given', async () => {
|
||||
pressVirtualKey.mockClear()
|
||||
await systemVolume.execute({ action: 'augmenter' })
|
||||
expect(pressVirtualKey).toHaveBeenCalledWith(0xaf, 5)
|
||||
})
|
||||
|
||||
it('should decrease volume using the given number of steps, capped at 25', async () => {
|
||||
pressVirtualKey.mockClear()
|
||||
await systemVolume.execute({ action: 'baisser', steps: 999 })
|
||||
expect(pressVirtualKey).toHaveBeenCalledWith(0xae, 25)
|
||||
})
|
||||
|
||||
it('should throw on an invalid action', async () => {
|
||||
await expect(systemVolume.execute({ action: 'danser' })).rejects.toThrow(/action invalide/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { mkdtempSync, existsSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-screenshot-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: 1920, height: 1080 } }) }
|
||||
}))
|
||||
|
||||
const { takeScreenshot } = await import('../../src/main/skills/windows/takeScreenshot')
|
||||
|
||||
describe('take_screenshot', () => {
|
||||
it('should capture the primary screen and save it as a real PNG file', async () => {
|
||||
const result = await takeScreenshot.execute({})
|
||||
expect(result).toMatch(/Capture d'ecran enregistree/)
|
||||
expect(result).toMatch(/\.png/)
|
||||
const match = /: (.+\.png)\./.exec(result)
|
||||
expect(match?.[1] ? existsSync(match[1]) : false).toBe(true)
|
||||
})
|
||||
|
||||
it('should throw when no screen source is detected', async () => {
|
||||
getSources.mockResolvedValueOnce([])
|
||||
await expect(takeScreenshot.execute({})).rejects.toThrow(/Aucun ecran detecte/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
const collectTranslatableElements = vi.fn(async () => [{ id: 't0', text: 'Hello' }])
|
||||
const applyTranslations = vi.fn(async () => {})
|
||||
vi.mock('../../src/main/browser/browserWindow', () => ({
|
||||
collectTranslatableElements,
|
||||
applyTranslations
|
||||
}))
|
||||
|
||||
const translateTexts = vi.fn(async () => ['Bonjour'])
|
||||
vi.mock('../../src/main/ai/translate', () => ({ translateTexts }))
|
||||
|
||||
const { translateBrowserPage } = await import('../../src/main/skills/browser/translateBrowserPage')
|
||||
|
||||
describe('translate_browser_page', () => {
|
||||
it('should refuse an empty language', async () => {
|
||||
await expect(translateBrowserPage.execute({ language: '' })).rejects.toThrow(
|
||||
/language manquante/
|
||||
)
|
||||
})
|
||||
|
||||
it('should report no translatable text when the page is empty', async () => {
|
||||
collectTranslatableElements.mockResolvedValueOnce([])
|
||||
const result = await translateBrowserPage.execute({ language: 'anglais' })
|
||||
expect(result).toMatch(/Aucun texte traduisible/)
|
||||
expect(translateTexts).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should translate and apply the translated text to the page', async () => {
|
||||
const result = await translateBrowserPage.execute({ language: 'francais' })
|
||||
expect(translateTexts).toHaveBeenCalledWith(['Hello'], 'francais')
|
||||
expect(applyTranslations).toHaveBeenCalledWith([{ id: 't0', text: 'Bonjour' }])
|
||||
expect(result).toMatch(/Page traduite en francais \(1 elements remplaces\)/)
|
||||
})
|
||||
|
||||
it('should fall back to the original text when a translation is missing', async () => {
|
||||
translateTexts.mockResolvedValueOnce([])
|
||||
await translateBrowserPage.execute({ language: 'francais' })
|
||||
expect(applyTranslations).toHaveBeenCalledWith([{ id: 't0', text: 'Hello' }])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,159 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
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 } }) }
|
||||
}))
|
||||
vi.mock('../../src/main/windowBridge', () => ({ requestCameraFrame, 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
|
||||
// plutot que de changer le point d'entree importe par le code de production pour contourner ce bug
|
||||
// tiers.
|
||||
vi.mock('pdf-parse', () => ({ default: vi.fn(async () => ({ text: 'Texte extrait du PDF' })) }))
|
||||
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')
|
||||
const { saveMeeting } = await import('../../src/main/meeting/meetingStore')
|
||||
const { extractText } = await import('../../src/main/skills/documents/extractText')
|
||||
|
||||
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', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
})
|
||||
|
||||
it('should refuse an empty query', async () => {
|
||||
await expect(searchWeb.execute({ query: '' })).rejects.toThrow(/query manquante/)
|
||||
})
|
||||
|
||||
it('should parse DuckDuckGo HTML results into a readable list', async () => {
|
||||
const html = `
|
||||
<div class="result web-result">
|
||||
<div class="result__body">
|
||||
<a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com">Titre du resultat</a>
|
||||
<a class="result__title"><span>Titre du resultat</span></a>
|
||||
<div class="result__snippet">Un extrait pertinent.</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
vi.mocked(fetch).mockResolvedValue({ ok: true, text: () => Promise.resolve(html) } as Response)
|
||||
const result = await searchWeb.execute({ query: 'test' })
|
||||
expect(result).toMatch(/example\.com/)
|
||||
})
|
||||
|
||||
it('should report no results when nothing matches', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: true,
|
||||
text: () => Promise.resolve('<html></html>')
|
||||
} as Response)
|
||||
const result = await searchWeb.execute({ query: 'test' })
|
||||
expect(result).toMatch(/Aucun resultat/)
|
||||
})
|
||||
|
||||
it('should throw when the request fails', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({ ok: false, status: 503 } as Response)
|
||||
await expect(searchWeb.execute({ query: 'test' })).rejects.toThrow(/echouee/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('get_last_meeting_summary', () => {
|
||||
it('should report no session recorded yet', async () => {
|
||||
const result = await getLastMeetingSummarySkill.execute({})
|
||||
expect(result).toMatch(/Aucune session/)
|
||||
})
|
||||
|
||||
it('should return the last saved meeting summary', async () => {
|
||||
saveMeeting('transcript complet', 'resume de la reunion')
|
||||
const result = await getLastMeetingSummarySkill.execute({})
|
||||
expect(result).toMatch(/resume de la reunion/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('extractText()', () => {
|
||||
it('should read a plain text file as-is', async () => {
|
||||
const filePath = join(tempDir, 'note.txt')
|
||||
writeFileSync(filePath, 'Contenu simple')
|
||||
const doc = await extractText(filePath)
|
||||
expect(doc.text).toBe('Contenu simple')
|
||||
expect(doc.truncated).toBe(false)
|
||||
})
|
||||
|
||||
it('should truncate content longer than the max length', async () => {
|
||||
const filePath = join(tempDir, 'long.txt')
|
||||
writeFileSync(filePath, 'a'.repeat(20000))
|
||||
const doc = await extractText(filePath)
|
||||
expect(doc.truncated).toBe(true)
|
||||
expect(doc.text.length).toBe(12000)
|
||||
})
|
||||
|
||||
it('should throw for an unsupported file extension', async () => {
|
||||
const filePath = join(tempDir, 'image.png')
|
||||
writeFileSync(filePath, 'binaire')
|
||||
await expect(extractText(filePath)).rejects.toThrow(/non supporte/)
|
||||
})
|
||||
|
||||
it('should extract text from a .pdf file via pdf-parse', async () => {
|
||||
const filePath = join(tempDir, 'document.pdf')
|
||||
writeFileSync(filePath, 'contenu-binaire-simule')
|
||||
const doc = await extractText(filePath)
|
||||
expect(doc.text).toBe('Texte extrait du PDF')
|
||||
})
|
||||
|
||||
it('should extract text from a .docx file via mammoth', async () => {
|
||||
const filePath = join(tempDir, 'document.docx')
|
||||
writeFileSync(filePath, 'contenu-binaire-simule')
|
||||
const doc = await extractText(filePath)
|
||||
expect(doc.text).toBe('Texte extrait du docx')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,140 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const openPath = vi.fn(async () => '')
|
||||
vi.mock('electron', () => ({
|
||||
shell: { openPath },
|
||||
app: { getPath: (name: string) => `C:\\Users\\test\\${name}` }
|
||||
}))
|
||||
|
||||
const writeFileSyncMock = vi.fn()
|
||||
const existsSyncMock = vi.fn(() => false)
|
||||
const mkdirSyncMock = vi.fn()
|
||||
const statSyncMock = vi.fn(() => ({ isDirectory: () => false }))
|
||||
vi.mock('fs', () => ({
|
||||
writeFileSync: writeFileSyncMock,
|
||||
existsSync: existsSyncMock,
|
||||
mkdirSync: mkdirSyncMock,
|
||||
statSync: statSyncMock
|
||||
}))
|
||||
|
||||
const execFileMock = vi.fn((_cmd: string, _args: string[], cb: (err: Error | null) => void) =>
|
||||
cb(null)
|
||||
)
|
||||
vi.mock('child_process', () => ({ execFile: execFileMock }))
|
||||
|
||||
const findFileByName = vi.fn(async (name: string) =>
|
||||
name.includes('introuvable') ? null : `C:\\Users\\test\\desktop\\${name}.txt`
|
||||
)
|
||||
vi.mock('../../src/main/skills/windows/lib/fileSearch', () => ({ findFileByName }))
|
||||
|
||||
const { createFile } = await import('../../src/main/skills/windows/createFile')
|
||||
const { createFolder } = await import('../../src/main/skills/windows/createFolder')
|
||||
const { deleteFileOrFolder } = await import('../../src/main/skills/windows/deleteFileOrFolder')
|
||||
const { printFile } = await import('../../src/main/skills/windows/printFile')
|
||||
const { searchFile } = await import('../../src/main/skills/windows/searchFile')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
existsSyncMock.mockReturnValue(false)
|
||||
statSyncMock.mockReturnValue({ isDirectory: () => false })
|
||||
findFileByName.mockImplementation(async (name: string) =>
|
||||
name.includes('introuvable') ? null : `C:\\Users\\test\\desktop\\${name}.txt`
|
||||
)
|
||||
})
|
||||
|
||||
describe('create_file', () => {
|
||||
it('should refuse an empty name', async () => {
|
||||
await expect(createFile.execute({ name: ' ' })).rejects.toThrow(/nom manquant/)
|
||||
})
|
||||
|
||||
it('should sanitize illegal characters, write the file and open it', async () => {
|
||||
const result = await createFile.execute({ name: 'note<test>', content: 'hello' })
|
||||
expect(result).toMatch(/Fichier cree et ouvert/)
|
||||
expect(writeFileSyncMock).toHaveBeenCalled()
|
||||
expect(openPath).toHaveBeenCalled()
|
||||
expect(String(writeFileSyncMock.mock.calls[0]?.[0])).not.toMatch(/[<>]/)
|
||||
})
|
||||
|
||||
it('should append .txt when the name has no extension', async () => {
|
||||
await createFile.execute({ name: 'sansextension' })
|
||||
expect(String(writeFileSyncMock.mock.calls[0]?.[0])).toMatch(/sansextension\.txt$/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('create_folder', () => {
|
||||
it('should refuse an empty name', async () => {
|
||||
await expect(createFolder.execute({ name: '' })).rejects.toThrow(/nom manquant/)
|
||||
})
|
||||
|
||||
it('should report when the folder already exists without creating it again', async () => {
|
||||
existsSyncMock.mockReturnValue(true)
|
||||
const result = await createFolder.execute({ name: 'existant' })
|
||||
expect(result).toMatch(/existe deja/)
|
||||
expect(mkdirSyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should create and open a new folder', async () => {
|
||||
const result = await createFolder.execute({ name: 'nouveau' })
|
||||
expect(result).toMatch(/Dossier cree et ouvert/)
|
||||
expect(mkdirSyncMock).toHaveBeenCalled()
|
||||
expect(openPath).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('delete_file', () => {
|
||||
it('should refuse an empty name', async () => {
|
||||
await expect(deleteFileOrFolder.execute({ name: '' })).rejects.toThrow(/nom manquant/)
|
||||
})
|
||||
|
||||
it('should report when nothing is found', async () => {
|
||||
const result = await deleteFileOrFolder.execute({ name: 'introuvable' })
|
||||
expect(result).toMatch(/Aucun fichier ou dossier/)
|
||||
})
|
||||
|
||||
it('should refuse to delete a protected location (drive root)', async () => {
|
||||
findFileByName.mockResolvedValue('C:\\')
|
||||
const result = await deleteFileOrFolder.execute({ name: 'quelquechose' })
|
||||
expect(result).toMatch(/protege/)
|
||||
expect(execFileMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should send a found file to the recycle bin', async () => {
|
||||
const result = await deleteFileOrFolder.execute({ name: 'document' })
|
||||
expect(result).toMatch(/corbeille/)
|
||||
expect(execFileMock).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('print_file', () => {
|
||||
it('should refuse an empty name', async () => {
|
||||
await expect(printFile.execute({ name: '' })).rejects.toThrow(/nom manquant/)
|
||||
})
|
||||
|
||||
it('should report when no file is found', async () => {
|
||||
const result = await printFile.execute({ name: 'introuvable' })
|
||||
expect(result).toMatch(/Aucun fichier/)
|
||||
})
|
||||
|
||||
it('should launch printing for a found file', async () => {
|
||||
const result = await printFile.execute({ name: 'rapport' })
|
||||
expect(result).toMatch(/Impression lancee/)
|
||||
expect(execFileMock).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('search_file', () => {
|
||||
it('should refuse an empty name', async () => {
|
||||
await expect(searchFile.execute({ name: '' })).rejects.toThrow(/nom manquant/)
|
||||
})
|
||||
|
||||
it('should report when nothing is found', async () => {
|
||||
const result = await searchFile.execute({ name: 'introuvable' })
|
||||
expect(result).toMatch(/Aucun fichier ou dossier/)
|
||||
})
|
||||
|
||||
it('should find and open a matching file', async () => {
|
||||
const result = await searchFile.execute({ name: 'photo' })
|
||||
expect(result).toMatch(/Trouve et ouvert/)
|
||||
expect(openPath).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { EventEmitter } from 'node:events'
|
||||
|
||||
const readText = vi.fn(async () => '')
|
||||
const writeText = vi.fn(async () => {})
|
||||
const openExternal = vi.fn(async () => {})
|
||||
const NotificationShow = vi.fn()
|
||||
class NotificationMock {
|
||||
show = NotificationShow
|
||||
}
|
||||
vi.mock('electron', () => ({
|
||||
clipboard: { readText, writeText },
|
||||
shell: { openExternal },
|
||||
Notification: NotificationMock
|
||||
}))
|
||||
|
||||
const writeFileSyncMock = vi.fn()
|
||||
const mkdtempSyncMock = vi.fn(() => 'C:\\temp\\forge-avatar-xyz')
|
||||
vi.mock('fs', () => ({ writeFileSync: writeFileSyncMock, mkdtempSync: mkdtempSyncMock }))
|
||||
|
||||
const execFileMock = vi.fn(() => new EventEmitter())
|
||||
vi.mock('child_process', () => ({ execFile: execFileMock }))
|
||||
|
||||
const synthesizeSpeech = vi.fn(async () => new Uint8Array([1, 2, 3]).buffer as unknown as Buffer)
|
||||
vi.mock('../../src/main/ai/elevenlabs', () => ({ synthesizeSpeech }))
|
||||
const sendToRenderer = vi.fn()
|
||||
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer }))
|
||||
|
||||
const { clipboardSkill } = await import('../../src/main/skills/windows/clipboard')
|
||||
const { showNotification } = await import('../../src/main/skills/windows/showNotification')
|
||||
const { playMusic } = await import('../../src/main/skills/windows/playMusic')
|
||||
const { reminder } = await import('../../src/main/skills/windows/reminder')
|
||||
const { openNotepad } = await import('../../src/main/skills/windows/openNotepad')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('clipboard', () => {
|
||||
it('should refuse an invalid action', async () => {
|
||||
await expect(clipboardSkill.execute({ action: 'danser' })).rejects.toThrow(/action invalide/)
|
||||
})
|
||||
|
||||
it('should report an empty clipboard', async () => {
|
||||
readText.mockResolvedValue('')
|
||||
const result = await clipboardSkill.execute({ action: 'lire' })
|
||||
expect(result).toMatch(/vide/)
|
||||
})
|
||||
|
||||
it('should read non-empty clipboard content', async () => {
|
||||
readText.mockResolvedValue('Bonjour')
|
||||
const result = await clipboardSkill.execute({ action: 'lire' })
|
||||
expect(result).toMatch(/Bonjour/)
|
||||
})
|
||||
|
||||
it('should refuse to copy an empty text', async () => {
|
||||
await expect(clipboardSkill.execute({ action: 'copier', text: '' })).rejects.toThrow(
|
||||
/texte manquant/
|
||||
)
|
||||
})
|
||||
|
||||
it('should copy a given text to the clipboard', async () => {
|
||||
const result = await clipboardSkill.execute({ action: 'copier', text: 'Salut' })
|
||||
expect(result).toMatch(/copie/)
|
||||
expect(writeText).toHaveBeenCalledWith('Salut')
|
||||
})
|
||||
})
|
||||
|
||||
describe('show_notification', () => {
|
||||
it('should refuse an empty message', async () => {
|
||||
await expect(showNotification.execute({ message: '' })).rejects.toThrow(/message manquant/)
|
||||
})
|
||||
|
||||
it('should show a notification with the given title and message', async () => {
|
||||
const result = await showNotification.execute({ title: 'Alerte', message: 'Ca a marche' })
|
||||
expect(result).toMatch(/affichee/)
|
||||
expect(NotificationShow).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('play_music', () => {
|
||||
it('should refuse an empty query', async () => {
|
||||
await expect(playMusic.execute({ query: '' })).rejects.toThrow(/requete manquante/)
|
||||
})
|
||||
|
||||
it('should open Spotify with the encoded search query', async () => {
|
||||
const result = await playMusic.execute({ query: 'Daft Punk' })
|
||||
expect(result).toMatch(/Spotify ouvert/)
|
||||
expect(openExternal).toHaveBeenCalledWith('spotify:search:Daft%20Punk')
|
||||
})
|
||||
|
||||
it('should fall back to the web player when the Spotify URI fails', async () => {
|
||||
openExternal.mockRejectedValueOnce(new Error('no spotify'))
|
||||
const result = await playMusic.execute({ query: 'Daft Punk' })
|
||||
expect(result).toMatch(/web ouvert/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('set_reminder', () => {
|
||||
it('should refuse an invalid delay', async () => {
|
||||
await expect(reminder.execute({ minutes: 0, message: 'test' })).rejects.toThrow(
|
||||
/minutes invalide/
|
||||
)
|
||||
})
|
||||
|
||||
it('should refuse an empty message', async () => {
|
||||
await expect(reminder.execute({ minutes: 5, message: '' })).rejects.toThrow(/message manquant/)
|
||||
})
|
||||
|
||||
it('should confirm the reminder is scheduled', async () => {
|
||||
const result = await reminder.execute({ minutes: 10, message: 'Pause cafe' })
|
||||
expect(result).toMatch(/Rappel programme dans 10 minute/)
|
||||
expect(result).toMatch(/Pause cafe/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('open_notepad', () => {
|
||||
it('should open an empty notepad when no text is given', async () => {
|
||||
const result = await openNotepad.execute({})
|
||||
expect(result).toBe('Bloc-notes ouvert.')
|
||||
expect(writeFileSyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should pre-fill a temp file and open it when text is given', async () => {
|
||||
const result = await openNotepad.execute({ text: 'Mon brouillon' })
|
||||
expect(result).toMatch(/texte demande/)
|
||||
expect(writeFileSyncMock).toHaveBeenCalledWith(expect.any(String), 'Mon brouillon', 'utf-8')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,118 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const execFileMock = vi.fn(
|
||||
(
|
||||
_cmd: string,
|
||||
_args: string[],
|
||||
_opts: unknown,
|
||||
cb?: (err: Error | null, result: unknown) => void
|
||||
) => {
|
||||
const callback = typeof _opts === 'function' ? (_opts as typeof cb) : cb
|
||||
callback?.(null, { stdout: '{}', stderr: '' })
|
||||
}
|
||||
)
|
||||
vi.mock('child_process', () => ({ execFile: execFileMock }))
|
||||
|
||||
const { systemStatus } = await import('../../src/main/skills/windows/systemStatus')
|
||||
const { systemStorage } = await import('../../src/main/skills/windows/systemStorage')
|
||||
const { checkInternet } = await import('../../src/main/skills/windows/checkInternet')
|
||||
const { lockScreen } = await import('../../src/main/skills/windows/lockScreen')
|
||||
const { emptyRecycleBin } = await import('../../src/main/skills/windows/emptyRecycleBin')
|
||||
|
||||
function mockStdout(json: unknown): void {
|
||||
execFileMock.mockImplementation(
|
||||
(
|
||||
_cmd: string,
|
||||
_args: string[],
|
||||
optsOrCb: unknown,
|
||||
cb?: (err: Error | null, result: unknown) => void
|
||||
) => {
|
||||
const callback = typeof optsOrCb === 'function' ? (optsOrCb as typeof cb) : cb
|
||||
callback?.(null, { stdout: JSON.stringify(json), stderr: '' })
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('check_battery_and_cpu', () => {
|
||||
it('should report no battery for a desktop computer', async () => {
|
||||
mockStdout({ BatteryPercent: null, Charging: null, CpuPercent: 42 })
|
||||
const result = await systemStatus.execute({})
|
||||
expect(result).toMatch(/Pas de batterie detectee/)
|
||||
expect(result).toMatch(/42%/)
|
||||
})
|
||||
|
||||
it('should report battery level and charging state for a laptop', async () => {
|
||||
mockStdout({ BatteryPercent: 80, Charging: true, CpuPercent: 10 })
|
||||
const result = await systemStatus.execute({})
|
||||
expect(result).toMatch(/Batterie a 80%/)
|
||||
expect(result).toMatch(/en charge/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('check_storage', () => {
|
||||
it('should report usage for a single drive', async () => {
|
||||
mockStdout({ DriveLetter: 'C', SizeGB: 500, FreeGB: 100 })
|
||||
const result = await systemStorage.execute({})
|
||||
expect(result).toMatch(/Disque C : 400\.0 Go utilises sur 500 Go \(100 Go libres\)/)
|
||||
})
|
||||
|
||||
it('should report usage for multiple drives', async () => {
|
||||
mockStdout([
|
||||
{ DriveLetter: 'C', SizeGB: 500, FreeGB: 100 },
|
||||
{ DriveLetter: 'D', SizeGB: 1000, FreeGB: 900 }
|
||||
])
|
||||
const result = await systemStorage.execute({})
|
||||
expect(result).toMatch(/Disque C/)
|
||||
expect(result).toMatch(/Disque D/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('check_internet_connection', () => {
|
||||
it('should report a working connection with its local IP', async () => {
|
||||
mockStdout({ Connected: true, Ip: '192.168.1.10' })
|
||||
const result = await checkInternet.execute({})
|
||||
expect(result).toMatch(/Internet fonctionne/)
|
||||
expect(result).toMatch(/192\.168\.1\.10/)
|
||||
})
|
||||
|
||||
it('should report no connection', async () => {
|
||||
mockStdout({ Connected: false, Ip: null })
|
||||
const result = await checkInternet.execute({})
|
||||
expect(result).toMatch(/Pas de connexion internet/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('lock_screen', () => {
|
||||
it('should invoke the lock command and confirm immediately', async () => {
|
||||
const result = await lockScreen.execute({})
|
||||
expect(result).toBe('Ecran verrouille.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('empty_recycle_bin', () => {
|
||||
it('should confirm the recycle bin was emptied', async () => {
|
||||
mockStdout({})
|
||||
const result = await emptyRecycleBin.execute({})
|
||||
expect(result).toBe('Corbeille videe.')
|
||||
})
|
||||
|
||||
it('should still confirm even if the underlying command fails (bin already empty)', async () => {
|
||||
execFileMock.mockImplementation(
|
||||
(
|
||||
_cmd: string,
|
||||
_args: string[],
|
||||
optsOrCb: unknown,
|
||||
cb?: (err: Error | null, result: unknown) => void
|
||||
) => {
|
||||
const callback = typeof optsOrCb === 'function' ? (optsOrCb as typeof cb) : cb
|
||||
callback?.(new Error('already empty'), null)
|
||||
}
|
||||
)
|
||||
const result = await emptyRecycleBin.execute({})
|
||||
expect(result).toBe('Corbeille videe.')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { summarizeMeeting } from '../../src/main/meeting/summarize'
|
||||
|
||||
describe('summarizeMeeting()', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
process.env.OPENROUTER_API_KEY = 'test-key'
|
||||
})
|
||||
|
||||
it('should throw when the API key is missing', async () => {
|
||||
delete process.env.OPENROUTER_API_KEY
|
||||
await expect(summarizeMeeting('court transcript')).rejects.toThrow(/OPENROUTER_API_KEY/)
|
||||
})
|
||||
|
||||
it('should summarize a short transcript in a single call', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ choices: [{ message: { content: 'Resume concis.' } }] })
|
||||
} as Response)
|
||||
|
||||
const summary = await summarizeMeeting('Un court transcript de reunion.')
|
||||
expect(summary).toBe('Resume concis.')
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should throw a descriptive error when the API call fails', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: () => Promise.resolve('panne')
|
||||
} as Response)
|
||||
await expect(summarizeMeeting('transcript')).rejects.toThrow(/Resume echoue/)
|
||||
})
|
||||
|
||||
it('should split a long transcript into chunks, summarize each, then merge', async () => {
|
||||
const longTranscript = 'a'.repeat(25000)
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({ choices: [{ message: { content: 'Resume partiel ou final.' } }] })
|
||||
} as Response)
|
||||
|
||||
const summary = await summarizeMeeting(longTranscript)
|
||||
expect(summary).toBe('Resume partiel ou final.')
|
||||
// 25000 chars / 12000 max => 3 chunks + 1 fusion = 4 appels.
|
||||
expect(fetch).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { extractFakeToolCall, extractBareJsonRetry } from '../../src/main/ai/toolCallRecovery'
|
||||
|
||||
describe('extractFakeToolCall()', () => {
|
||||
it('should recover a tool call written as plain text with a known tool name', () => {
|
||||
const content = 'generate_course_plan\n{"subject": "algebre", "objective": "resoudre"}'
|
||||
const result = extractFakeToolCall(content, ['generate_course_plan', 'research_topic'])
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.name).toBe('generate_course_plan')
|
||||
expect(JSON.parse(result?.arguments ?? '{}')).toEqual({
|
||||
subject: 'algebre',
|
||||
objective: 'resoudre'
|
||||
})
|
||||
})
|
||||
|
||||
it('should return null when no known tool name appears in the text', () => {
|
||||
const content = 'Je vais y reflechir et te revenir avec une reponse.'
|
||||
expect(extractFakeToolCall(content, ['generate_course_plan'])).toBeNull()
|
||||
})
|
||||
|
||||
it('should return null when the tool name is present but the JSON is malformed', () => {
|
||||
const content = 'generate_course_plan\n{subject: algebre'
|
||||
expect(extractFakeToolCall(content, ['generate_course_plan'])).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('extractBareJsonRetry()', () => {
|
||||
it('should recover a bare JSON object as a retry of the given tool, with no tool name in the text', () => {
|
||||
const content = 'Voici une nouvelle tentative :\n{"subject": "algebre", "module": "fractions"}'
|
||||
const result = extractBareJsonRetry(content, 'write_module_content')
|
||||
expect(result).toEqual({
|
||||
name: 'write_module_content',
|
||||
arguments: '{"subject": "algebre", "module": "fractions"}'
|
||||
})
|
||||
})
|
||||
|
||||
it('should return null when the text contains no JSON object at all', () => {
|
||||
expect(
|
||||
extractBareJsonRetry('Je ne sais pas comment continuer.', 'write_module_content')
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { translateTexts } from '../../src/main/ai/translate'
|
||||
|
||||
describe('translateTexts()', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
process.env.OPENROUTER_API_KEY = 'test-key'
|
||||
})
|
||||
|
||||
it('should return the translated array when the API call succeeds', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
choices: [{ message: { content: '["Bonjour", "Au revoir"]' } }]
|
||||
})
|
||||
} as Response)
|
||||
|
||||
const result = await translateTexts(['Hello', 'Goodbye'], 'francais')
|
||||
expect(result).toEqual(['Bonjour', 'Au revoir'])
|
||||
})
|
||||
|
||||
it('should extract a JSON array even when the model wraps it in extra text', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
choices: [{ message: { content: 'Voici le resultat:\n["Salut"]\nVoila.' } }]
|
||||
})
|
||||
} as Response)
|
||||
|
||||
const result = await translateTexts(['Hi'], 'francais')
|
||||
expect(result).toEqual(['Salut'])
|
||||
})
|
||||
|
||||
it('should throw when the API call fails', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: () => Promise.resolve('Internal error')
|
||||
} as Response)
|
||||
|
||||
await expect(translateTexts(['Hello'], 'francais')).rejects.toThrow(/Traduction echouee/)
|
||||
})
|
||||
|
||||
it('should throw when the API key is missing', async () => {
|
||||
delete process.env.OPENROUTER_API_KEY
|
||||
await expect(translateTexts(['Hello'], 'francais')).rejects.toThrow(/OPENROUTER_API_KEY/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { EventEmitter } from 'node:events'
|
||||
|
||||
class AutoUpdaterMock extends EventEmitter {
|
||||
autoDownload = false
|
||||
autoInstallOnAppQuit = false
|
||||
checkForUpdates = vi.fn(async () => {})
|
||||
}
|
||||
const autoUpdater = new AutoUpdaterMock()
|
||||
vi.mock('electron-updater', () => ({ autoUpdater }))
|
||||
|
||||
const sendToRenderer = vi.fn()
|
||||
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer }))
|
||||
|
||||
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
|
||||
|
||||
const { startAutoUpdater } = await import('../../src/main/updater')
|
||||
|
||||
describe('startAutoUpdater()', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
it('should enable auto download and install-on-quit', () => {
|
||||
startAutoUpdater()
|
||||
expect(autoUpdater.autoDownload).toBe(true)
|
||||
expect(autoUpdater.autoInstallOnAppQuit).toBe(true)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should notify the renderer when an update is available', () => {
|
||||
startAutoUpdater()
|
||||
autoUpdater.emit('update-available')
|
||||
expect(sendToRenderer).toHaveBeenCalledWith('update:available')
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should notify the renderer when an update is downloaded and ready', () => {
|
||||
startAutoUpdater()
|
||||
autoUpdater.emit('update-downloaded')
|
||||
expect(sendToRenderer).toHaveBeenCalledWith('update:ready')
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should check for updates immediately on start', () => {
|
||||
startAutoUpdater()
|
||||
expect(autoUpdater.checkForUpdates).toHaveBeenCalledTimes(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should check for updates again after the periodic interval elapses', async () => {
|
||||
startAutoUpdater()
|
||||
autoUpdater.checkForUpdates.mockClear()
|
||||
await vi.advanceTimersByTimeAsync(4 * 60 * 60 * 1000)
|
||||
expect(autoUpdater.checkForUpdates).toHaveBeenCalledTimes(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: true } }))
|
||||
const { logger } = await import('../../src/main/utils/logger')
|
||||
const { SECURE_WEB_PREFERENCES, blockExternalNavigation } =
|
||||
await import('../../src/main/utils/windowSecurity')
|
||||
|
||||
describe('logger', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('should forward debug() to console.log when in dev mode', () => {
|
||||
logger.debug('hello', 42)
|
||||
expect(console.log).toHaveBeenCalledWith('hello', 42)
|
||||
})
|
||||
|
||||
it('should forward warn() to console.warn', () => {
|
||||
logger.warn('attention')
|
||||
expect(console.warn).toHaveBeenCalledWith('attention')
|
||||
})
|
||||
|
||||
it('should forward error() to console.error', () => {
|
||||
logger.error('echec')
|
||||
expect(console.error).toHaveBeenCalledWith('echec')
|
||||
})
|
||||
})
|
||||
|
||||
describe('SECURE_WEB_PREFERENCES', () => {
|
||||
it('should always require contextIsolation and disable nodeIntegration', () => {
|
||||
expect(SECURE_WEB_PREFERENCES).toEqual({
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
// sandbox:false ici — voir le commentaire dans windowSecurity.ts (casse contextBridge sur
|
||||
// cette machine, cause exacte non identifiee).
|
||||
sandbox: false
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('blockExternalNavigation()', () => {
|
||||
it('should prevent navigation to a non-local URL', () => {
|
||||
let handler: ((event: { preventDefault: () => void }, url: string) => void) | undefined
|
||||
const window = {
|
||||
webContents: {
|
||||
on: (event: string, cb: typeof handler) => {
|
||||
if (event === 'will-navigate') handler = cb
|
||||
}
|
||||
}
|
||||
}
|
||||
blockExternalNavigation(window as never)
|
||||
const preventDefault = vi.fn()
|
||||
handler?.({ preventDefault }, 'https://evil.example.com')
|
||||
expect(preventDefault).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should allow navigation to a local file:// URL', () => {
|
||||
let handler: ((event: { preventDefault: () => void }, url: string) => void) | undefined
|
||||
const window = {
|
||||
webContents: {
|
||||
on: (event: string, cb: typeof handler) => {
|
||||
if (event === 'will-navigate') handler = cb
|
||||
}
|
||||
}
|
||||
}
|
||||
blockExternalNavigation(window as never)
|
||||
const preventDefault = vi.fn()
|
||||
handler?.({ preventDefault }, 'file:///app/index.html')
|
||||
expect(preventDefault).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
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/
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { stripWakeWord } from '../../src/main/wakeWord'
|
||||
|
||||
describe('stripWakeWord()', () => {
|
||||
it('should strip the wake word and return the rest of the command', () => {
|
||||
expect(stripWakeWord('Max, quelle heure est-il ?')).toBe('quelle heure est-il ?')
|
||||
})
|
||||
|
||||
it('should be case-insensitive', () => {
|
||||
expect(stripWakeWord('MAX ouvre le bloc-notes')).toBe('ouvre le bloc-notes')
|
||||
})
|
||||
|
||||
it('should tolerate immediate punctuation after the wake word', () => {
|
||||
expect(stripWakeWord('Max! ferme ca')).toBe('ferme ca')
|
||||
expect(stripWakeWord('Max: dis bonjour')).toBe('dis bonjour')
|
||||
})
|
||||
|
||||
it('should return null when the transcript does not start with the wake word', () => {
|
||||
expect(stripWakeWord('quelle heure est-il ?')).toBeNull()
|
||||
})
|
||||
|
||||
it('should return null for a different word starting with "max" (e.g. "Maxime")', () => {
|
||||
expect(stripWakeWord('Maxime est en retard')).toBeNull()
|
||||
})
|
||||
|
||||
it('should return null when nothing follows the wake word', () => {
|
||||
expect(stripWakeWord('Max')).toBeNull()
|
||||
expect(stripWakeWord('Max,')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, it, expect, vi, beforeEach } 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')
|
||||
|
||||
describe('sendToRenderer()', () => {
|
||||
it('should do nothing when no main window has been set', () => {
|
||||
expect(() => sendToRenderer('some-channel', 1, 2)).not.toThrow()
|
||||
})
|
||||
|
||||
it('should forward the channel and args to the main window webContents', () => {
|
||||
const send = vi.fn()
|
||||
setMainWindow({ webContents: { send } } as never)
|
||||
sendToRenderer('some-channel', 'a', 'b')
|
||||
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')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user