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>
261 lines
9.6 KiB
TypeScript
261 lines
9.6 KiB
TypeScript
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.')
|
|
})
|
|
})
|