Develop #2
Generated
+1
-1131
File diff suppressed because it is too large
Load Diff
@@ -49,11 +49,9 @@
|
||||
"dotenv": "^18.0.8",
|
||||
"electron-updater": "^6.8.11",
|
||||
"mammoth": "^1.13.0",
|
||||
"mermaid": "^12.2.0",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"pdf-parse": "^1.1.1",
|
||||
"pptxgenjs": "^4.0.1",
|
||||
"roughjs": "^4.6.6",
|
||||
"three": "^0.186.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -2,42 +2,10 @@ import { loadSkills } from '../skills'
|
||||
import { getMemoriesText, getMood } from '../memory/store'
|
||||
import { synthesizeSpeech } from './elevenlabs'
|
||||
import { sendToRenderer } from '../windowBridge'
|
||||
import { getSubjectLevel } from '../coach/coachStore'
|
||||
import { recordCourseBuildTool, clearCourseBuild } from '../coach/courseBuildStepper'
|
||||
import { logger } from '../utils/logger'
|
||||
import { extractFakeToolCall, extractBareJsonRetry } from './toolCallRecovery'
|
||||
import { getConfigValue, requireLoggedIn } from '../auth/session'
|
||||
|
||||
// Outils dont l'argument "subject" permet de suivre le sujet Coach en cours de traitement dans ce
|
||||
// tour, pour le garde-fou mecanique anti-blocage du pipeline (voir plus bas).
|
||||
const PIPELINE_SUBJECT_TOOLS = new Set([
|
||||
'research_topic',
|
||||
'generate_course_plan',
|
||||
'write_module_content',
|
||||
'ask_written_exercise',
|
||||
'record_subject_level'
|
||||
])
|
||||
|
||||
// Construction du plan de cours : AUCUN acces a la voix pendant toute cette phase (demande
|
||||
// utilisateur explicite, a plusieurs reprises) — remplacee par le stepper visuel
|
||||
// (courseBuildStepper.ts) pilote par le code, pas par ce que le modele dit avoir fait. Seule
|
||||
// exception autorisee : l'annonce orale juste avant le formulaire d'evaluation initiale
|
||||
// (ask_written_exercise, kind="initial"), qui n'est pas dans cette liste.
|
||||
const SILENT_CONSTRUCTION_TOOLS = new Set([
|
||||
'research_topic',
|
||||
'generate_course_plan',
|
||||
'write_module_content',
|
||||
'record_subject_level'
|
||||
])
|
||||
|
||||
// Phrases typiques d'une annonce d'intention sans execution reelle, constate en test reel
|
||||
// specifiquement au tout premier message d'une demande d'apprentissage ("Je vais t'apprendre X !
|
||||
// Commencons par une recherche...") : a ce moment precis (round 0, aucun outil encore appele), le
|
||||
// garde-fou mecanique base sur "outils deja appeles ce tour" ne peut pas se declencher puisqu'aucun
|
||||
// outil n'a encore ete appele. Ce motif textuel, limite au tout premier round, comble ce trou.
|
||||
const FIRST_ROUND_ANNOUNCE_PATTERN =
|
||||
/\b(je vais (t'apprendre|te|faire|commencer)|commen[cç]ons par|je te propose de commencer)\b/i
|
||||
|
||||
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions'
|
||||
|
||||
// Si le modele principal est temporairement indisponible cote fournisseur (constate en test reel :
|
||||
@@ -78,13 +46,12 @@ appelle search_web et base ta reponse uniquement sur son resultat reel.
|
||||
|
||||
Pour consulter un site, utilise toujours navigate_browser (jamais d'autre moyen) : il ouvre un
|
||||
navigateur que TU controles (fenetre separee, visible par l'utilisateur) et que tu peux ensuite lire
|
||||
(read_browser_page), dans lequel tu peux cliquer (click_browser_element), remplir des formulaires
|
||||
(fill_browser_field), revenir en arriere (go_back_browser), traduire (translate_browser_page) ou
|
||||
surligner du texte (highlight_browser_text). Quand l'utilisateur demande d'ouvrir/consulter un site,
|
||||
IMPORTANT : si tu dois d'abord appeler search_web pour trouver l'URL, enchaine OBLIGATOIREMENT avec
|
||||
navigate_browser des que tu as l'URL, dans la meme reponse, sans t'arreter apres la recherche. Ne
|
||||
t'arrete et ne reponds a l'utilisateur qu'une fois la page reellement ouverte (ou en cas d'echec reel
|
||||
a signaler).
|
||||
(read_browser_page), dans lequel tu peux cliquer (click_browser_element), revenir en arriere
|
||||
(go_back_browser), traduire (translate_browser_page) ou surligner du texte (highlight_browser_text).
|
||||
Quand l'utilisateur demande d'ouvrir/consulter un site, IMPORTANT : si tu dois d'abord appeler
|
||||
search_web pour trouver l'URL, enchaine OBLIGATOIREMENT avec navigate_browser des que tu as l'URL,
|
||||
dans la meme reponse, sans t'arreter apres la recherche. Ne t'arrete et ne reponds a l'utilisateur
|
||||
qu'une fois la page reellement ouverte (ou en cas d'echec reel a signaler).
|
||||
|
||||
Quand l'utilisateur demande de surligner "les points cles" ou "les passages importants" d'une page
|
||||
(sans preciser de texte exact), agis de maniere autonome, sans demander de precisions : si aucune page
|
||||
@@ -134,11 +101,6 @@ function buildTools(): object[] {
|
||||
}))
|
||||
}
|
||||
|
||||
// Outils qui gerent eux-memes leur narration audio (ex: draw_schema, une caption par forme) : le
|
||||
// texte de reponse qui accompagne leur appel ne doit jamais etre parle en plus, sous peine de
|
||||
// doublon/chevauchement audio.
|
||||
const SELF_NARRATING_TOOLS = new Set(['draw_schema', 'draw_flow_diagram'])
|
||||
|
||||
// Marqueurs pour detecter une fuite de "boilerplate" interne du modele (constate en test reel :
|
||||
// "Use the results below to formulate an answer..." prononce a voix haute au lieu d'une vraie
|
||||
// reponse de Max) : present si ca ressemble a de l'anglais generique sans aucun mot-outil francais.
|
||||
@@ -171,12 +133,10 @@ const FALLBACK_REPLY =
|
||||
"Voila, j'ai bien avance avec toi sur ce sujet. Dis-moi si tu veux qu'on continue."
|
||||
|
||||
/**
|
||||
* Jusqu'ici, le texte qu'un message contenait EN MEME TEMPS qu'un appel d'outil etait jete : seule
|
||||
* la reponse du tour suivant (apres le resultat de l'outil, donc apres un aller-retour reseau
|
||||
* supplementaire) etait prononcee. Resultat observe : avec draw_schema, le dessin demarrait puis un
|
||||
* silence s'installait avant que Max ne commente, au lieu de parler pendant que le dessin apparait.
|
||||
* On prononce donc desormais ce commentaire immediatement (meme mecanisme que les rappels
|
||||
* proactifs), en parallele de l'execution de l'outil.
|
||||
* Le texte qu'un message contient EN MEME TEMPS qu'un appel d'outil est prononce immediatement
|
||||
* (meme mecanisme que les rappels proactifs), en parallele de l'execution de l'outil, plutot que
|
||||
* d'attendre le tour suivant (apres le resultat de l'outil, donc apres un aller-retour reseau
|
||||
* supplementaire).
|
||||
*/
|
||||
async function speakIntermediate(text: string): Promise<void> {
|
||||
try {
|
||||
@@ -215,9 +175,7 @@ async function executeTool(call: ToolCall): Promise<string> {
|
||||
// Historique borne en memoire pour garder le contexte entre deux echanges vocaux.
|
||||
const history: ChatMessage[] = []
|
||||
const MAX_HISTORY_MESSAGES = 16
|
||||
// Genereux pour laisser le pipeline Coach (recherche, plusieurs questions d'evaluation, niveau,
|
||||
// plan de cours, validation de modules...) enchainer ses outils sans etre coupe en plein milieu.
|
||||
const MAX_TOOL_ROUNDS = 40
|
||||
const MAX_TOOL_ROUNDS = 20
|
||||
|
||||
export async function getAssistantReply(userText: string): Promise<string> {
|
||||
requireLoggedIn()
|
||||
@@ -229,19 +187,8 @@ export async function getAssistantReply(userText: string): Promise<string> {
|
||||
history.push({ role: 'user', content: userText })
|
||||
|
||||
const messages: ChatMessage[] = [{ role: 'system', content: buildSystemPrompt() }, ...history]
|
||||
const calledTools = new Set<string>()
|
||||
let trackedSubject: string | null = null
|
||||
let moduleKindAskedThisTurn: string | null = null
|
||||
let finalKindAskedThisTurn = false
|
||||
let lastFailedTool: string | null = null
|
||||
let reliabilitySwitchUsed = false
|
||||
let pipelineNudges = 0
|
||||
const MAX_PIPELINE_NUDGES = 4
|
||||
|
||||
// Le pipeline Coach (recherche, plusieurs questions d'evaluation, niveau, plan de cours...)
|
||||
// enchaine naturellement bien plus de 4 appels d'outils en un seul tour : une limite trop basse
|
||||
// coupait la reponse en pleine evaluation initiale (constate en test reel : erreur silencieuse
|
||||
// apres le 4e appel, l'utilisateur ne recevait plus aucune reponse).
|
||||
for (let round = 0; round < MAX_TOOL_ROUNDS; round++) {
|
||||
const tools = buildTools()
|
||||
const callModel = (model: string): Promise<Response> =>
|
||||
@@ -327,17 +274,8 @@ export async function getAssistantReply(userText: string): Promise<string> {
|
||||
}
|
||||
|
||||
if (message.tool_calls?.length) {
|
||||
// draw_schema gere sa propre narration pas-a-pas (une caption par forme) : parler EN PLUS
|
||||
// le texte de ce tour doublerait/chevaucherait cet audio (constate en test reel : paroles
|
||||
// incoherentes, parfois dites deux fois). On ne declenche donc le commentaire immediat que
|
||||
// pour les outils qui n'ont pas leur propre canal audio.
|
||||
const handlesOwnNarration = message.tool_calls.some(
|
||||
(call) =>
|
||||
SELF_NARRATING_TOOLS.has(call.function.name) ||
|
||||
SILENT_CONSTRUCTION_TOOLS.has(call.function.name)
|
||||
)
|
||||
const intermediateText = message.content?.trim()
|
||||
if (intermediateText && !handlesOwnNarration) {
|
||||
if (intermediateText) {
|
||||
if (containsLeakedBoilerplate(intermediateText) || isDegenerateText(intermediateText)) {
|
||||
console.warn(`[chat] commentaire ignore (fuite/degenere): ${intermediateText}`)
|
||||
} else {
|
||||
@@ -346,152 +284,13 @@ export async function getAssistantReply(userText: string): Promise<string> {
|
||||
}
|
||||
}
|
||||
for (const call of message.tool_calls) {
|
||||
calledTools.add(call.function.name)
|
||||
let parsedArgs: Record<string, unknown> | null = null
|
||||
if (call.function.arguments) {
|
||||
try {
|
||||
parsedArgs = JSON.parse(call.function.arguments) as Record<string, unknown>
|
||||
} catch {
|
||||
// argument non parseable : ignore, pas critique pour le suivi
|
||||
}
|
||||
}
|
||||
if (parsedArgs && call.function.name === 'ask_written_exercise') {
|
||||
if (
|
||||
parsedArgs.kind === 'module' &&
|
||||
typeof parsedArgs.concept === 'string' &&
|
||||
parsedArgs.concept.trim()
|
||||
) {
|
||||
moduleKindAskedThisTurn = parsedArgs.concept.trim()
|
||||
} else if (parsedArgs.kind === 'final') {
|
||||
finalKindAskedThisTurn = true
|
||||
}
|
||||
}
|
||||
if (
|
||||
parsedArgs &&
|
||||
PIPELINE_SUBJECT_TOOLS.has(call.function.name) &&
|
||||
typeof parsedArgs.subject === 'string' &&
|
||||
parsedArgs.subject.trim()
|
||||
) {
|
||||
trackedSubject = parsedArgs.subject.trim()
|
||||
}
|
||||
const content = await executeTool(call)
|
||||
if (content.startsWith('Echec')) {
|
||||
lastFailedTool = call.function.name
|
||||
} else {
|
||||
lastFailedTool = null
|
||||
if (call.function.name === 'open_module_for_user') {
|
||||
// Construction terminee et remise a l'utilisateur : le stepper n'a plus lieu d'etre.
|
||||
clearCourseBuild()
|
||||
} else if (parsedArgs) {
|
||||
recordCourseBuildTool(call.function.name, parsedArgs)
|
||||
}
|
||||
}
|
||||
lastFailedTool = content.startsWith('Echec') ? call.function.name : null
|
||||
messages.push({ role: 'tool', tool_call_id: call.id, content })
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Garde-fou mecanique (constate en test reel, a plusieurs reprises : le modele annonce l'etape
|
||||
// suivante du pipeline initial ("je vais te poser des questions", "je vais rediger le plan")
|
||||
// SANS jamais appeler l'outil correspondant, laissant le pipeline bloque indefiniment). Le
|
||||
// prompt seul ne suffit pas toujours a l'empecher. Ne s'applique qu'AVANT que le niveau soit
|
||||
// enregistre (getSubjectLevel) : au-dela, un arret silencieux peut etre legitime (fin
|
||||
// d'enseignement d'un module, qui s'arrete volontairement sans enchainer sur une evaluation).
|
||||
if (trackedSubject && !getSubjectLevel(trackedSubject)) {
|
||||
let nudge: string | null = null
|
||||
if (calledTools.has('research_topic') && !calledTools.has('generate_course_plan')) {
|
||||
nudge =
|
||||
"Tu as fait la recherche mais tu n'as pas encore redige le plan de cours. Appelle MAINTENANT generate_course_plan (objectif mesurable + modules devines a partir de la recherche) avant de poser la moindre question."
|
||||
} else if (
|
||||
calledTools.has('generate_course_plan') &&
|
||||
!calledTools.has('write_module_content')
|
||||
) {
|
||||
nudge =
|
||||
"Le plan de cours est cree mais aucun module n'a encore de contenu ecrit. Appelle MAINTENANT write_module_content pour CHAQUE module cree, avant de poser la moindre question d'evaluation."
|
||||
} else if (
|
||||
calledTools.has('write_module_content') &&
|
||||
!calledTools.has('ask_written_exercise')
|
||||
) {
|
||||
nudge =
|
||||
"Le contenu des modules est pret. Appelle MAINTENANT ask_written_exercise (kind=\"initial\") pour commencer reellement l'evaluation, au lieu de l'annoncer sans l'executer."
|
||||
}
|
||||
if (nudge && pipelineNudges < MAX_PIPELINE_NUDGES) {
|
||||
pipelineNudges++
|
||||
console.warn(`[chat] pipeline bloque : relance forcee (${nudge.slice(0, 70)}...)`)
|
||||
messages.push({ role: 'system', content: nudge })
|
||||
continue
|
||||
}
|
||||
if (nudge && !reliabilitySwitchUsed && activeModel !== FALLBACK_MODEL) {
|
||||
// Le modele actif a ignore ${MAX_PIPELINE_NUDGES} rappels explicites de suite sur la meme
|
||||
// etape (constate en test reel) : ce n'est plus un probleme de formulation du prompt, c'est
|
||||
// une panne de fiabilite de ce modele sur ce tour precis. Bascule sur le modele de secours
|
||||
// (meme mecanisme de secours que pour une panne reseau) avec un budget de relance neuf,
|
||||
// plutot que d'abandonner et de rendre un texte qui n'a rien accompli.
|
||||
reliabilitySwitchUsed = true
|
||||
activeModel = FALLBACK_MODEL
|
||||
pipelineNudges = 0
|
||||
console.warn(
|
||||
`[chat] ${MAX_PIPELINE_NUDGES} relances infructueuses sur ${primaryModel} : bascule sur ${FALLBACK_MODEL} pour fiabilite`
|
||||
)
|
||||
messages.push({ role: 'system', content: nudge })
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Meme garde-fou, pour la transition evaluation -> validation (constate en test reel : "Je vais
|
||||
// maintenant marquer ce module comme acquis et deverrouiller le suivant" ecrit en texte, SANS
|
||||
// jamais appeler complete_module - le module restait bloque indefiniment). S'applique APRES le
|
||||
// niveau enregistre, independamment du garde-fou precedent.
|
||||
{
|
||||
let completionNudge: string | null = null
|
||||
if (moduleKindAskedThisTurn && !calledTools.has('complete_module')) {
|
||||
completionNudge = `Tu as evalue le module "${moduleKindAskedThisTurn}" mais tu ne l'as pas valide. Appelle MAINTENANT complete_module avant de conclure (si l'evaluation est insuffisante — moins de 2 niveaux de difficulte distincts — l'outil te le dira et tu pourras poser une question supplementaire).`
|
||||
} else if (finalKindAskedThisTurn && !calledTools.has('complete_subject')) {
|
||||
completionNudge =
|
||||
"Tu as fait l'evaluation finale mais tu ne l'as pas validee. Appelle MAINTENANT complete_subject avant de conclure."
|
||||
}
|
||||
if (completionNudge && pipelineNudges < MAX_PIPELINE_NUDGES) {
|
||||
pipelineNudges++
|
||||
console.warn(
|
||||
`[chat] validation manquante : relance forcee (${completionNudge.slice(0, 70)}...)`
|
||||
)
|
||||
messages.push({ role: 'system', content: completionNudge })
|
||||
continue
|
||||
}
|
||||
if (completionNudge && !reliabilitySwitchUsed && activeModel !== FALLBACK_MODEL) {
|
||||
reliabilitySwitchUsed = true
|
||||
activeModel = FALLBACK_MODEL
|
||||
pipelineNudges = 0
|
||||
console.warn(
|
||||
`[chat] ${MAX_PIPELINE_NUDGES} relances infructueuses sur ${primaryModel} : bascule sur ${FALLBACK_MODEL} pour fiabilite`
|
||||
)
|
||||
messages.push({ role: 'system', content: completionNudge })
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Garde-fou specifique au tout premier message d'une demande d'apprentissage (constate en test
|
||||
// reel : "Je vais t'apprendre la trigonometrie ! Commencons par une recherche...", prononce a
|
||||
// voix haute puis plus rien). A ce stade (round 0), aucun outil n'a encore ete appele, donc les
|
||||
// garde-fous bases sur calledTools/trackedSubject ci-dessus ne peuvent pas se declencher.
|
||||
if (
|
||||
round === 0 &&
|
||||
pipelineNudges < MAX_PIPELINE_NUDGES &&
|
||||
message.content &&
|
||||
FIRST_ROUND_ANNOUNCE_PATTERN.test(message.content)
|
||||
) {
|
||||
pipelineNudges++
|
||||
console.warn(
|
||||
`[chat] annonce sans action au premier message : relance forcee (${message.content.slice(0, 70)}...)`
|
||||
)
|
||||
messages.push({
|
||||
role: 'system',
|
||||
content:
|
||||
"Tu viens d'annoncer une action a venir sans l'executer. Appelle MAINTENANT research_topic dans ce tour, au lieu d'ecrire un texte qui l'annonce seulement."
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
let reply = message.content ?? ''
|
||||
if (containsLeakedBoilerplate(reply) || isDegenerateText(reply)) {
|
||||
console.warn(`[chat] reponse finale rejetee (fuite/degeneree), fallback utilise: ${reply}`)
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions'
|
||||
|
||||
/** Analyse une image (data URL complete, ex: "data:image/png;base64,...") via un modele vision. */
|
||||
export async function analyzeImage(imageDataUrl: string, question: string): Promise<string> {
|
||||
const apiKey = process.env.OPENROUTER_API_KEY
|
||||
if (!apiKey) throw new Error('OPENROUTER_API_KEY manquante dans .env')
|
||||
|
||||
const model = process.env.OPENROUTER_VISION_MODEL || 'deepseek/deepseek-v4.1-flash-1017'
|
||||
|
||||
const response = await fetch(OPENROUTER_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: question },
|
||||
{ type: 'image_url', image_url: { url: imageDataUrl } }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`OpenRouter (vision) a renvoye ${response.status}: ${await response.text()}`)
|
||||
}
|
||||
|
||||
const data = (await response.json()) as {
|
||||
choices?: { message: { content?: string } }[]
|
||||
}
|
||||
return data.choices?.[0]?.message.content ?? "Je n'ai pas reussi a analyser l'image."
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { parentPort } from 'node:worker_threads'
|
||||
import { writeFileSync, readdirSync, statSync, unlinkSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
|
||||
interface WriteJob {
|
||||
filePath: string
|
||||
png: Buffer
|
||||
}
|
||||
|
||||
interface PurgeJob {
|
||||
purgeDir: string
|
||||
cutoff: number
|
||||
}
|
||||
|
||||
// Tourne dans un worker_thread dedie : ecrit les PNG encodes et purge les anciens fichiers sur
|
||||
// disque. L'encodage PNG lui-meme (nativeImage.toPNG()) reste dans le thread principal car les API
|
||||
// Electron ne sont pas utilisables depuis un worker_thread ; seules les operations fichier (Node
|
||||
// pur, aucune dependance Electron) sont deportees ici pour ne jamais occuper le thread JS
|
||||
// principal pendant la capture continue du mode Coach.
|
||||
parentPort?.on('message', (job: WriteJob | PurgeJob) => {
|
||||
try {
|
||||
if ('purgeDir' in job) {
|
||||
for (const file of readdirSync(job.purgeDir)) {
|
||||
const filePath = join(job.purgeDir, file)
|
||||
if (statSync(filePath).mtimeMs < job.cutoff) unlinkSync(filePath)
|
||||
}
|
||||
parentPort?.postMessage({ ok: true })
|
||||
} else {
|
||||
writeFileSync(job.filePath, job.png)
|
||||
parentPort?.postMessage({ ok: true, filePath: job.filePath })
|
||||
}
|
||||
} catch (error) {
|
||||
parentPort?.postMessage({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -1,883 +0,0 @@
|
||||
import { app } from 'electron'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { join } from 'path'
|
||||
import type {
|
||||
AssessmentKind,
|
||||
ComplianceCheck,
|
||||
ConceptStatus,
|
||||
CourseComplianceReport,
|
||||
ExerciseDifficulty,
|
||||
ExerciseStyle,
|
||||
ModuleAssessment,
|
||||
ModuleDetail,
|
||||
ModuleDiagram,
|
||||
ModuleDiagramKind,
|
||||
SubjectProgress,
|
||||
SubjectStatus
|
||||
} from '../../shared/coach'
|
||||
|
||||
export type { ConceptStatus } from '../../shared/coach'
|
||||
|
||||
// Sequence d'intervalles (jours) approximant la courbe d'oubli d'Ebbinghaus : calculee cote code,
|
||||
// jamais laissee a l'IA (source d'erreurs si elle devait calculer des dates elle-meme).
|
||||
const REVIEW_INTERVALS_DAYS = [1, 3, 7, 16, 35]
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
let db: DatabaseSync | null = null
|
||||
|
||||
function addColumnIfMissing(
|
||||
database: DatabaseSync,
|
||||
table: string,
|
||||
column: string,
|
||||
type: string
|
||||
): void {
|
||||
try {
|
||||
database.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`)
|
||||
} catch {
|
||||
// Colonne deja presente (node:sqlite n'a pas d'equivalent "ADD COLUMN IF NOT EXISTS") : ok.
|
||||
}
|
||||
}
|
||||
|
||||
function getDb(): DatabaseSync {
|
||||
if (db) return db
|
||||
|
||||
const dbPath = join(app.getPath('userData'), 'coach.sqlite')
|
||||
db = new DatabaseSync(dbPath)
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS subjects (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
level TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
last_session_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS concepts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
subject_id INTEGER NOT NULL REFERENCES subjects(id),
|
||||
name TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
last_reviewed_at TEXT NOT NULL,
|
||||
UNIQUE(subject_id, name)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS assessments (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
subject_id INTEGER NOT NULL REFERENCES subjects(id),
|
||||
concept TEXT,
|
||||
question TEXT NOT NULL,
|
||||
question_type TEXT NOT NULL,
|
||||
options_json TEXT,
|
||||
answer TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS module_diagrams (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
subject_id INTEGER NOT NULL REFERENCES subjects(id),
|
||||
concept TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
`)
|
||||
addColumnIfMissing(db, 'concepts', 'next_review_at', 'TEXT')
|
||||
addColumnIfMissing(db, 'concepts', 'interval_index', 'INTEGER NOT NULL DEFAULT 0')
|
||||
addColumnIfMissing(db, 'concepts', 'reminded', 'INTEGER NOT NULL DEFAULT 0')
|
||||
addColumnIfMissing(db, 'concepts', 'order_index', 'INTEGER NOT NULL DEFAULT 0')
|
||||
addColumnIfMissing(db, 'concepts', 'locked', 'INTEGER NOT NULL DEFAULT 0')
|
||||
addColumnIfMissing(db, 'concepts', 'theory_summary', 'TEXT')
|
||||
addColumnIfMissing(db, 'subjects', 'research_summary', 'TEXT')
|
||||
addColumnIfMissing(db, 'subjects', 'status', "TEXT NOT NULL DEFAULT 'researching'")
|
||||
addColumnIfMissing(db, 'assessments', 'kind', "TEXT NOT NULL DEFAULT 'module'")
|
||||
addColumnIfMissing(db, 'assessments', 'dont_know', 'INTEGER NOT NULL DEFAULT 0')
|
||||
addColumnIfMissing(db, 'subjects', 'objective', 'TEXT')
|
||||
addColumnIfMissing(db, 'assessments', 'difficulty', 'TEXT')
|
||||
addColumnIfMissing(db, 'assessments', 'exercise_style', 'TEXT')
|
||||
addColumnIfMissing(db, 'assessments', 'targets_common_error', 'TEXT')
|
||||
return db
|
||||
}
|
||||
|
||||
function upsertSubject(name: string, level?: string): number {
|
||||
const now = new Date().toISOString()
|
||||
const database = getDb()
|
||||
const existing = database.prepare('SELECT id FROM subjects WHERE name = ?').get(name) as
|
||||
{ id: number } | undefined
|
||||
|
||||
if (existing) {
|
||||
database
|
||||
.prepare('UPDATE subjects SET last_session_at = ?, level = COALESCE(?, level) WHERE id = ?')
|
||||
.run(now, level ?? null, existing.id)
|
||||
return existing.id
|
||||
}
|
||||
|
||||
const result = database
|
||||
.prepare('INSERT INTO subjects (name, level, created_at, last_session_at) VALUES (?, ?, ?, ?)')
|
||||
.run(name, level ?? null, now, now)
|
||||
return Number(result.lastInsertRowid)
|
||||
}
|
||||
|
||||
function getSubjectId(name: string): number | undefined {
|
||||
const row = getDb().prepare('SELECT id FROM subjects WHERE name = ?').get(name) as
|
||||
{ id: number } | undefined
|
||||
return row?.id
|
||||
}
|
||||
|
||||
export function setSubjectLevel(subjectName: string, level: string): void {
|
||||
upsertSubject(subjectName, level)
|
||||
}
|
||||
|
||||
export function getSubjectLevel(subjectName: string): string | null {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return null
|
||||
const row = getDb().prepare('SELECT level FROM subjects WHERE id = ?').get(subjectId) as
|
||||
{ level: string | null } | undefined
|
||||
return row?.level ?? null
|
||||
}
|
||||
|
||||
export function setResearchSummary(subjectName: string, summary: string): void {
|
||||
const subjectId = upsertSubject(subjectName)
|
||||
getDb().prepare('UPDATE subjects SET research_summary = ? WHERE id = ?').run(summary, subjectId)
|
||||
}
|
||||
|
||||
export function setSubjectStatus(subjectName: string, status: SubjectStatus): void {
|
||||
const subjectId = upsertSubject(subjectName)
|
||||
getDb().prepare('UPDATE subjects SET status = ? WHERE id = ?').run(status, subjectId)
|
||||
}
|
||||
|
||||
export function getResearchSummary(subjectName: string): string | null {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return null
|
||||
const row = getDb()
|
||||
.prepare('SELECT research_summary FROM subjects WHERE id = ?')
|
||||
.get(subjectId) as { research_summary: string | null } | undefined
|
||||
return row?.research_summary ?? null
|
||||
}
|
||||
|
||||
export function setSubjectObjective(subjectName: string, objective: string): void {
|
||||
const subjectId = upsertSubject(subjectName)
|
||||
getDb().prepare('UPDATE subjects SET objective = ? WHERE id = ?').run(objective, subjectId)
|
||||
}
|
||||
|
||||
export function getSubjectObjective(subjectName: string): string | null {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return null
|
||||
const row = getDb().prepare('SELECT objective FROM subjects WHERE id = ?').get(subjectId) as
|
||||
{ objective: string | null } | undefined
|
||||
return row?.objective ?? null
|
||||
}
|
||||
|
||||
/** Au moins une evaluation ecrite existe pour ce sujet (et ce concept/type si precises). */
|
||||
export function hasAssessment(
|
||||
subjectName: string,
|
||||
concept?: string,
|
||||
kind?: AssessmentKind
|
||||
): boolean {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return false
|
||||
|
||||
const conditions = ['subject_id = ?']
|
||||
const values: (string | number)[] = [subjectId]
|
||||
if (concept) {
|
||||
conditions.push('concept = ?')
|
||||
values.push(concept)
|
||||
}
|
||||
if (kind) {
|
||||
conditions.push('kind = ?')
|
||||
values.push(kind)
|
||||
}
|
||||
|
||||
const row = getDb()
|
||||
.prepare(`SELECT 1 FROM assessments WHERE ${conditions.join(' AND ')} LIMIT 1`)
|
||||
.get(...values)
|
||||
return row !== undefined
|
||||
}
|
||||
|
||||
export function saveAssessment(
|
||||
subjectName: string,
|
||||
concept: string | null,
|
||||
question: string,
|
||||
type: string,
|
||||
options: string[] | null,
|
||||
answer: string,
|
||||
kind: AssessmentKind,
|
||||
dontKnow: boolean,
|
||||
difficulty: ExerciseDifficulty | null = null,
|
||||
exerciseStyle: ExerciseStyle | null = null,
|
||||
targetsCommonError: string | null = null
|
||||
): void {
|
||||
const subjectId = upsertSubject(subjectName)
|
||||
getDb()
|
||||
.prepare(
|
||||
`INSERT INTO assessments (subject_id, concept, question, question_type, options_json, answer, kind, dont_know, difficulty, exercise_style, targets_common_error, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
)
|
||||
.run(
|
||||
subjectId,
|
||||
concept,
|
||||
question,
|
||||
type,
|
||||
options ? JSON.stringify(options) : null,
|
||||
answer,
|
||||
kind,
|
||||
dontKnow ? 1 : 0,
|
||||
difficulty,
|
||||
exerciseStyle,
|
||||
targetsCommonError,
|
||||
new Date().toISOString()
|
||||
)
|
||||
}
|
||||
|
||||
/** Au moins 2 difficultes distinctes parmi les evaluations kind="module" de ce module. */
|
||||
export function hasMultipleDifficulties(subjectName: string, moduleName: string): boolean {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return false
|
||||
const rows = getDb()
|
||||
.prepare(
|
||||
`SELECT DISTINCT difficulty FROM assessments
|
||||
WHERE subject_id = ? AND concept = ? AND kind = 'module' AND difficulty IS NOT NULL`
|
||||
)
|
||||
.all(subjectId, moduleName) as { difficulty: string }[]
|
||||
return rows.length >= 2
|
||||
}
|
||||
|
||||
/**
|
||||
* Part des evaluations kind="module" repondues "Je ne sais pas" pour ce module — proxy pour "a
|
||||
* reussi", pas seulement "a tente" (RÈGLE 8.3 de docs/Max_Regles_Strictes_Module_Coach.md : un
|
||||
* module valide uniquement si l'utilisateur a reussi, pas juste essaye). Renvoie 1 (bloquant) s'il
|
||||
* n'y a aucune evaluation.
|
||||
*/
|
||||
export function moduleDontKnowRatio(subjectName: string, moduleName: string): number {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return 1
|
||||
const rows = getDb()
|
||||
.prepare(
|
||||
`SELECT dont_know FROM assessments WHERE subject_id = ? AND concept = ? AND kind = 'module'`
|
||||
)
|
||||
.all(subjectId, moduleName) as { dont_know: number }[]
|
||||
if (rows.length === 0) return 1
|
||||
return rows.filter((r) => r.dont_know === 1).length / rows.length
|
||||
}
|
||||
|
||||
export function upsertConceptStatus(
|
||||
subjectName: string,
|
||||
conceptName: string,
|
||||
status: ConceptStatus
|
||||
): void {
|
||||
const subjectId = upsertSubject(subjectName)
|
||||
const now = new Date().toISOString()
|
||||
const database = getDb()
|
||||
|
||||
const existing = database
|
||||
.prepare('SELECT interval_index FROM concepts WHERE subject_id = ? AND name = ?')
|
||||
.get(subjectId, conceptName) as { interval_index: number } | undefined
|
||||
|
||||
let intervalIndex = existing?.interval_index ?? 0
|
||||
let nextReviewAt: string | null = null
|
||||
const reminded = 0
|
||||
|
||||
if (status === 'acquired') {
|
||||
const intervalDays =
|
||||
REVIEW_INTERVALS_DAYS[Math.min(intervalIndex, REVIEW_INTERVALS_DAYS.length - 1)] ?? 0
|
||||
nextReviewAt = new Date(Date.now() + intervalDays * DAY_MS).toISOString()
|
||||
intervalIndex = Math.min(intervalIndex + 1, REVIEW_INTERVALS_DAYS.length - 1)
|
||||
} else if (status === 'to_review') {
|
||||
intervalIndex = 0
|
||||
nextReviewAt = new Date(Date.now() + (REVIEW_INTERVALS_DAYS[0] ?? 0) * DAY_MS).toISOString()
|
||||
}
|
||||
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO concepts (subject_id, name, status, last_reviewed_at, next_review_at, interval_index, reminded)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(subject_id, name) DO UPDATE SET
|
||||
status = excluded.status,
|
||||
last_reviewed_at = excluded.last_reviewed_at,
|
||||
next_review_at = excluded.next_review_at,
|
||||
interval_index = excluded.interval_index,
|
||||
reminded = excluded.reminded`
|
||||
)
|
||||
.run(subjectId, conceptName, status, now, nextReviewAt, intervalIndex, reminded)
|
||||
}
|
||||
|
||||
/** Ecrit/remplace le contenu theorique complet d'un module existant. */
|
||||
export function setModuleTheory(subjectName: string, moduleName: string, content: string): boolean {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return false
|
||||
const result = getDb()
|
||||
.prepare('UPDATE concepts SET theory_summary = ? WHERE subject_id = ? AND name = ?')
|
||||
.run(content, subjectId, moduleName)
|
||||
return result.changes > 0
|
||||
}
|
||||
|
||||
export function saveModuleDiagram(
|
||||
subjectName: string,
|
||||
moduleName: string,
|
||||
kind: ModuleDiagramKind,
|
||||
title: string,
|
||||
data: unknown
|
||||
): void {
|
||||
const subjectId = upsertSubject(subjectName)
|
||||
getDb()
|
||||
.prepare(
|
||||
'INSERT INTO module_diagrams (subject_id, concept, kind, title, data, created_at) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
)
|
||||
.run(subjectId, moduleName, kind, title, JSON.stringify(data), new Date().toISOString())
|
||||
}
|
||||
|
||||
export interface ModuleInput {
|
||||
name: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Cree ou REVISE (ajoute/supprime/modifie) les modules d'un plan de cours, dans l'ordre : seul le
|
||||
* premier est deverrouille. Remplacement complet par rapport au dernier appel (un module absent de
|
||||
* la nouvelle liste est supprime), sauf si sa progression reelle doit etre protegee (deja `acquired`
|
||||
* ou deja evalue via une evaluation `kind="module"`) — evite de perdre une progression reelle lors
|
||||
* d'une revision du plan suite a l'evaluation initiale. Ne prend plus de contenu directement (voir
|
||||
* ModuleInput) : le contenu deja ecrit (`theory_summary`, uniquement via write_module_content) est
|
||||
* TOUJOURS preserve ici (plus aucun moyen de le court-circuiter ou de l'effacer via ce point
|
||||
* d'entree — constate en test reel : un `theorySummary` sommaire glisse ici contournait entierement
|
||||
* la validation stricte de write_module_content).
|
||||
*/
|
||||
export function createModules(subjectName: string, modules: ModuleInput[]): void {
|
||||
const subjectId = upsertSubject(subjectName)
|
||||
const now = new Date().toISOString()
|
||||
const database = getDb()
|
||||
|
||||
const newNames = new Set(modules.map((m) => m.name))
|
||||
const existing = database
|
||||
.prepare('SELECT name, status FROM concepts WHERE subject_id = ?')
|
||||
.all(subjectId) as { name: string; status: ConceptStatus }[]
|
||||
|
||||
for (const row of existing) {
|
||||
if (newNames.has(row.name)) continue
|
||||
const hasModuleAssessment = database
|
||||
.prepare(
|
||||
"SELECT 1 FROM assessments WHERE subject_id = ? AND concept = ? AND kind = 'module' LIMIT 1"
|
||||
)
|
||||
.get(subjectId, row.name)
|
||||
if (row.status === 'acquired' || hasModuleAssessment) continue
|
||||
database
|
||||
.prepare('DELETE FROM concepts WHERE subject_id = ? AND name = ?')
|
||||
.run(subjectId, row.name)
|
||||
database
|
||||
.prepare('DELETE FROM module_diagrams WHERE subject_id = ? AND concept = ?')
|
||||
.run(subjectId, row.name)
|
||||
}
|
||||
|
||||
modules.forEach((module, index) => {
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO concepts (subject_id, name, status, last_reviewed_at, order_index, locked)
|
||||
VALUES (?, ?, 'not_started', ?, ?, ?)
|
||||
ON CONFLICT(subject_id, name) DO UPDATE SET
|
||||
order_index = excluded.order_index,
|
||||
locked = excluded.locked`
|
||||
)
|
||||
.run(subjectId, module.name, now, index, index === 0 ? 0 : 1)
|
||||
})
|
||||
}
|
||||
|
||||
/** Tous les modules d'un sujet ont un contenu ecrit (write_module_content deja appele pour chacun). */
|
||||
/**
|
||||
* Vrai uniquement si CHAQUE module a un contenu present ET structurellement conforme (6 sections,
|
||||
* longueurs minimales, etc. — voir validateModuleContent). Un contenu juste "non vide" ne suffit
|
||||
* pas : constate en test reel, un `theorySummary` sommaire glisse ailleurs (desormais impossible,
|
||||
* voir createModules) suffisait a tort a satisfaire cette verification.
|
||||
*/
|
||||
export function allModulesHaveContent(subjectName: string): boolean {
|
||||
return listModules(subjectName).length > 0 && modulesMissingContent(subjectName).length === 0
|
||||
}
|
||||
|
||||
/** Noms des modules d'un sujet dont le contenu est absent OU non conforme (RÈGLE du document). */
|
||||
export function modulesMissingContent(subjectName: string): string[] {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return []
|
||||
const rows = getDb()
|
||||
.prepare(
|
||||
'SELECT name, theory_summary FROM concepts WHERE subject_id = ? ORDER BY order_index ASC'
|
||||
)
|
||||
.all(subjectId) as { name: string; theory_summary: string | null }[]
|
||||
if (rows.length === 0) return []
|
||||
return rows
|
||||
.filter((r) => !r.theory_summary || validateModuleContent(r.theory_summary).length > 0)
|
||||
.map((r) => r.name)
|
||||
}
|
||||
|
||||
export interface ModuleRow {
|
||||
name: string
|
||||
status: ConceptStatus
|
||||
locked: boolean
|
||||
orderIndex: number
|
||||
}
|
||||
|
||||
export function listModules(subjectName: string): ModuleRow[] {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return []
|
||||
const rows = getDb()
|
||||
.prepare(
|
||||
'SELECT name, status, locked, order_index FROM concepts WHERE subject_id = ? ORDER BY order_index ASC'
|
||||
)
|
||||
.all(subjectId) as {
|
||||
name: string
|
||||
status: ConceptStatus
|
||||
locked: number
|
||||
order_index: number
|
||||
}[]
|
||||
return rows.map((r) => ({
|
||||
name: r.name,
|
||||
status: r.status,
|
||||
locked: r.locked === 1,
|
||||
orderIndex: r.order_index
|
||||
}))
|
||||
}
|
||||
|
||||
/** Deverrouille le module dont order_index suit celui donne, s'il existe. */
|
||||
export function unlockNextModule(subjectName: string, afterOrderIndex: number): void {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return
|
||||
getDb()
|
||||
.prepare(
|
||||
'UPDATE concepts SET locked = 0 WHERE subject_id = ? AND order_index = ? AND locked = 1'
|
||||
)
|
||||
.run(subjectId, afterOrderIndex + 1)
|
||||
}
|
||||
|
||||
export function getModuleOrderIndex(subjectName: string, moduleName: string): number | null {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return null
|
||||
const row = getDb()
|
||||
.prepare('SELECT order_index FROM concepts WHERE subject_id = ? AND name = ?')
|
||||
.get(subjectId, moduleName) as { order_index: number } | undefined
|
||||
return row?.order_index ?? null
|
||||
}
|
||||
|
||||
export function areAllModulesAcquired(subjectName: string): boolean {
|
||||
const modules = listModules(subjectName)
|
||||
return modules.length > 0 && modules.every((m) => m.status === 'acquired')
|
||||
}
|
||||
|
||||
export function getModuleDetail(subjectName: string, moduleName: string): ModuleDetail | null {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return null
|
||||
const database = getDb()
|
||||
|
||||
const module = database
|
||||
.prepare(
|
||||
'SELECT status, locked, theory_summary FROM concepts WHERE subject_id = ? AND name = ?'
|
||||
)
|
||||
.get(subjectId, moduleName) as
|
||||
{ status: ConceptStatus; locked: number; theory_summary: string | null } | undefined
|
||||
if (!module) return null
|
||||
|
||||
const assessmentRows = database
|
||||
.prepare(
|
||||
'SELECT question, answer, dont_know, difficulty, exercise_style, targets_common_error, created_at FROM assessments WHERE subject_id = ? AND concept = ? ORDER BY id ASC'
|
||||
)
|
||||
.all(subjectId, moduleName) as {
|
||||
question: string
|
||||
answer: string
|
||||
dont_know: number
|
||||
difficulty: ExerciseDifficulty | null
|
||||
exercise_style: ExerciseStyle | null
|
||||
targets_common_error: string | null
|
||||
created_at: string
|
||||
}[]
|
||||
|
||||
const assessments: ModuleAssessment[] = assessmentRows.map((a) => ({
|
||||
question: a.question,
|
||||
answer: a.answer,
|
||||
dontKnow: a.dont_know === 1,
|
||||
difficulty: a.difficulty,
|
||||
exerciseStyle: a.exercise_style,
|
||||
targetsCommonError: a.targets_common_error,
|
||||
createdAt: a.created_at
|
||||
}))
|
||||
|
||||
const diagramRows = database
|
||||
.prepare(
|
||||
'SELECT kind, title, data, created_at FROM module_diagrams WHERE subject_id = ? AND concept = ? ORDER BY id ASC'
|
||||
)
|
||||
.all(subjectId, moduleName) as {
|
||||
kind: ModuleDiagramKind
|
||||
title: string
|
||||
data: string
|
||||
created_at: string
|
||||
}[]
|
||||
|
||||
const diagrams: ModuleDiagram[] = diagramRows.map((d) => ({
|
||||
kind: d.kind,
|
||||
title: d.title,
|
||||
data: JSON.parse(d.data) as unknown,
|
||||
createdAt: d.created_at
|
||||
}))
|
||||
|
||||
return {
|
||||
name: moduleName,
|
||||
status: module.status,
|
||||
locked: module.locked === 1,
|
||||
theorySummary: module.theory_summary,
|
||||
assessments,
|
||||
diagrams
|
||||
}
|
||||
}
|
||||
|
||||
export interface DueReview {
|
||||
conceptId: number
|
||||
subject: string
|
||||
concept: string
|
||||
}
|
||||
|
||||
export function getDueReviews(nowIso: string): DueReview[] {
|
||||
const rows = getDb()
|
||||
.prepare(
|
||||
`SELECT concepts.id as conceptId, subjects.name as subject, concepts.name as concept
|
||||
FROM concepts JOIN subjects ON subjects.id = concepts.subject_id
|
||||
WHERE concepts.next_review_at IS NOT NULL
|
||||
AND concepts.next_review_at <= ?
|
||||
AND concepts.reminded = 0`
|
||||
)
|
||||
.all(nowIso) as unknown as DueReview[]
|
||||
return rows
|
||||
}
|
||||
|
||||
export function markReminded(conceptId: number): void {
|
||||
getDb().prepare('UPDATE concepts SET reminded = 1 WHERE id = ?').run(conceptId)
|
||||
}
|
||||
|
||||
function stripAccents(text: string): string {
|
||||
return text.normalize('NFD').replace(/[̀-ͯ]/g, '')
|
||||
}
|
||||
|
||||
function sectionIndex(content: string, label: string): number {
|
||||
return stripAccents(content).toLowerCase().indexOf(stripAccents(label).toLowerCase())
|
||||
}
|
||||
|
||||
function countWords(text: string): number {
|
||||
return text.trim().split(/\s+/).filter(Boolean).length
|
||||
}
|
||||
|
||||
// Structure imposee par docs/Max_Regles_Strictes_Module_Coach.md (RÈGLE 1) : 6 sections obligatoires
|
||||
// dans cet ordre, remplace l'ancienne structure a 5 sections (Accroche/Contexte/Idee centrale/
|
||||
// Analogie/Exemple) devenue trop sommaire suite au retour utilisateur fournissant ce document.
|
||||
export const REQUIRED_CONTENT_SECTIONS = [
|
||||
'Accroche',
|
||||
'Developpement theorique',
|
||||
'Phase guidee',
|
||||
'Exercices progressifs',
|
||||
'Exercice de debogage',
|
||||
'Synthese'
|
||||
]
|
||||
|
||||
// Longueurs minimales par section (RÈGLE 2/3/7 et annexe du document) — seules les sections dont la
|
||||
// longueur se verifie simplement par un comptage de mots sont contraintes ici ; les sous-sections
|
||||
// tres fines (idee centrale 80 mots, analogie 60 mots...) ne sont pas verifiees individuellement,
|
||||
// seulement leur section parente, pour rester un garde-fou robuste plutot qu'une analyse fragile.
|
||||
const SECTION_MIN_WORDS = new Map<string, number>([
|
||||
['Accroche', 150],
|
||||
['Developpement theorique', 300],
|
||||
['Synthese', 100]
|
||||
])
|
||||
|
||||
/** Sections obligatoires absentes d'un contenu de module, selon la structure pedagogique imposee. */
|
||||
export function missingContentSections(content: string): string[] {
|
||||
return REQUIRED_CONTENT_SECTIONS.filter((s) => sectionIndex(content, s) === -1)
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifie un contenu de module par rapport a docs/Max_Regles_Strictes_Module_Coach.md : sections
|
||||
* presentes ET dans l'ordre, longueurs minimales, phase guidee avec au moins 3 etapes numerotees,
|
||||
* au moins 6 exercices numerotes couvrant les 3 niveaux de difficulte, exercice de debogage
|
||||
* mentionnant une erreur a trouver. Heuristique par comptage/mots-cles (comme le reste du pipeline
|
||||
* Coach), pas une comprehension du contenu : un garde-fou reel mais pas une preuve de qualite.
|
||||
*/
|
||||
export function validateModuleContent(content: string): string[] {
|
||||
const violations: string[] = []
|
||||
const missing = missingContentSections(content)
|
||||
if (missing.length > 0) {
|
||||
violations.push(`Sections manquantes : ${missing.join(', ')}`)
|
||||
return violations
|
||||
}
|
||||
|
||||
const positions = REQUIRED_CONTENT_SECTIONS.map((label) => ({
|
||||
label,
|
||||
index: sectionIndex(content, label)
|
||||
})).sort((a, b) => a.index - b.index)
|
||||
|
||||
if (positions.map((p) => p.label).join('|') !== REQUIRED_CONTENT_SECTIONS.join('|')) {
|
||||
violations.push(
|
||||
`Les sections ne sont pas dans l'ordre impose : ${REQUIRED_CONTENT_SECTIONS.join(' -> ')}`
|
||||
)
|
||||
}
|
||||
|
||||
for (const [i, current] of positions.entries()) {
|
||||
const { label, index } = current
|
||||
const next = positions[i + 1]
|
||||
const end = next ? next.index : content.length
|
||||
const sectionText = content.slice(index, end)
|
||||
|
||||
const minWords = SECTION_MIN_WORDS.get(label)
|
||||
if (minWords) {
|
||||
const words = countWords(sectionText)
|
||||
if (words < minWords) {
|
||||
violations.push(`Section "${label}" trop courte : ${words} mots (minimum ${minWords})`)
|
||||
}
|
||||
}
|
||||
|
||||
// Match sur le texte sans accents : le modele ecrit naturellement "ÉTAPE" (accentue), qui ne
|
||||
// correspond jamais a /etape/i (code point different, pas juste une variante de casse) —
|
||||
// constate en test reel : un module correctement structure etait rejete a chaque tentative.
|
||||
const normalizedSection = stripAccents(sectionText).toLowerCase()
|
||||
|
||||
if (label === 'Phase guidee') {
|
||||
const steps = normalizedSection.match(/etape\s*\d/g) ?? []
|
||||
if (steps.length < 3) {
|
||||
violations.push(
|
||||
`Section "Phase guidee" : au moins 3 etapes numerotees requises ("ETAPE 1", "ETAPE 2"...), ${steps.length} trouvee(s)`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (label === 'Exercices progressifs') {
|
||||
const exercises = normalizedSection.match(/exercice\s*\d/g) ?? []
|
||||
if (exercises.length < 6) {
|
||||
violations.push(
|
||||
`Section "Exercices progressifs" : au moins 6 exercices numerotes requis ("EXERCICE 1"...), ${exercises.length} trouve(s)`
|
||||
)
|
||||
}
|
||||
for (const level of ['facile', 'moyen', 'difficile']) {
|
||||
if (!normalizedSection.includes(level)) {
|
||||
violations.push(`Section "Exercices progressifs" : aucun exercice de niveau "${level}"`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (label === 'Exercice de debogage') {
|
||||
if (!normalizedSection.includes('erreur')) {
|
||||
violations.push(
|
||||
`Section "Exercice de debogage" : aucune mention d'une erreur a trouver/corriger`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return violations
|
||||
}
|
||||
|
||||
/**
|
||||
* Empeche de rediger/mettre a jour le contenu d'un module si un module ANTERIEUR (order_index plus
|
||||
* petit) n'est pas encore acquis — demande utilisateur explicite : "interdire a Max de passer a la
|
||||
* redaction du module suivant si le precedent n'a pas passe la validation". Ne s'applique qu'une
|
||||
* fois le niveau enregistre (getSubjectLevel) : avant, tous les modules sont legitimement rediges
|
||||
* d'un coup en phase de preparation initiale, avant la moindre evaluation.
|
||||
*/
|
||||
export function canWriteModuleContent(
|
||||
subjectName: string,
|
||||
moduleName: string
|
||||
): { ok: boolean; blockedBy: string | null } {
|
||||
if (!getSubjectLevel(subjectName)) return { ok: true, blockedBy: null }
|
||||
|
||||
const modules = listModules(subjectName)
|
||||
const target = modules.find((m) => m.name === moduleName)
|
||||
if (!target) return { ok: true, blockedBy: null }
|
||||
|
||||
const earlierUnacquired = modules.find(
|
||||
(m) => m.orderIndex < target.orderIndex && m.status !== 'acquired'
|
||||
)
|
||||
return { ok: !earlierUnacquired, blockedBy: earlierUnacquired?.name ?? null }
|
||||
}
|
||||
|
||||
const MIN_MODULES = 3
|
||||
const MAX_MODULES_COMPLIANCE = 7
|
||||
|
||||
/**
|
||||
* Rapport de conformite au guide pedagogique "methode prof", calcule uniquement a partir des
|
||||
* donnees deja stockees (aucune confiance envers le modele) : rend auditable par l'utilisateur ce
|
||||
* qu'un garde-fou technique isole ne peut pas garantir (cohérence globale, structure du contenu).
|
||||
*/
|
||||
export function getCourseComplianceReport(subjectName: string): CourseComplianceReport | null {
|
||||
const subjectId = getSubjectId(subjectName)
|
||||
if (!subjectId) return null
|
||||
const database = getDb()
|
||||
|
||||
const subjectRow = database
|
||||
.prepare('SELECT objective, research_summary FROM subjects WHERE id = ?')
|
||||
.get(subjectId) as { objective: string | null; research_summary: string | null } | undefined
|
||||
|
||||
let research: Record<string, unknown>
|
||||
try {
|
||||
research = subjectRow?.research_summary
|
||||
? (JSON.parse(subjectRow.research_summary) as Record<string, unknown>)
|
||||
: {}
|
||||
} catch {
|
||||
research = {}
|
||||
}
|
||||
|
||||
const keyConcepts: unknown[] = Array.isArray(research.keyConcepts) ? research.keyConcepts : []
|
||||
const commonErrors: string[] = Array.isArray(research.commonErrors)
|
||||
? (research.commonErrors as string[])
|
||||
: []
|
||||
const sources = Array.isArray(research.sources) ? (research.sources as { level?: number }[]) : []
|
||||
|
||||
const modules = listModules(subjectName)
|
||||
|
||||
const checks: ComplianceCheck[] = []
|
||||
|
||||
checks.push({
|
||||
key: 'sources',
|
||||
label: 'Recherche sourcee (docs/Max_Recherche_Sources_Coach.md)',
|
||||
ok: sources.length > 0 && sources.some((s) => typeof s.level === 'number' && s.level <= 3),
|
||||
detail:
|
||||
sources.length > 0
|
||||
? `${sources.length} source(s), dont ${sources.filter((s) => (s.level ?? 4) <= 3).length} de niveau 1-3`
|
||||
: 'Aucune source enregistree'
|
||||
})
|
||||
checks.push({
|
||||
key: 'objective',
|
||||
label: 'Objectif final mesurable defini',
|
||||
ok: !!subjectRow?.objective,
|
||||
detail: subjectRow?.objective ?? 'Aucun objectif enregistre'
|
||||
})
|
||||
checks.push({
|
||||
key: 'prerequisites',
|
||||
label: 'Prerequis identifies',
|
||||
ok: !!research.prerequisites,
|
||||
detail: typeof research.prerequisites === 'string' ? research.prerequisites : 'Non renseigne'
|
||||
})
|
||||
checks.push({
|
||||
key: 'keyConcepts',
|
||||
label: '5 a 10 concepts cles identifies',
|
||||
ok: keyConcepts.length >= 5 && keyConcepts.length <= 10,
|
||||
detail: `${keyConcepts.length} concept(s)`
|
||||
})
|
||||
checks.push({
|
||||
key: 'commonErrors',
|
||||
label: '3 erreurs typiques identifiees',
|
||||
ok: commonErrors.length >= 3,
|
||||
detail: `${commonErrors.length} erreur(s)`
|
||||
})
|
||||
checks.push({
|
||||
key: 'feynman',
|
||||
label: 'Auto-verification Feynman faite',
|
||||
ok: !!research.feynmanExplanation,
|
||||
detail: typeof research.feynmanExplanation === 'string' ? 'Presente' : 'Absente'
|
||||
})
|
||||
checks.push({
|
||||
key: 'moduleCount',
|
||||
label: '3 a 7 modules',
|
||||
ok: modules.length >= MIN_MODULES && modules.length <= MAX_MODULES_COMPLIANCE,
|
||||
detail: `${modules.length} module(s)`
|
||||
})
|
||||
|
||||
for (const module of modules) {
|
||||
const moduleRow = database
|
||||
.prepare('SELECT theory_summary FROM concepts WHERE subject_id = ? AND name = ?')
|
||||
.get(subjectId, module.name) as { theory_summary: string | null } | undefined
|
||||
const content = moduleRow?.theory_summary ?? ''
|
||||
const violations = validateModuleContent(content)
|
||||
checks.push({
|
||||
key: `module-structure-${module.name}`,
|
||||
label: `Contenu conforme (6 sections, RÈGLES) : "${module.name}"`,
|
||||
ok: violations.length === 0,
|
||||
detail: violations.length === 0 ? 'Conforme' : violations.join(' | ')
|
||||
})
|
||||
|
||||
if (module.status === 'acquired') {
|
||||
checks.push({
|
||||
key: `module-difficulty-${module.name}`,
|
||||
label: `Progression de difficulte respectee : "${module.name}"`,
|
||||
ok: hasMultipleDifficulties(subjectName, module.name),
|
||||
detail: hasMultipleDifficulties(subjectName, module.name)
|
||||
? 'Au moins 2 difficultes distinctes'
|
||||
: 'Une seule difficulte utilisee (ou aucune)'
|
||||
})
|
||||
}
|
||||
|
||||
const debugRow = database
|
||||
.prepare(
|
||||
`SELECT 1 FROM assessments WHERE subject_id = ? AND concept = ? AND kind = 'module'
|
||||
AND exercise_style = 'debogage' AND targets_common_error IS NOT NULL LIMIT 1`
|
||||
)
|
||||
.get(subjectId, module.name)
|
||||
checks.push({
|
||||
key: `module-debug-${module.name}`,
|
||||
label: `Exercice de debogage lie a une erreur typique : "${module.name}"`,
|
||||
ok: debugRow !== undefined,
|
||||
detail: debugRow !== undefined ? 'Present' : 'Absent'
|
||||
})
|
||||
}
|
||||
|
||||
const finalRow = database
|
||||
.prepare(
|
||||
`SELECT difficulty FROM assessments WHERE subject_id = ? AND kind = 'final' ORDER BY id DESC LIMIT 1`
|
||||
)
|
||||
.get(subjectId) as { difficulty: string | null } | undefined
|
||||
checks.push({
|
||||
key: 'finalDifficulty',
|
||||
label: 'Evaluation finale exigeante (difficulte "difficile")',
|
||||
ok: finalRow?.difficulty === 'difficile',
|
||||
detail: finalRow?.difficulty ?? 'Pas encore evaluee'
|
||||
})
|
||||
|
||||
const acquiredModules = modules.filter((m) => m.status === 'acquired')
|
||||
if (acquiredModules.length > 0) {
|
||||
const reviewRows = database
|
||||
.prepare(
|
||||
'SELECT COUNT(*) as count FROM concepts WHERE subject_id = ? AND status = ? AND next_review_at IS NOT NULL'
|
||||
)
|
||||
.get(subjectId, 'acquired') as { count: number }
|
||||
checks.push({
|
||||
key: 'reviewsScheduled',
|
||||
label: 'Revisions programmees pour les modules acquis',
|
||||
ok: reviewRows.count === acquiredModules.length,
|
||||
detail: `${reviewRows.count}/${acquiredModules.length} module(s) acquis avec revision programmee`
|
||||
})
|
||||
}
|
||||
|
||||
return { subject: subjectName, checks }
|
||||
}
|
||||
|
||||
export function getProgress(subjectName?: string): SubjectProgress[] {
|
||||
const database = getDb()
|
||||
const subjects = (
|
||||
subjectName
|
||||
? database.prepare('SELECT * FROM subjects WHERE name = ?').all(subjectName)
|
||||
: database.prepare('SELECT * FROM subjects ORDER BY last_session_at DESC').all()
|
||||
) as {
|
||||
id: number
|
||||
name: string
|
||||
level: string | null
|
||||
status: SubjectStatus
|
||||
objective: string | null
|
||||
last_session_at: string
|
||||
}[]
|
||||
|
||||
return subjects.map((subject) => {
|
||||
const concepts = database
|
||||
.prepare(
|
||||
'SELECT name, status, last_reviewed_at, next_review_at, locked, order_index FROM concepts WHERE subject_id = ? ORDER BY order_index ASC'
|
||||
)
|
||||
.all(subject.id) as {
|
||||
name: string
|
||||
status: ConceptStatus
|
||||
last_reviewed_at: string
|
||||
next_review_at: string | null
|
||||
locked: number
|
||||
order_index: number
|
||||
}[]
|
||||
return {
|
||||
subject: subject.name,
|
||||
level: subject.level,
|
||||
status: subject.status,
|
||||
objective: subject.objective,
|
||||
lastSessionAt: subject.last_session_at,
|
||||
concepts: concepts.map((c) => ({
|
||||
name: c.name,
|
||||
status: c.status,
|
||||
lastReviewedAt: c.last_reviewed_at,
|
||||
nextReviewAt: c.next_review_at,
|
||||
locked: c.locked === 1,
|
||||
orderIndex: c.order_index
|
||||
}))
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
import { sendToRenderer } from '../windowBridge'
|
||||
import type { CourseBuildState, CourseBuildStepStatus } from '../../shared/courseBuild'
|
||||
|
||||
/**
|
||||
* Suit et affiche a l'utilisateur l'avancement de la construction d'un plan de cours (recherche,
|
||||
* plan, redaction des modules, evaluation initiale, niveau, revision), pour que Max n'ait plus a
|
||||
* l'annoncer a l'oral a chaque etape (demande utilisateur explicite) : le stepper remplace la
|
||||
* narration vocale par un affichage visuel, pilote par code a partir des outils reellement appeles
|
||||
* (jamais par ce que le modele dit avoir fait).
|
||||
*/
|
||||
|
||||
const STEP_DEFS: { key: string; label: string }[] = [
|
||||
{ key: 'recherche', label: 'Recherche approfondie' },
|
||||
{ key: 'plan', label: 'Objectif et plan de modules' },
|
||||
{ key: 'redaction', label: 'Redaction des modules' },
|
||||
{ key: 'evaluation_initiale', label: 'Evaluation initiale' },
|
||||
{ key: 'niveau', label: 'Niveau enregistre' },
|
||||
{ key: 'revision', label: 'Ajustement du plan' }
|
||||
]
|
||||
|
||||
interface InternalState {
|
||||
subject: string
|
||||
statuses: Map<string, CourseBuildStepStatus>
|
||||
totalModules: number
|
||||
writtenModules: number
|
||||
sourceCount: number
|
||||
}
|
||||
|
||||
let state: InternalState | null = null
|
||||
|
||||
function emit(): void {
|
||||
if (!state) return
|
||||
const payload: CourseBuildState = {
|
||||
subject: state.subject,
|
||||
steps: STEP_DEFS.map((def) => {
|
||||
const detail =
|
||||
def.key === 'redaction' && state!.totalModules > 0
|
||||
? `${state!.writtenModules}/${state!.totalModules}`
|
||||
: def.key === 'recherche' && state!.sourceCount > 0
|
||||
? `${state!.sourceCount} source(s)`
|
||||
: undefined
|
||||
return {
|
||||
key: def.key,
|
||||
label: def.label,
|
||||
status: state!.statuses.get(def.key) ?? 'pending',
|
||||
...(detail !== undefined ? { detail } : {})
|
||||
}
|
||||
})
|
||||
}
|
||||
sendToRenderer('course-build-step', payload)
|
||||
}
|
||||
|
||||
/**
|
||||
* Efface le stepper explicitement (ex: au moment ou open_module_for_user ouvre le premier module,
|
||||
* signe que la construction est terminee et remise a l'utilisateur). AUCUN masquage automatique par
|
||||
* minuterie : un tour de voix dans ce pipeline peut prendre plusieurs dizaines de secondes a
|
||||
* plusieurs minutes entre deux appels d'outils (constate en test reel), et un masquage par inactivite
|
||||
* effaçait l'etat ENTIER (y compris les coches deja validees) avant l'etape suivante — l'utilisateur
|
||||
* voyait alors des coches "se decocher" (demande utilisateur explicite : elles doivent rester).
|
||||
*/
|
||||
export function clearCourseBuild(): void {
|
||||
state = null
|
||||
sendToRenderer('course-build-step', null)
|
||||
}
|
||||
|
||||
function ensureState(subject: string): InternalState {
|
||||
if (!state || state.subject !== subject) {
|
||||
state = {
|
||||
subject,
|
||||
statuses: new Map(STEP_DEFS.map((d) => [d.key, 'pending'])),
|
||||
totalModules: 0,
|
||||
writtenModules: 0,
|
||||
sourceCount: 0
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
/** A appeler apres l'execution reussie de chaque outil du pipeline Coach, avec ses arguments bruts. */
|
||||
export function recordCourseBuildTool(toolName: string, args: Record<string, unknown>): void {
|
||||
const subject = typeof args.subject === 'string' ? args.subject.trim() : null
|
||||
if (!subject) return
|
||||
|
||||
const s = ensureState(subject)
|
||||
|
||||
switch (toolName) {
|
||||
case 'research_topic':
|
||||
s.statuses.set('recherche', 'done')
|
||||
s.statuses.set('plan', 'active')
|
||||
s.sourceCount = Array.isArray(args.sources) ? args.sources.length : 0
|
||||
break
|
||||
case 'generate_course_plan':
|
||||
if (s.statuses.get('niveau') === 'done') {
|
||||
s.statuses.set('revision', 'done')
|
||||
} else {
|
||||
s.statuses.set('plan', 'done')
|
||||
s.totalModules = Array.isArray(args.modules) ? args.modules.length : 0
|
||||
s.writtenModules = 0
|
||||
s.statuses.set('redaction', s.totalModules > 0 ? 'active' : 'pending')
|
||||
}
|
||||
break
|
||||
case 'write_module_content':
|
||||
s.writtenModules += 1
|
||||
if (s.totalModules > 0 && s.writtenModules >= s.totalModules) {
|
||||
s.statuses.set('redaction', 'done')
|
||||
s.statuses.set('evaluation_initiale', 'active')
|
||||
}
|
||||
break
|
||||
case 'ask_written_exercise':
|
||||
if (args.kind === 'initial') {
|
||||
s.statuses.set('evaluation_initiale', 'done')
|
||||
s.statuses.set('niveau', 'active')
|
||||
}
|
||||
break
|
||||
case 'record_subject_level':
|
||||
s.statuses.set('niveau', 'done')
|
||||
break
|
||||
default:
|
||||
return
|
||||
}
|
||||
|
||||
emit()
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
import { randomUUID } from 'crypto'
|
||||
import { BrowserWindow, ipcMain, type IpcMainEvent } from 'electron'
|
||||
import { join } from 'path'
|
||||
import { is } from '@electron-toolkit/utils'
|
||||
import type { DrawShape } from '../../shared/drawing'
|
||||
import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from '../utils/windowSecurity'
|
||||
|
||||
let win: BrowserWindow | null = null
|
||||
let windowReady: Promise<void> | null = null
|
||||
|
||||
// Fenetre normale et independante de l'avatar, meme pattern singleton que progressWindow.ts.
|
||||
function ensureWindow(): { window: BrowserWindow; ready: Promise<void> } {
|
||||
if (win && !win.isDestroyed()) return { window: win, ready: windowReady ?? Promise.resolve() }
|
||||
|
||||
win = new BrowserWindow({
|
||||
width: 700,
|
||||
height: 560,
|
||||
title: 'Max — tableau',
|
||||
alwaysOnTop: true,
|
||||
webPreferences: {
|
||||
preload: join(__dirname, '../preload/index.js'),
|
||||
...SECURE_WEB_PREFERENCES
|
||||
}
|
||||
})
|
||||
blockExternalNavigation(win)
|
||||
// Meme raison que exerciseWindow.ts : visible au-dessus de tout (y compris plein ecran), mais en
|
||||
// dessous de l'avatar ('screen-saver') qui reste donc toujours devant.
|
||||
win.setAlwaysOnTop(true, 'floating')
|
||||
win.maximize()
|
||||
win.on('closed', () => {
|
||||
win = null
|
||||
windowReady = null
|
||||
})
|
||||
|
||||
const window = win
|
||||
windowReady = new Promise((resolve) => {
|
||||
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
|
||||
void window.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#coach-drawing`)
|
||||
} else {
|
||||
void window.loadFile(join(__dirname, '../renderer/index.html'), { hash: 'coach-drawing' })
|
||||
}
|
||||
if (window.webContents.isLoading()) {
|
||||
window.webContents.once('did-finish-load', () => resolve())
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
|
||||
return { window, ready: windowReady }
|
||||
}
|
||||
|
||||
/** Ouvre (ou reutilise) la fenetre et initialise le canvas (titre, dimensions, vide). */
|
||||
export async function openDrawingWindow(
|
||||
title: string,
|
||||
width: number,
|
||||
height: number
|
||||
): Promise<void> {
|
||||
const { window, ready } = ensureWindow()
|
||||
window.show()
|
||||
window.moveTop()
|
||||
window.focus()
|
||||
await ready
|
||||
window.webContents.send('init-drawing', { title, width, height })
|
||||
}
|
||||
|
||||
/**
|
||||
* Attend un accuse de reception a usage unique du renderer (evenement `ackEvent` portant le meme
|
||||
* `requestId` que celui envoye), avec expiration et nettoyage si la fenetre se ferme entre-temps.
|
||||
* Factorise le boilerplate partage par revealShape() et playCaption().
|
||||
*/
|
||||
function waitForAck(
|
||||
window: BrowserWindow,
|
||||
ackEvent: string,
|
||||
timeoutMs: number,
|
||||
send: (requestId: string) => void
|
||||
): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const requestId = randomUUID()
|
||||
|
||||
let settled = false
|
||||
const finish = (): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
ipcMain.removeListener(ackEvent, handler)
|
||||
resolve()
|
||||
}
|
||||
|
||||
const timeout = setTimeout(finish, timeoutMs)
|
||||
|
||||
function handler(_event: IpcMainEvent, id: string): void {
|
||||
if (id !== requestId) return
|
||||
finish()
|
||||
}
|
||||
ipcMain.on(ackEvent, handler)
|
||||
window.once('closed', finish)
|
||||
|
||||
send(requestId)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Revele une forme dans la fenetre deja ouverte, avec un audio optionnel (narration pas-a-pas).
|
||||
* Attend l'accuse de reception du renderer (forme dessinee + audio termine) avant de se resoudre,
|
||||
* pour que draw_schema puisse enchainer les formes au rythme de la narration.
|
||||
*/
|
||||
export function revealShape(
|
||||
shape: DrawShape,
|
||||
audio: ArrayBuffer | null,
|
||||
timeoutMs = 20000
|
||||
): Promise<void> {
|
||||
if (!win || win.isDestroyed()) return Promise.resolve()
|
||||
const window = win
|
||||
return waitForAck(window, 'shape-reveal-done', timeoutMs, (requestId) => {
|
||||
window.webContents.send('reveal-shape', { requestId, shape, audio })
|
||||
})
|
||||
}
|
||||
|
||||
/** Rend un diagramme Mermaid (cycle/hierarchie/flux) dans la fenetre, d'un coup (pas de reveal
|
||||
* noeud-par-noeud : la fiabilite du layout prime sur l'effet progressif pour ce type precis). */
|
||||
export async function renderMermaid(title: string, mermaidCode: string): Promise<void> {
|
||||
const { window, ready } = ensureWindow()
|
||||
window.show()
|
||||
window.moveTop()
|
||||
window.focus()
|
||||
await ready
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const requestId = randomUUID()
|
||||
function handler(_event: IpcMainEvent, id: string, ok: boolean, error?: string): void {
|
||||
if (id !== requestId) return
|
||||
ipcMain.removeListener('mermaid-render-done', handler)
|
||||
if (ok) resolve()
|
||||
else reject(new Error(error ?? 'Echec du rendu Mermaid'))
|
||||
}
|
||||
ipcMain.on('mermaid-render-done', handler)
|
||||
window.webContents.send('render-mermaid', { requestId, title, mermaidCode })
|
||||
})
|
||||
}
|
||||
|
||||
/** Joue une legende audio seule (sans forme associee), pour la narration sequencee de Mermaid. */
|
||||
export function playCaption(audio: ArrayBuffer, timeoutMs = 20000): Promise<void> {
|
||||
if (!win || win.isDestroyed()) return Promise.resolve()
|
||||
const window = win
|
||||
return waitForAck(window, 'caption-done', timeoutMs, (requestId) => {
|
||||
window.webContents.send('play-caption', { requestId, audio })
|
||||
})
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
import { randomUUID } from 'crypto'
|
||||
import { BrowserWindow, ipcMain, type IpcMainEvent } from 'electron'
|
||||
import { join } from 'path'
|
||||
import { is } from '@electron-toolkit/utils'
|
||||
import type { ExerciseFormAnswer, ExerciseFormItem } from '../../shared/coach'
|
||||
import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from '../utils/windowSecurity'
|
||||
|
||||
let win: BrowserWindow | null = null
|
||||
|
||||
// Delai avant fermeture automatique de la fenetre une fois le formulaire soumis (demande
|
||||
// utilisateur explicite : la fenetre ne doit pas rester ouverte indefiniment apres soumission).
|
||||
const AUTO_CLOSE_DELAY_MS = 2000
|
||||
|
||||
// Fenetre normale et independante de l'avatar et de la courbe d'apprentissage, meme pattern
|
||||
// singleton que progressWindow.ts.
|
||||
function ensureWindow(): BrowserWindow {
|
||||
if (win && !win.isDestroyed()) return win
|
||||
|
||||
win = new BrowserWindow({
|
||||
width: 520,
|
||||
height: 480,
|
||||
title: 'Max — exercice',
|
||||
alwaysOnTop: true,
|
||||
webPreferences: {
|
||||
preload: join(__dirname, '../preload/index.js'),
|
||||
...SECURE_WEB_PREFERENCES
|
||||
}
|
||||
})
|
||||
blockExternalNavigation(win)
|
||||
// Niveau en dessous de l'avatar ('screen-saver') mais au-dessus de tout le reste, y compris une
|
||||
// appli en plein ecran : sans ca, la fenetre pouvait s'ouvrir derriere le premier plan actuel et
|
||||
// l'utilisateur devait la retrouver via la barre des taches (constate en test reel).
|
||||
win.setAlwaysOnTop(true, 'floating')
|
||||
win.maximize()
|
||||
win.on('closed', () => {
|
||||
win = null
|
||||
})
|
||||
|
||||
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
|
||||
void win.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#coach-exercise`)
|
||||
} else {
|
||||
void win.loadFile(join(__dirname, '../renderer/index.html'), { hash: 'coach-exercise' })
|
||||
}
|
||||
return win
|
||||
}
|
||||
|
||||
export interface QuestionInput {
|
||||
question: string
|
||||
type: ExerciseFormItem['type']
|
||||
options: string[] | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Ouvre la fenetre d'exercice, pose TOUTES les questions en une seule fois (formulaire groupe, pas
|
||||
* une par une : demande utilisateur explicite) et attend la soumission de l'utilisateur. Renvoie un
|
||||
* tableau de reponses (meme ordre que `questions`), `null` par entree si la fenetre est fermee sans
|
||||
* soumission ou si le delai est depasse. La fenetre se ferme automatiquement 2 secondes apres
|
||||
* soumission.
|
||||
*/
|
||||
export function requestWrittenAnswers(
|
||||
questions: QuestionInput[],
|
||||
timeoutMs = 30 * 60 * 1000
|
||||
): Promise<(string | null)[]> {
|
||||
return new Promise((resolve) => {
|
||||
const window = ensureWindow()
|
||||
window.show()
|
||||
window.moveTop()
|
||||
window.focus()
|
||||
const requestId = randomUUID()
|
||||
const items: ExerciseFormItem[] = questions.map((q, index) => ({
|
||||
id: String(index),
|
||||
question: q.question,
|
||||
type: q.type,
|
||||
options: q.options
|
||||
}))
|
||||
|
||||
let settled = false
|
||||
const finish = (answers: (string | null)[]): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
ipcMain.removeListener('written-form-result', handler)
|
||||
resolve(answers)
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => finish(items.map(() => null)), timeoutMs)
|
||||
|
||||
function handler(_event: IpcMainEvent, id: string, answers: ExerciseFormAnswer[]): void {
|
||||
if (id !== requestId) return
|
||||
const byId = new Map(answers.map((a) => [a.id, a.answer]))
|
||||
finish(items.map((item) => byId.get(item.id) ?? null))
|
||||
setTimeout(() => {
|
||||
if (win && !win.isDestroyed()) win.close()
|
||||
}, AUTO_CLOSE_DELAY_MS)
|
||||
}
|
||||
ipcMain.on('written-form-result', handler)
|
||||
window.once('closed', () => finish(items.map(() => null)))
|
||||
|
||||
const send = (): void => window.webContents.send('ask-written-form', { requestId, items })
|
||||
if (window.webContents.isLoading()) {
|
||||
window.webContents.once('did-finish-load', send)
|
||||
} else {
|
||||
send()
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import type { DrawShape } from '../../../shared/drawing'
|
||||
import { num } from './utils'
|
||||
|
||||
const PALETTE = ['#2a5fb8', '#b83a3a', '#3a9b5c', '#c98a1e', '#7a4ab8', '#1e9ab0']
|
||||
|
||||
interface Slice {
|
||||
label?: string | undefined
|
||||
value: number
|
||||
color?: string | undefined
|
||||
caption?: string | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Cercle divise en secteurs (camembert) : les angles sont calcules proportionnellement par le
|
||||
* code a partir des valeurs fournies, jamais devines par le modele.
|
||||
*/
|
||||
export function buildCircleSector(params: Record<string, unknown>): DrawShape[] {
|
||||
const cx = num(params.cx, 250, 0, 2000)
|
||||
const cy = num(params.cy, 220, 0, 2000)
|
||||
const radius = num(params.radius, 140, 30, 800)
|
||||
const rawSlices = Array.isArray(params.slices) ? params.slices : []
|
||||
|
||||
const slices: Slice[] = rawSlices
|
||||
.map((s): Slice | null => {
|
||||
if (typeof s !== 'object' || s === null) return null
|
||||
const slice = s as Record<string, unknown>
|
||||
const value = num(slice.value, 0, 0, 1e9)
|
||||
if (value <= 0) return null
|
||||
return {
|
||||
label: typeof slice.label === 'string' ? slice.label : undefined,
|
||||
value,
|
||||
color: typeof slice.color === 'string' ? slice.color : undefined,
|
||||
caption: typeof slice.caption === 'string' ? slice.caption : undefined
|
||||
}
|
||||
})
|
||||
.filter((s): s is Slice => s !== null)
|
||||
|
||||
if (slices.length === 0) return []
|
||||
|
||||
const total = slices.reduce((sum, s) => sum + s.value, 0)
|
||||
let current = -90 // demarre en haut (12h), sens horaire
|
||||
|
||||
return slices.map((slice, i) => {
|
||||
const sweep = (slice.value / total) * 360
|
||||
const shape: DrawShape = {
|
||||
type: 'arc',
|
||||
x: cx,
|
||||
y: cy,
|
||||
radius,
|
||||
startAngle: current,
|
||||
endAngle: current + sweep,
|
||||
closed: true,
|
||||
color: slice.color ?? PALETTE[i % PALETTE.length],
|
||||
label: slice.label,
|
||||
caption: slice.caption
|
||||
}
|
||||
current += sweep
|
||||
return shape
|
||||
})
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import type { DrawShape } from '../../../shared/drawing'
|
||||
import { num, str } from './utils'
|
||||
|
||||
interface Point {
|
||||
x: number
|
||||
y: number
|
||||
label?: string | undefined
|
||||
caption?: string | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Axes de coordonnees perpendiculaires (toujours a angle droit par construction) avec points a
|
||||
* tracer optionnels, pour l'algebre/la geometrie analytique.
|
||||
*/
|
||||
export function buildCoordinateAxes(params: Record<string, unknown>): DrawShape[] {
|
||||
const x = num(params.x, 80, 0, 2000)
|
||||
const y = num(params.y, 60, 0, 2000)
|
||||
const width = num(params.width, 320, 80, 1500)
|
||||
const height = num(params.height, 260, 80, 1500)
|
||||
const color = str(params.color, '#333333')
|
||||
const originX = x
|
||||
const originY = y + height
|
||||
|
||||
const shapes: DrawShape[] = [
|
||||
{ type: 'arrow', x: originX, y: originY, x2: originX + width, y2: originY, color },
|
||||
{ type: 'arrow', x: originX, y: originY, x2: originX, y2: y, color },
|
||||
{
|
||||
type: 'text',
|
||||
x: originX + width - 10,
|
||||
y: originY + 18,
|
||||
content: str(params.xLabel, 'x'),
|
||||
color
|
||||
},
|
||||
{ type: 'text', x: originX - 16, y: y - 6, content: str(params.yLabel, 'y'), color }
|
||||
]
|
||||
|
||||
const rawPoints = Array.isArray(params.points) ? params.points : []
|
||||
for (const p of rawPoints) {
|
||||
if (typeof p !== 'object' || p === null) continue
|
||||
const point = p as Record<string, unknown>
|
||||
const px = originX + num(point.x, 0, -width, width)
|
||||
const py = originY - num(point.y, 0, -height, height)
|
||||
const pt: Point = {
|
||||
x: px,
|
||||
y: py,
|
||||
label: typeof point.label === 'string' ? point.label : undefined,
|
||||
caption: typeof point.caption === 'string' ? point.caption : undefined
|
||||
}
|
||||
shapes.push({
|
||||
type: 'circle',
|
||||
x: pt.x,
|
||||
y: pt.y,
|
||||
radius: 4,
|
||||
color: '#b83a3a',
|
||||
label: pt.label,
|
||||
caption: pt.caption
|
||||
})
|
||||
}
|
||||
|
||||
return shapes
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import type { DrawShape } from '../../../shared/drawing'
|
||||
import { buildRightTriangle } from './rightTriangle'
|
||||
import { buildTriangle } from './triangle'
|
||||
import { buildRegularPolygon } from './regularPolygon'
|
||||
import { buildCircleSector } from './circleSector'
|
||||
import { buildVennDiagram } from './vennDiagram'
|
||||
import { buildCoordinateAxes } from './coordinateAxes'
|
||||
|
||||
export const PRESET_GENERATORS = new Map<string, (params: Record<string, unknown>) => DrawShape[]>([
|
||||
['right_triangle', buildRightTriangle],
|
||||
['triangle', buildTriangle],
|
||||
['regular_polygon', buildRegularPolygon],
|
||||
['circle_sector', buildCircleSector],
|
||||
['venn_diagram', buildVennDiagram],
|
||||
['coordinate_axes', buildCoordinateAxes]
|
||||
])
|
||||
@@ -1,35 +0,0 @@
|
||||
import type { DrawShape } from '../../../shared/drawing'
|
||||
import { num, str } from './utils'
|
||||
|
||||
/**
|
||||
* Polygone regulier a N cotes (carre, pentagone, hexagone...) inscrit dans un cercle : les sommets
|
||||
* sont toujours parfaitement espaces par construction, jamais devines par le modele.
|
||||
*/
|
||||
export function buildRegularPolygon(params: Record<string, unknown>): DrawShape[] {
|
||||
const sides = Math.round(num(params.sides, 6, 3, 12))
|
||||
const cx = num(params.cx, 250, 0, 2000)
|
||||
const cy = num(params.cy, 220, 0, 2000)
|
||||
const radius = num(params.radius, 140, 30, 800)
|
||||
const color = str(params.color, '#2a5fb8')
|
||||
const labels = Array.isArray(params.labels) ? params.labels.map((l) => String(l)) : []
|
||||
const captions = Array.isArray(params.captions) ? params.captions.map((c) => String(c)) : []
|
||||
|
||||
const vertices = Array.from({ length: sides }, (_, i) => {
|
||||
const angle = -Math.PI / 2 + (i * 2 * Math.PI) / sides
|
||||
return { x: cx + radius * Math.cos(angle), y: cy + radius * Math.sin(angle) }
|
||||
})
|
||||
|
||||
return vertices.map((vertex, i) => {
|
||||
const next = vertices[(i + 1) % sides] ?? vertex
|
||||
return {
|
||||
type: 'line',
|
||||
x: vertex.x,
|
||||
y: vertex.y,
|
||||
x2: next.x,
|
||||
y2: next.y,
|
||||
color,
|
||||
label: labels.at(i),
|
||||
caption: captions.at(i)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import type { DrawShape } from '../../../shared/drawing'
|
||||
import { num, str, strOrUndefined } from './utils'
|
||||
|
||||
/**
|
||||
* Triangle rectangle toujours geometriquement valide : angle droit fixe en bas-a-gauche, angle
|
||||
* theta en haut. Le modele ne fournit que des labels/captions, jamais de coordonnees.
|
||||
*/
|
||||
export function buildRightTriangle(params: Record<string, unknown>): DrawShape[] {
|
||||
const x = num(params.x, 120, 0, 2000)
|
||||
const y = num(params.y, 80, 0, 2000)
|
||||
const size = num(params.size, 220, 50, 800)
|
||||
const color = str(params.color, '#2a5fb8')
|
||||
const hypotenuseColor = str(params.hypotenuseColor, '#b83a3a')
|
||||
|
||||
return [
|
||||
{
|
||||
type: 'line',
|
||||
x,
|
||||
y,
|
||||
x2: x,
|
||||
y2: y + size,
|
||||
color,
|
||||
label: str(params.adjacentLabel, 'Adjacent'),
|
||||
caption: strOrUndefined(params.adjacentCaption)
|
||||
},
|
||||
{
|
||||
type: 'line',
|
||||
x,
|
||||
y: y + size,
|
||||
x2: x + size,
|
||||
y2: y + size,
|
||||
color,
|
||||
label: str(params.oppositeLabel, 'Opposé'),
|
||||
caption: strOrUndefined(params.oppositeCaption)
|
||||
},
|
||||
{
|
||||
type: 'line',
|
||||
x,
|
||||
y,
|
||||
x2: x + size,
|
||||
y2: y + size,
|
||||
color: hypotenuseColor,
|
||||
label: str(params.hypotenuseLabel, 'Hypoténuse'),
|
||||
caption: strOrUndefined(params.hypotenuseCaption)
|
||||
},
|
||||
{ type: 'rect', x, y: y + size - 14, width: 14, height: 14, color: '#555555' },
|
||||
{
|
||||
type: 'arc',
|
||||
x,
|
||||
y,
|
||||
radius: 28,
|
||||
startAngle: 45,
|
||||
endAngle: 90,
|
||||
color: '#555555',
|
||||
label: str(params.angleLabel, 'θ'),
|
||||
caption: strOrUndefined(params.angleCaption)
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import type { DrawShape } from '../../../shared/drawing'
|
||||
import { num, str, strOrUndefined } from './utils'
|
||||
|
||||
/**
|
||||
* Triangle quelconque (equilateral, isocele, scalene, rectangle...) toujours valide : decrit par
|
||||
* une base, une hauteur et un decalage horizontal du sommet — jamais par 3 sommets devines par le
|
||||
* modele (source d'incoherences). apexOffset = base/2 donne un triangle isocele, 0 ou base un
|
||||
* triangle rectangle, toute autre valeur un triangle scalene.
|
||||
*/
|
||||
export function buildTriangle(params: Record<string, unknown>): DrawShape[] {
|
||||
const x = num(params.x, 120, 0, 2000)
|
||||
const y = num(params.y, 80, 0, 2000)
|
||||
const base = num(params.base, 220, 40, 1000)
|
||||
const height = num(params.height, 180, 40, 1000)
|
||||
const apexOffset = num(params.apexOffset, base / 2, -500, 1500)
|
||||
const color = str(params.color, '#2a5fb8')
|
||||
|
||||
const bottomLeft = { x, y: y + height }
|
||||
const bottomRight = { x: x + base, y: y + height }
|
||||
const apex = { x: x + apexOffset, y }
|
||||
|
||||
const shapes: DrawShape[] = [
|
||||
{
|
||||
type: 'line',
|
||||
x: bottomLeft.x,
|
||||
y: bottomLeft.y,
|
||||
x2: bottomRight.x,
|
||||
y2: bottomRight.y,
|
||||
color,
|
||||
label: strOrUndefined(params.baseLabel),
|
||||
caption: strOrUndefined(params.baseCaption)
|
||||
},
|
||||
{
|
||||
type: 'line',
|
||||
x: bottomLeft.x,
|
||||
y: bottomLeft.y,
|
||||
x2: apex.x,
|
||||
y2: apex.y,
|
||||
color,
|
||||
label: strOrUndefined(params.leftSideLabel),
|
||||
caption: strOrUndefined(params.leftSideCaption)
|
||||
},
|
||||
{
|
||||
type: 'line',
|
||||
x: apex.x,
|
||||
y: apex.y,
|
||||
x2: bottomRight.x,
|
||||
y2: bottomRight.y,
|
||||
color,
|
||||
label: strOrUndefined(params.rightSideLabel),
|
||||
caption: strOrUndefined(params.rightSideCaption)
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
x: apex.x - 6,
|
||||
y: apex.y - 8,
|
||||
content: str(params.apexLabel, ''),
|
||||
color: '#555555',
|
||||
caption: strOrUndefined(params.apexCaption)
|
||||
}
|
||||
]
|
||||
return shapes.filter((shape) => shape.type !== 'text' || shape.content)
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
export function num(value: unknown, fallback: number, min = -1e6, max = 1e6): number {
|
||||
const n = Number(value)
|
||||
if (!Number.isFinite(n)) return fallback
|
||||
return Math.min(Math.max(n, min), max)
|
||||
}
|
||||
|
||||
export function str(value: unknown, fallback = ''): string {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : fallback
|
||||
}
|
||||
|
||||
export function strOrUndefined(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : undefined
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import type { DrawShape } from '../../../shared/drawing'
|
||||
import { num, str } from './utils'
|
||||
|
||||
const PALETTE = ['#2a5fb8', '#b83a3a', '#3a9b5c']
|
||||
|
||||
/**
|
||||
* Diagramme de Venn a 2 ou 3 cercles, disposition standard (cote-a-cote ou triangulaire) calculee
|
||||
* par le code : le chevauchement est toujours coherent, jamais devine par le modele.
|
||||
*/
|
||||
export function buildVennDiagram(params: Record<string, unknown>): DrawShape[] {
|
||||
const cx = num(params.cx, 300, 0, 2000)
|
||||
const cy = num(params.cy, 220, 0, 2000)
|
||||
const radius = num(params.radius, 110, 30, 500)
|
||||
const rawLabels = Array.isArray(params.labels) ? params.labels : []
|
||||
const labels = rawLabels.slice(0, 3).map((l) => (typeof l === 'string' ? l : undefined))
|
||||
const count = Math.max(2, Math.min(3, labels.length || 2))
|
||||
|
||||
const centers =
|
||||
count === 2
|
||||
? [
|
||||
{ x: cx - radius * 0.5, y: cy },
|
||||
{ x: cx + radius * 0.5, y: cy }
|
||||
]
|
||||
: [
|
||||
{ x: cx, y: cy - radius * 0.5 },
|
||||
{ x: cx - radius * 0.55, y: cy + radius * 0.35 },
|
||||
{ x: cx + radius * 0.55, y: cy + radius * 0.35 }
|
||||
]
|
||||
|
||||
return centers.map((center, i) => ({
|
||||
type: 'circle',
|
||||
x: center.x,
|
||||
y: center.y,
|
||||
radius,
|
||||
color: str((params.colors as unknown[] | undefined)?.at(i), PALETTE.at(i % PALETTE.length)),
|
||||
label: labels.at(i)
|
||||
}))
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import { BrowserWindow } from 'electron'
|
||||
import { join } from 'path'
|
||||
import { is } from '@electron-toolkit/utils'
|
||||
import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from '../utils/windowSecurity'
|
||||
|
||||
let win: BrowserWindow | null = null
|
||||
|
||||
export interface ModuleTarget {
|
||||
subject: string
|
||||
module: string
|
||||
}
|
||||
|
||||
function sendNavigateToModule(window: BrowserWindow, target: ModuleTarget): void {
|
||||
const send = (): void => window.webContents.send('navigate-to-module', target)
|
||||
if (window.webContents.isLoading()) {
|
||||
window.webContents.once('did-finish-load', send)
|
||||
} else {
|
||||
send()
|
||||
}
|
||||
}
|
||||
|
||||
// Fenetre normale et independante de l'avatar (qui continue de s'afficher a cote, inchange) :
|
||||
// meme principe singleton que src/main/browser/browserWindow.ts, mais charge le renderer compile
|
||||
// de l'app avec un hash different plutot qu'une URL externe.
|
||||
export function openCoachProgressWindow(navigateTo?: ModuleTarget): void {
|
||||
if (win && !win.isDestroyed()) {
|
||||
win.show()
|
||||
win.moveTop()
|
||||
win.focus()
|
||||
if (navigateTo) sendNavigateToModule(win, navigateTo)
|
||||
return
|
||||
}
|
||||
|
||||
win = new BrowserWindow({
|
||||
width: 480,
|
||||
height: 640,
|
||||
title: "Max — courbe d'apprentissage",
|
||||
alwaysOnTop: true,
|
||||
webPreferences: {
|
||||
preload: join(__dirname, '../preload/index.js'),
|
||||
...SECURE_WEB_PREFERENCES
|
||||
}
|
||||
})
|
||||
blockExternalNavigation(win)
|
||||
win.setAlwaysOnTop(true, 'floating')
|
||||
win.maximize()
|
||||
win.on('closed', () => {
|
||||
win = null
|
||||
})
|
||||
|
||||
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
|
||||
void win.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#coach-progress`)
|
||||
} else {
|
||||
void win.loadFile(join(__dirname, '../renderer/index.html'), { hash: 'coach-progress' })
|
||||
}
|
||||
|
||||
if (navigateTo) sendNavigateToModule(win, navigateTo)
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { Notification } from 'electron'
|
||||
import { synthesizeSpeech } from '../ai/elevenlabs'
|
||||
import { sendToRenderer } from '../windowBridge'
|
||||
import { getDueReviews, markReminded } from './coachStore'
|
||||
|
||||
const TICK_MS = 5 * 60 * 1000
|
||||
|
||||
async function checkDueReviews(): Promise<void> {
|
||||
const due = getDueReviews(new Date().toISOString())
|
||||
if (due.length === 0) return
|
||||
|
||||
const summary = due.map((d) => `${d.concept} (${d.subject})`).join(', ')
|
||||
new Notification({
|
||||
title: 'Revision due',
|
||||
body: `A reviser : ${summary}`
|
||||
}).show()
|
||||
|
||||
try {
|
||||
const message = `C'est le moment de reviser : ${summary}. Repasse en mode apprentissage pour qu'on y travaille ensemble.`
|
||||
const speech = await synthesizeSpeech(message)
|
||||
const buffer = speech.buffer.slice(
|
||||
speech.byteOffset,
|
||||
speech.byteOffset + speech.byteLength
|
||||
) as ArrayBuffer
|
||||
sendToRenderer('proactive-speech', buffer)
|
||||
} catch (error) {
|
||||
console.error('[coach] echec annonce vocale de revision', error)
|
||||
}
|
||||
|
||||
for (const review of due) markReminded(review.conceptId)
|
||||
}
|
||||
|
||||
// Tourne independamment du mode actif : une revision peut etre signalee meme hors mode Coach.
|
||||
export function startReviewScheduler(): void {
|
||||
setInterval(() => {
|
||||
checkDueReviews().catch((error) =>
|
||||
console.error('[coach] echec verification des revisions', error)
|
||||
)
|
||||
}, TICK_MS)
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { app, desktopCapturer, screen } from 'electron'
|
||||
import { Worker } from 'node:worker_threads'
|
||||
import { existsSync, mkdirSync, readdirSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
|
||||
const CAPTURE_INTERVAL_MS = 1000
|
||||
const ROLLING_WINDOW_MS = 7 * 60 * 60 * 1000
|
||||
|
||||
let worker: Worker | null = null
|
||||
let intervalHandle: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
function captureDir(): string {
|
||||
const dir = join(app.getPath('userData'), 'coach-captures')
|
||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
||||
return dir
|
||||
}
|
||||
|
||||
function ensureWorker(): Worker {
|
||||
if (worker) return worker
|
||||
worker = new Worker(join(__dirname, 'captureWorker.js'))
|
||||
worker.on('error', (error) => console.error('[coach] erreur worker de capture', error))
|
||||
return worker
|
||||
}
|
||||
|
||||
async function captureOnce(): Promise<void> {
|
||||
const display = screen.getPrimaryDisplay()
|
||||
const sources = await desktopCapturer.getSources({
|
||||
types: ['screen'],
|
||||
thumbnailSize: display.size
|
||||
})
|
||||
const source = sources[0]
|
||||
if (!source) return
|
||||
|
||||
const png = source.thumbnail.toPNG()
|
||||
const filePath = join(captureDir(), `capture-${Date.now()}.png`)
|
||||
ensureWorker().postMessage({ filePath, png })
|
||||
}
|
||||
|
||||
function purgeOldCaptures(): void {
|
||||
const cutoff = Date.now() - ROLLING_WINDOW_MS
|
||||
ensureWorker().postMessage({ purgeDir: captureDir(), cutoff })
|
||||
}
|
||||
|
||||
let tickCount = 0
|
||||
|
||||
export function startVisionCapture(): void {
|
||||
if (intervalHandle) return
|
||||
intervalHandle = setInterval(() => {
|
||||
tickCount += 1
|
||||
captureOnce().catch((error) => console.error('[coach] echec capture ecran', error))
|
||||
if (tickCount % 60 === 0) purgeOldCaptures()
|
||||
}, CAPTURE_INTERVAL_MS)
|
||||
}
|
||||
|
||||
export function stopVisionCapture(): void {
|
||||
if (intervalHandle) {
|
||||
clearInterval(intervalHandle)
|
||||
intervalHandle = null
|
||||
}
|
||||
}
|
||||
|
||||
export function getRecentCaptures(count: number): string[] {
|
||||
const dir = captureDir()
|
||||
if (!existsSync(dir)) return []
|
||||
return readdirSync(dir)
|
||||
.filter((f: string) => f.endsWith('.png'))
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.slice(-count)
|
||||
.map((f: string) => join(dir, f))
|
||||
}
|
||||
@@ -11,8 +11,6 @@ import { enqueueMeetingAudioChunk, finishMeetingSession } from './meeting/meetin
|
||||
import { loginAndLoadKeys } from './auth/authClient'
|
||||
import { openLoginWindow, closeLoginWindow } from './auth/loginWindow'
|
||||
import { clearSession, getCurrentUserEmail, isLoggedIn } from './auth/session'
|
||||
import { getProgress, getModuleDetail, getCourseComplianceReport } from './coach/coachStore'
|
||||
import { startReviewScheduler } from './coach/reviewScheduler'
|
||||
import type { VoiceTurnResult } from '../shared/voice'
|
||||
import type { AuthStatus, LoginResult } from '../shared/auth'
|
||||
import { logger } from './utils/logger'
|
||||
@@ -22,8 +20,7 @@ import { startAutoUpdater } from './updater'
|
||||
let mainWindow: BrowserWindow | null = null
|
||||
|
||||
// Empeche de lancer plusieurs instances de Max en parallele (chaque instance ouvrirait sa propre
|
||||
// fenetre avatar, son propre acces concurrent a la base SQLite et son propre planificateur de
|
||||
// revisions) : le second lancement se ferme immediatement et reactive la fenetre existante.
|
||||
// fenetre avatar) : le second lancement se ferme immediatement et reactive la fenetre existante.
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit()
|
||||
process.exit(0)
|
||||
@@ -171,14 +168,6 @@ app
|
||||
if (window) menu.popup({ window })
|
||||
})
|
||||
|
||||
ipcMain.handle('get-coach-progress', () => getProgress())
|
||||
ipcMain.handle('get-module-detail', (_event, subject: string, moduleName: string) =>
|
||||
getModuleDetail(subject, moduleName)
|
||||
)
|
||||
ipcMain.handle('get-course-compliance', (_event, subject: string) =>
|
||||
getCourseComplianceReport(subject)
|
||||
)
|
||||
|
||||
ipcMain.on('meeting-audio-chunk', (_event, audio: ArrayBuffer, mimeType: string) => {
|
||||
enqueueMeetingAudioChunk(Buffer.from(audio), mimeType)
|
||||
})
|
||||
@@ -216,24 +205,6 @@ app
|
||||
})()
|
||||
})
|
||||
|
||||
ipcMain.on('evaluate-module', (_event, subject: string, moduleName: string) => {
|
||||
void (async () => {
|
||||
const prompt = `[Evenement systeme] L'utilisateur a clique sur "Evaluer" pour le module "${moduleName}" du sujet "${subject}". Relis le contenu de ce module (get_course_plan) pour rester coherent avec ce qui a ete enseigne, puis commence immediatement l'evaluation ecrite (ask_written_exercise, kind="module", concept="${moduleName}").`
|
||||
|
||||
try {
|
||||
const reply = await getAssistantReply(prompt)
|
||||
const speech = await synthesizeSpeech(reply)
|
||||
const audio = speech.buffer.slice(
|
||||
speech.byteOffset,
|
||||
speech.byteOffset + speech.byteLength
|
||||
) as ArrayBuffer
|
||||
sendToRenderer('proactive-speech', audio)
|
||||
} catch (error) {
|
||||
console.error('[evaluate-module]', error)
|
||||
}
|
||||
})()
|
||||
})
|
||||
|
||||
ipcMain.handle(
|
||||
'voice-turn',
|
||||
async (_event, inputAudio: ArrayBuffer, mimeType: string): Promise<VoiceTurnResult> => {
|
||||
@@ -290,7 +261,6 @@ app
|
||||
}))
|
||||
|
||||
createWindow()
|
||||
startReviewScheduler()
|
||||
if (!is.dev) startAutoUpdater()
|
||||
|
||||
app.on('activate', function () {
|
||||
|
||||
@@ -1,288 +0,0 @@
|
||||
import { requestWrittenAnswers } from '../../coach/exerciseWindow'
|
||||
import {
|
||||
saveAssessment,
|
||||
listModules,
|
||||
areAllModulesAcquired,
|
||||
getSubjectLevel,
|
||||
getSubjectObjective,
|
||||
allModulesHaveContent,
|
||||
modulesMissingContent
|
||||
} from '../../coach/coachStore'
|
||||
import { DONT_KNOW_ANSWER } from '../../../shared/coach'
|
||||
import type {
|
||||
ExerciseType,
|
||||
AssessmentKind,
|
||||
ExerciseDifficulty,
|
||||
ExerciseStyle
|
||||
} from '../../../shared/coach'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const VALID_TYPES: ExerciseType[] = ['free_text', 'multiple_choice', 'true_false']
|
||||
const VALID_KINDS: AssessmentKind[] = ['initial', 'module', 'final']
|
||||
const VALID_DIFFICULTIES: ExerciseDifficulty[] = ['facile', 'moyen', 'difficile']
|
||||
const VALID_STYLES: ExerciseStyle[] = [
|
||||
'prediction',
|
||||
'debogage',
|
||||
'probleme_ouvert',
|
||||
'projet',
|
||||
'qcm_cible'
|
||||
]
|
||||
const DEMANDING_STYLES: ExerciseStyle[] = ['projet', 'probleme_ouvert']
|
||||
const MAX_QUESTIONS = 12
|
||||
|
||||
/**
|
||||
* Le modele ecrit naturellement le francais avec accents ("probleme_ouvert" devient
|
||||
* "problème_ouvert"), ce qui ne correspondait a aucune valeur d'enum exacte et faisait echouer
|
||||
* l'appel pour rien (constate en test reel : un aller-retour perdu a chaque fois). Normalise avant
|
||||
* comparaison plutot que d'exiger une orthographe exacte sans accent.
|
||||
*/
|
||||
function stripAccents(text: string): string {
|
||||
return text.normalize('NFD').replace(/[̀-ͯ]/g, '')
|
||||
}
|
||||
|
||||
function normalizeStyle(raw: string): ExerciseStyle | null {
|
||||
const normalized = stripAccents(raw).toLowerCase()
|
||||
return VALID_STYLES.find((s) => stripAccents(s).toLowerCase() === normalized) ?? null
|
||||
}
|
||||
|
||||
interface ParsedQuestion {
|
||||
question: string
|
||||
type: ExerciseType
|
||||
options: string[] | null
|
||||
concept: string | null
|
||||
difficulty: ExerciseDifficulty | null
|
||||
exerciseStyle: ExerciseStyle | null
|
||||
targetsCommonError: string | null
|
||||
}
|
||||
|
||||
export const askWrittenExercise: SkillDefinition = {
|
||||
name: 'ask_written_exercise',
|
||||
description:
|
||||
"Pose TOUTES les questions d'evaluation d'un coup, dans UN SEUL formulaire a l'ecrit (jamais une par une, et JAMAIS a l'oral — ne recite jamais les questions dans ta reponse, seule la fenetre ecrite les affiche), et attend que l'utilisateur soumette l'ensemble. Un bouton \"Je ne sais pas\" est toujours propose pour chaque question : rassure l'utilisateur, ce n'est qu'une base pour savoir quoi enseigner, jamais une notation. Obligatoire avant tout jugement de maitrise (track_concept_mastery/complete_module) ou avant de fixer le niveau d'un sujet (record_subject_level). Precise 'kind' : 'initial' (evaluation de depart d'un sujet — refuse techniquement tant que generate_course_plan et write_module_content pour TOUS les modules n'ont pas ete faits avant ; exige EXACTEMENT une question par module existant, avec le champ 'concept' de chaque question egal au nom exact du module qu'elle teste — jamais de question generale non liee a un module precis), 'module' (validation d'un module du plan de cours), ou 'final' (evaluation globale de maitrise du sujet).",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage concerne" },
|
||||
concept: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Module/concept precis evalue (omettre pour une evaluation generale de niveau initial/final)'
|
||||
},
|
||||
kind: {
|
||||
type: 'string',
|
||||
enum: VALID_KINDS,
|
||||
description: "Type d'evaluation : initial, module ou final"
|
||||
},
|
||||
questions: {
|
||||
type: 'array',
|
||||
description:
|
||||
"Toutes les questions a poser EN UNE FOIS dans le meme formulaire (au moins 1, par exemple 5 a 10 pour une evaluation initiale). Varie les difficultes et les types d'exercice au sein du tableau.",
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
question: { type: 'string', description: "Question a poser a l'ecrit" },
|
||||
concept: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Pour kind="initial" UNIQUEMENT (obligatoire) : nom EXACT du module que cette question teste (une question par module, jamais de question generale). Pour kind="module"/"final", omettre (utilise le champ \'concept\' global).'
|
||||
},
|
||||
type: {
|
||||
type: 'string',
|
||||
enum: VALID_TYPES,
|
||||
description:
|
||||
'Type de question : free_text (texte libre), multiple_choice (QCM, fournir options) ou true_false'
|
||||
},
|
||||
options: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description: 'Liste des choix, obligatoire uniquement si type = multiple_choice'
|
||||
},
|
||||
difficulty: {
|
||||
type: 'string',
|
||||
enum: VALID_DIFFICULTIES,
|
||||
description:
|
||||
'Niveau de difficulte : facile (application directe), moyen (plusieurs etapes/contexte nouveau), difficile (transfert/combinaison/debogage). Varie les difficultes au sein du formulaire, jamais toutes au meme niveau.'
|
||||
},
|
||||
exerciseStyle: {
|
||||
type: 'string',
|
||||
enum: VALID_STYLES,
|
||||
description:
|
||||
"Type d'exercice (methode prof, du plus au moins efficace) : prediction, debogage (trouve l'erreur), probleme_ouvert (situation reelle), projet, qcm_cible (distracteurs = erreurs typiques)."
|
||||
},
|
||||
targetsCommonError: {
|
||||
type: 'string',
|
||||
description:
|
||||
"Si exerciseStyle = 'debogage' : quelle erreur typique (identifiee dans research_topic) cette question cible precisement"
|
||||
}
|
||||
},
|
||||
required: ['question', 'type']
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['subject', 'kind', 'questions']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const concept = typeof args.concept === 'string' ? args.concept.trim() : null
|
||||
const kind = asString(args.kind, 'module') as AssessmentKind
|
||||
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!VALID_KINDS.includes(kind)) throw new Error('kind invalide')
|
||||
|
||||
const rawQuestions = Array.isArray(args.questions) ? args.questions : []
|
||||
if (rawQuestions.length === 0) throw new Error('questions manquantes (au moins une requise)')
|
||||
|
||||
const questions: ParsedQuestion[] = rawQuestions.slice(0, MAX_QUESTIONS).map((raw, index) => {
|
||||
const q = (typeof raw === 'object' && raw !== null ? raw : {}) as Record<string, unknown>
|
||||
const question = asString(q.question).trim()
|
||||
const type = asString(q.type) as ExerciseType
|
||||
const options = Array.isArray(q.options) ? q.options.map((o) => String(o)) : null
|
||||
const questionConcept = typeof q.concept === 'string' ? q.concept.trim() : null
|
||||
const difficulty =
|
||||
typeof q.difficulty === 'string' ? (q.difficulty as ExerciseDifficulty) : null
|
||||
const exerciseStyle =
|
||||
typeof q.exerciseStyle === 'string' ? normalizeStyle(q.exerciseStyle) : null
|
||||
const targetsCommonError =
|
||||
typeof q.targetsCommonError === 'string' ? q.targetsCommonError.trim() : null
|
||||
|
||||
if (!question) throw new Error(`question manquante (item ${index + 1})`)
|
||||
if (!VALID_TYPES.includes(type)) throw new Error(`type invalide (item ${index + 1})`)
|
||||
if (type === 'multiple_choice' && (!options || options.length < 2)) {
|
||||
throw new Error(
|
||||
`options manquantes ou insuffisantes pour multiple_choice (item ${index + 1})`
|
||||
)
|
||||
}
|
||||
if (difficulty && !VALID_DIFFICULTIES.includes(difficulty)) {
|
||||
throw new Error(`difficulty invalide (item ${index + 1})`)
|
||||
}
|
||||
if (q.exerciseStyle && !exerciseStyle) {
|
||||
throw new Error(`exerciseStyle invalide (item ${index + 1}) : ${VALID_STYLES.join(', ')}`)
|
||||
}
|
||||
|
||||
return {
|
||||
question,
|
||||
type,
|
||||
options,
|
||||
concept: questionConcept,
|
||||
difficulty,
|
||||
exerciseStyle,
|
||||
targetsCommonError
|
||||
}
|
||||
})
|
||||
|
||||
// Garde-fous anti-confusion de phase. kind="initial" : (1) le plan de cours complet (objectif +
|
||||
// modules + CONTENU ECRIT de chaque module) doit exister AVANT la moindre question — exige par
|
||||
// l'utilisateur : "sans objectif final defini et mesurable pas de question a poser", "tout doit
|
||||
// etre redige a l'avance et consultable avant de verifier le niveau" ; (2) une fois le niveau
|
||||
// enregistre (record_subject_level), l'evaluation initiale est terminee, ne pas la rejouer
|
||||
// (constate en test reel par le passe). kind="final" : pas avant que tous les modules soient
|
||||
// acquis (constate en test reel : Max sautait directement a la finale).
|
||||
if (kind === 'initial') {
|
||||
if (getSubjectLevel(subject)) {
|
||||
throw new Error(
|
||||
`Le niveau de "${subject}" est deja enregistre : l'evaluation initiale est terminee, ne la relance pas. Utilise kind="module" pour le module en cours (appelle get_course_plan si besoin de verifier ou tu en es).`
|
||||
)
|
||||
}
|
||||
if (!getSubjectObjective(subject)) {
|
||||
throw new Error(
|
||||
`Aucun plan de cours ecrit pour "${subject}" : appelle d'abord generate_course_plan (avec un objectif mesurable et les modules devines a partir de la recherche), avant de poser la moindre question d'evaluation.`
|
||||
)
|
||||
}
|
||||
if (listModules(subject).length === 0) {
|
||||
throw new Error(
|
||||
`Aucun module cree pour "${subject}" : appelle generate_course_plan avant de poser la moindre question d'evaluation.`
|
||||
)
|
||||
}
|
||||
if (!allModulesHaveContent(subject)) {
|
||||
throw new Error(
|
||||
`Le contenu de certains modules de "${subject}" est absent ou ne respecte pas la structure obligatoire : ${modulesMissingContent(subject).join(', ')}. Appelle write_module_content pour CHAQUE module (il precisera exactement ce qui manque) avant de poser la moindre question d'evaluation.`
|
||||
)
|
||||
}
|
||||
// Chaque question doit tester EXACTEMENT un module, pour que la reponse (correcte ou non)
|
||||
// indique directement si ce module peut etre retire du plan (deja maitrise) ou doit etre
|
||||
// garde pour l'enseignement (demande utilisateur explicite : les questions correspondent aux
|
||||
// modules, pas des questions generales deconnectees du plan).
|
||||
const moduleNames = listModules(subject).map((m) => m.name)
|
||||
const providedConcepts = questions.map((q) => q.concept)
|
||||
const missingConcept = providedConcepts.some((c) => !c)
|
||||
const unknownConcepts = providedConcepts.filter((c) => c && !moduleNames.includes(c))
|
||||
const duplicateConcepts = providedConcepts.filter(
|
||||
(c, i) => c && providedConcepts.indexOf(c) !== i
|
||||
)
|
||||
const uncoveredModules = moduleNames.filter((name) => !providedConcepts.includes(name))
|
||||
if (
|
||||
missingConcept ||
|
||||
unknownConcepts.length ||
|
||||
duplicateConcepts.length ||
|
||||
uncoveredModules.length
|
||||
) {
|
||||
throw new Error(
|
||||
`L'evaluation initiale doit poser EXACTEMENT une question par module, avec "concept" egal au nom exact du module qu'elle teste.` +
|
||||
(missingConcept ? ' Au moins une question n\'a pas de "concept".' : '') +
|
||||
(unknownConcepts.length
|
||||
? ` Concepts invalides (aucun module correspondant) : ${unknownConcepts.join(', ')}.`
|
||||
: '') +
|
||||
(duplicateConcepts.length
|
||||
? ` Modules testes plusieurs fois : ${duplicateConcepts.join(', ')}.`
|
||||
: '') +
|
||||
(uncoveredModules.length
|
||||
? ` Modules non couverts : ${uncoveredModules.join(', ')}.`
|
||||
: '')
|
||||
)
|
||||
}
|
||||
}
|
||||
if (kind === 'final') {
|
||||
const modules = listModules(subject)
|
||||
if (modules.length === 0 || !areAllModulesAcquired(subject)) {
|
||||
throw new Error(
|
||||
`Tous les modules de "${subject}" ne sont pas encore valides : l'evaluation finale ne peut pas commencer avant (utilise kind="module" pour le module en cours).`
|
||||
)
|
||||
}
|
||||
const hasDemandingQuestion = questions.some(
|
||||
(q) =>
|
||||
q.difficulty === 'difficile' ||
|
||||
(q.exerciseStyle && DEMANDING_STYLES.includes(q.exerciseStyle))
|
||||
)
|
||||
if (!hasDemandingQuestion) {
|
||||
throw new Error(
|
||||
'L\'evaluation finale doit etre exigeante : au moins une question avec difficulty="difficile" (ou exerciseStyle="projet"/"probleme_ouvert"), jamais uniquement des rappels faciles.'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const answers = await requestWrittenAnswers(
|
||||
questions.map((q) => ({ question: q.question, type: q.type, options: q.options }))
|
||||
)
|
||||
|
||||
const summaries: string[] = []
|
||||
questions.forEach((q, index) => {
|
||||
const answer = answers.at(index)
|
||||
if (answer === null || answer === undefined) {
|
||||
summaries.push(`"${q.question}" : pas de reponse (fenetre fermee ou delai depasse)`)
|
||||
return
|
||||
}
|
||||
const dontKnow = answer === DONT_KNOW_ANSWER
|
||||
saveAssessment(
|
||||
subject,
|
||||
q.concept ?? concept,
|
||||
q.question,
|
||||
q.type,
|
||||
q.options,
|
||||
answer,
|
||||
kind,
|
||||
dontKnow,
|
||||
q.difficulty,
|
||||
q.exerciseStyle,
|
||||
q.targetsCommonError
|
||||
)
|
||||
summaries.push(
|
||||
dontKnow
|
||||
? `"${q.question}" : "Je ne sais pas" (lacune enregistree, pas un echec)`
|
||||
: `"${q.question}" : "${answer}"`
|
||||
)
|
||||
})
|
||||
|
||||
return `Formulaire soumis (${questions.length} question(s)) :\n${summaries.join('\n')}`
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import {
|
||||
hasAssessment,
|
||||
hasMultipleDifficulties,
|
||||
moduleDontKnowRatio,
|
||||
upsertConceptStatus,
|
||||
getModuleOrderIndex,
|
||||
unlockNextModule
|
||||
} from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const MAX_DONT_KNOW_RATIO = 0.5
|
||||
|
||||
export const completeModule: SkillDefinition = {
|
||||
name: 'complete_module',
|
||||
description:
|
||||
"Marque un module du plan de cours comme valide/acquis et deverrouille le module suivant. Necessite qu'une evaluation ecrite (ask_written_exercise, kind='module') ait ete faite pour ce module precis, avec au moins 2 niveaux de difficulte distincts (jamais uniquement du facile), ET que l'utilisateur ait reellement reussi (moins de la moitie des reponses en \"Je ne sais pas\" — un module valide uniquement s'il y a reussite, pas juste une tentative) : echoue sinon.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
module: { type: 'string', description: 'Nom du module valide' }
|
||||
},
|
||||
required: ['subject', 'module']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const module = asString(args.module).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!module) throw new Error('module manquant')
|
||||
|
||||
if (!hasAssessment(subject, module, 'module')) {
|
||||
throw new Error(
|
||||
`Aucune evaluation ecrite enregistree pour le module "${module}" (${subject}) : appelle ask_written_exercise (kind="module") avant.`
|
||||
)
|
||||
}
|
||||
if (!hasMultipleDifficulties(subject, module)) {
|
||||
throw new Error(
|
||||
`Les exercices du module "${module}" (${subject}) n'utilisent qu'un seul niveau de difficulte : pose au moins 2 niveaux distincts (ask_written_exercise, difficulty) avant de valider le module.`
|
||||
)
|
||||
}
|
||||
const dontKnowRatio = moduleDontKnowRatio(subject, module)
|
||||
if (dontKnowRatio > MAX_DONT_KNOW_RATIO) {
|
||||
throw new Error(
|
||||
`Trop de reponses "Je ne sais pas" sur les exercices du module "${module}" (${Math.round(dontKnowRatio * 100)}%) : le module n'est pas encore maitrise. Continue a l'enseigner (write_module_content si besoin) et repose des questions avant de le valider.`
|
||||
)
|
||||
}
|
||||
|
||||
const orderIndex = getModuleOrderIndex(subject, module)
|
||||
if (orderIndex === null) throw new Error(`Module "${module}" introuvable pour "${subject}"`)
|
||||
|
||||
upsertConceptStatus(subject, module, 'acquired')
|
||||
unlockNextModule(subject, orderIndex)
|
||||
|
||||
return `Module "${module}" valide. Le module suivant (s'il existe) est maintenant accessible.`
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import { areAllModulesAcquired, hasAssessment, setSubjectStatus } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const completeSubject: SkillDefinition = {
|
||||
name: 'complete_subject',
|
||||
description:
|
||||
"Marque un sujet comme maitrise, apres que tous ses modules sont valides ET qu'une evaluation finale globale (ask_written_exercise, kind='final') a ete faite. Echoue sinon.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" }
|
||||
},
|
||||
required: ['subject']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
|
||||
if (!areAllModulesAcquired(subject)) {
|
||||
throw new Error(`Tous les modules de "${subject}" ne sont pas encore valides.`)
|
||||
}
|
||||
if (!hasAssessment(subject, undefined, 'final')) {
|
||||
throw new Error(
|
||||
`Aucune evaluation finale enregistree pour "${subject}" : appelle ask_written_exercise (kind="final") avant.`
|
||||
)
|
||||
}
|
||||
|
||||
setSubjectStatus(subject, 'mastered')
|
||||
return `"${subject}" est maintenant maitrise !`
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
import { renderMermaid, playCaption } from '../../coach/drawingWindow'
|
||||
import { synthesizeSpeech } from '../../ai/elevenlabs'
|
||||
import { saveModuleDiagram } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const MAX_CAPTIONS = 12
|
||||
const CAPTION_MAX_LEN = 300
|
||||
const MERMAID_MAX_LEN = 4000
|
||||
|
||||
export const drawFlowDiagram: SkillDefinition = {
|
||||
name: 'draw_flow_diagram',
|
||||
description:
|
||||
"Dessine un cycle, une hierarchie, un flux ou un processus a etapes (ex: cycle de l'eau, organigramme) en syntaxe Mermaid (graph/flowchart), rendu par un vrai moteur de mise en page automatique — jamais de coordonnees manuelles pour ce type de diagramme, un modele economique les calcule mal. Donne aussi une liste de captions courtes, prononcees en sequence une fois le diagramme affiche, pour expliquer etape par etape.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Titre du diagramme' },
|
||||
subject: {
|
||||
type: 'string',
|
||||
description: "Sujet d'apprentissage concerne (pour conserver ce diagramme dans le module)"
|
||||
},
|
||||
module: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Module concerne : si fourni avec subject, le diagramme est conserve et relisible plus tard dans la page de progression'
|
||||
},
|
||||
mermaid: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Code Mermaid valide (ex: "graph LR; Evaporation --> Condensation --> Precipitation --> Infiltration --> Evaporation")'
|
||||
},
|
||||
captions: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description:
|
||||
'Phrases dites a voix haute en sequence une fois le diagramme affiche, une par etape'
|
||||
}
|
||||
},
|
||||
required: ['title', 'mermaid']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const title = asString(args.title, 'Diagramme').trim() || 'Diagramme'
|
||||
const subject = typeof args.subject === 'string' ? args.subject.trim() : null
|
||||
const module = typeof args.module === 'string' ? args.module.trim() : null
|
||||
const mermaidCode = asString(args.mermaid).trim().slice(0, MERMAID_MAX_LEN)
|
||||
if (!mermaidCode) throw new Error('mermaid manquant')
|
||||
|
||||
const captions = (Array.isArray(args.captions) ? args.captions : [])
|
||||
.map((c) => String(c).trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, MAX_CAPTIONS)
|
||||
.map((c) => c.slice(0, CAPTION_MAX_LEN))
|
||||
|
||||
if (captions.length === 0) {
|
||||
throw new Error(
|
||||
"Aucune caption fournie : un diagramme sans narration n'est jamais accepte. Donne au moins une phrase par etape importante."
|
||||
)
|
||||
}
|
||||
|
||||
await renderMermaid(title, mermaidCode)
|
||||
|
||||
for (const caption of captions) {
|
||||
try {
|
||||
const speech = await synthesizeSpeech(caption)
|
||||
const audio = speech.buffer.slice(
|
||||
speech.byteOffset,
|
||||
speech.byteOffset + speech.byteLength
|
||||
) as ArrayBuffer
|
||||
await playCaption(audio)
|
||||
} catch (error) {
|
||||
console.error('[coach] echec narration de diagramme', error)
|
||||
}
|
||||
}
|
||||
|
||||
if (subject && module) {
|
||||
saveModuleDiagram(subject, module, 'mermaid', title, { title, mermaidCode })
|
||||
}
|
||||
|
||||
return `Diagramme "${title}" affiche dans la fenetre dediee.`
|
||||
}
|
||||
}
|
||||
@@ -1,245 +0,0 @@
|
||||
import { openDrawingWindow, revealShape } from '../../coach/drawingWindow'
|
||||
import { synthesizeSpeech } from '../../ai/elevenlabs'
|
||||
import { PRESET_GENERATORS } from '../../coach/presets'
|
||||
import { saveModuleDiagram } from '../../coach/coachStore'
|
||||
import type { DrawShape, ShapeType } from '../../../shared/drawing'
|
||||
import type { Drawing } from '../../../shared/drawing'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const MANUAL_SHAPE_TYPES: ShapeType[] = ['rect', 'circle', 'line', 'arrow', 'text', 'stroke', 'arc']
|
||||
const PRESET_NAMES = [...PRESET_GENERATORS.keys()]
|
||||
const DEFAULT_WIDTH = 700
|
||||
const DEFAULT_HEIGHT = 500
|
||||
const NO_CAPTION_DELAY_MS = 500
|
||||
const CAPTION_MAX_LEN = 300
|
||||
const TEXT_MAX_LEN = 200
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(Math.max(value, min), max)
|
||||
}
|
||||
|
||||
function sanitizeNumber(value: unknown, fallback: number, min: number, max: number): number {
|
||||
const n = Number(value)
|
||||
if (!Number.isFinite(n)) return fallback
|
||||
return clamp(n, min, max)
|
||||
}
|
||||
|
||||
function clampCommonFields(shape: DrawShape): DrawShape {
|
||||
return {
|
||||
...shape,
|
||||
caption: shape.caption ? shape.caption.trim().slice(0, CAPTION_MAX_LEN) : undefined,
|
||||
content: shape.content ? shape.content.slice(0, TEXT_MAX_LEN) : shape.content
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce et borne une forme manuelle venue du modele dans les limites du canvas : jamais de markup
|
||||
* possible ici, uniquement des nombres/chaines simples passes en parametres a roughjs/canvas.
|
||||
*/
|
||||
function sanitizeManualShape(
|
||||
raw: Record<string, unknown>,
|
||||
type: ShapeType,
|
||||
width: number,
|
||||
height: number
|
||||
): DrawShape | null {
|
||||
const num = (key: string, fallback = 0): number =>
|
||||
sanitizeNumber(Reflect.get(raw, key), fallback, 0, Math.max(width, height))
|
||||
const caption =
|
||||
typeof raw.caption === 'string' && raw.caption.trim() ? raw.caption.trim() : undefined
|
||||
|
||||
if (type === 'stroke') {
|
||||
const rawPoints = Array.isArray(raw.points) ? raw.points : []
|
||||
const points = rawPoints
|
||||
.filter((p): p is { x: unknown; y: unknown } => typeof p === 'object' && p !== null)
|
||||
.map((p) => ({
|
||||
x: sanitizeNumber((p as Record<string, unknown>).x, 0, 0, width),
|
||||
y: sanitizeNumber((p as Record<string, unknown>).y, 0, 0, height)
|
||||
}))
|
||||
if (points.length < 2) return null
|
||||
return { type, points, caption, color: typeof raw.color === 'string' ? raw.color : undefined }
|
||||
}
|
||||
|
||||
const base: DrawShape = {
|
||||
type,
|
||||
x: num('x'),
|
||||
y: num('y'),
|
||||
caption,
|
||||
color: typeof raw.color === 'string' ? raw.color : undefined,
|
||||
label: typeof raw.label === 'string' ? raw.label : undefined
|
||||
}
|
||||
|
||||
if (type === 'rect') {
|
||||
base.width = num('width', 50)
|
||||
base.height = num('height', 50)
|
||||
} else if (type === 'circle') {
|
||||
base.radius = num('radius', 25)
|
||||
} else if (type === 'line' || type === 'arrow') {
|
||||
base.x2 = num('x2')
|
||||
base.y2 = num('y2')
|
||||
} else if (type === 'arc') {
|
||||
base.radius = num('radius', 25)
|
||||
base.startAngle = sanitizeNumber(raw.startAngle, 0, -360, 360)
|
||||
base.endAngle = sanitizeNumber(raw.endAngle, 90, -360, 360)
|
||||
base.closed = raw.closed === true
|
||||
} else if (type === 'text') {
|
||||
base.content = typeof raw.content === 'string' ? raw.content : ''
|
||||
if (!base.content) return null
|
||||
}
|
||||
|
||||
return base
|
||||
}
|
||||
|
||||
/** Expand un preset (geometrie calculee par le code) en une liste de formes reelles. */
|
||||
function expandPreset(raw: Record<string, unknown>): DrawShape[] {
|
||||
const presetName = asString(raw.preset)
|
||||
const generator = PRESET_GENERATORS.get(presetName)
|
||||
if (!generator) {
|
||||
throw new Error(
|
||||
`Preset inconnu: "${presetName}". Presets disponibles: ${PRESET_NAMES.join(', ')}`
|
||||
)
|
||||
}
|
||||
const params =
|
||||
typeof raw.presetParams === 'object' && raw.presetParams !== null
|
||||
? (raw.presetParams as Record<string, unknown>)
|
||||
: raw
|
||||
return generator(params)
|
||||
}
|
||||
|
||||
export const drawSchema: SkillDefinition = {
|
||||
name: 'draw_schema',
|
||||
description:
|
||||
"Dessine et NARRE un schema pas a pas, forme par forme, dans une fenetre dediee (jamais une image figee d'un coup). Pour toute figure geometrique/mathematique (triangle, polygone, camembert, Venn, axes...), utilise OBLIGATOIREMENT un preset (type: 'preset') plutot que des formes manuelles : le code calcule les vraies coordonnees, toi tu ne donnes que des labels/captions. Les formes manuelles (rect/circle/line/arrow/text/arc/stroke) sont reservees a de l'annotation simple et independante, jamais a une figure a plusieurs sommets relies (un modele economique calcule mal ce genre de coordonnees). Donne a chaque forme/preset une 'caption' : c'est le mecanisme de narration synchronisee, pas le texte de ta reponse.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Titre du dessin' },
|
||||
subject: {
|
||||
type: 'string',
|
||||
description: "Sujet d'apprentissage concerne (pour conserver ce dessin dans le module)"
|
||||
},
|
||||
module: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Module concerne : si fourni avec subject, le dessin est conserve et relisible plus tard dans la page de progression'
|
||||
},
|
||||
width: { type: 'number', description: 'Largeur du canvas en pixels (defaut 700)' },
|
||||
height: { type: 'number', description: 'Hauteur du canvas en pixels (defaut 500)' },
|
||||
shapes: {
|
||||
type: 'array',
|
||||
description:
|
||||
"Formes a dessiner dans l'ordre (ou presets a expand). Chacune peut porter une 'caption' dite a voix haute au moment ou elle apparait.",
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
type: {
|
||||
type: 'string',
|
||||
enum: [...MANUAL_SHAPE_TYPES, 'preset'],
|
||||
description:
|
||||
"'preset' pour une figure geometrique (voir 'preset'/'presetParams'), sinon rect/circle/line/arrow/text/arc/stroke pour de l'annotation simple"
|
||||
},
|
||||
preset: {
|
||||
type: 'string',
|
||||
enum: PRESET_NAMES,
|
||||
description: `Nom du preset si type='preset' : ${PRESET_NAMES.join(', ')}`
|
||||
},
|
||||
presetParams: {
|
||||
type: 'object',
|
||||
description:
|
||||
'Parametres semantiques du preset (labels, captions, tailles...) — jamais de coordonnees de sommets, le code les calcule'
|
||||
},
|
||||
x: { type: 'number' },
|
||||
y: { type: 'number' },
|
||||
x2: { type: 'number', description: "Point d'arrivee pour line/arrow" },
|
||||
y2: { type: 'number', description: "Point d'arrivee pour line/arrow" },
|
||||
width: { type: 'number', description: 'Pour rect' },
|
||||
height: { type: 'number', description: 'Pour rect' },
|
||||
radius: { type: 'number', description: 'Pour circle/arc' },
|
||||
startAngle: { type: 'number', description: 'Pour arc, en degres' },
|
||||
endAngle: { type: 'number', description: 'Pour arc, en degres' },
|
||||
content: { type: 'string', description: 'Texte affiche pour type text' },
|
||||
label: {
|
||||
type: 'string',
|
||||
description: 'Legende visuelle optionnelle sur rect/circle/line/arrow'
|
||||
},
|
||||
caption: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Ce que tu dis a voix haute pendant que cette forme apparait (narration pas-a-pas)'
|
||||
},
|
||||
color: { type: 'string', description: 'Couleur CSS simple (ex: "red", "#3366ff")' },
|
||||
points: {
|
||||
type: 'array',
|
||||
description: 'Liste de points {x, y} pour un trait libre (type stroke)',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: { x: { type: 'number' }, y: { type: 'number' } },
|
||||
required: ['x', 'y']
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['type']
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['title', 'shapes']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const title = asString(args.title, 'Schema').trim() || 'Schema'
|
||||
const subject = typeof args.subject === 'string' ? args.subject.trim() : null
|
||||
const module = typeof args.module === 'string' ? args.module.trim() : null
|
||||
const width = sanitizeNumber(args.width, DEFAULT_WIDTH, 200, 2000)
|
||||
const height = sanitizeNumber(args.height, DEFAULT_HEIGHT, 200, 2000)
|
||||
const rawShapes = Array.isArray(args.shapes) ? args.shapes : []
|
||||
|
||||
const shapes: DrawShape[] = []
|
||||
for (const raw of rawShapes) {
|
||||
if (typeof raw !== 'object' || raw === null) continue
|
||||
const entry = raw as Record<string, unknown>
|
||||
const type = asString(entry.type) as ShapeType
|
||||
|
||||
if (type === 'preset') {
|
||||
shapes.push(...expandPreset(entry).map(clampCommonFields))
|
||||
continue
|
||||
}
|
||||
if (MANUAL_SHAPE_TYPES.includes(type)) {
|
||||
const shape = sanitizeManualShape(entry, type, width, height)
|
||||
if (shape) shapes.push(clampCommonFields(shape))
|
||||
}
|
||||
}
|
||||
|
||||
if (shapes.length === 0) throw new Error('Aucune forme valide a dessiner')
|
||||
if (shapes.every((s) => !s.caption)) {
|
||||
throw new Error(
|
||||
"Aucune caption fournie : un dessin sans narration n'est jamais accepte. Donne une caption a au moins les formes importantes pour expliquer ce que tu dessines."
|
||||
)
|
||||
}
|
||||
|
||||
await openDrawingWindow(title, width, height)
|
||||
|
||||
for (const shape of shapes) {
|
||||
if (shape.caption) {
|
||||
try {
|
||||
const speech = await synthesizeSpeech(shape.caption)
|
||||
const audio = speech.buffer.slice(
|
||||
speech.byteOffset,
|
||||
speech.byteOffset + speech.byteLength
|
||||
) as ArrayBuffer
|
||||
await revealShape(shape, audio)
|
||||
continue
|
||||
} catch (error) {
|
||||
console.error('[coach] echec narration d’une forme', error)
|
||||
}
|
||||
}
|
||||
await revealShape(shape, null)
|
||||
await new Promise((resolve) => setTimeout(resolve, NO_CAPTION_DELAY_MS))
|
||||
}
|
||||
|
||||
if (subject && module) {
|
||||
const drawing: Drawing = { title, width, height, shapes }
|
||||
saveModuleDiagram(subject, module, 'shapes', title, drawing)
|
||||
}
|
||||
|
||||
return `Dessin "${title}" termine (${shapes.length} forme(s)) dans la fenetre dediee.`
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import { getResearchSummary, createModules, setSubjectObjective } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const MAX_MODULES = 12
|
||||
|
||||
export const generateCoursePlan: SkillDefinition = {
|
||||
name: 'generate_course_plan',
|
||||
description:
|
||||
"Cree (ou REVISE : ajoute/supprime/modifie des modules) le plan de cours. Premier appel : juste apres research_topic, AVANT toute question d'evaluation — les modules sont devines a partir de la recherche (concepts cles), pas encore de l'evaluation puisqu'elle n'a pas eu lieu. Deuxieme appel (revision), apres l'evaluation initiale et record_subject_level : ajuste les modules (ajoute/supprime/modifie) selon les lacunes reellement identifiees - un module absent de la nouvelle liste est supprime (sauf s'il est deja acquis ou deja evalue, protege automatiquement). Necessite qu'une recherche (research_topic) ait deja ete faite pour ce sujet : echoue sinon. Exige un objectif final mesurable (methode Backward Design) : une phrase concrete du type \"Tu seras capable de [faire X] dans [situation Y]\", jamais \"comprendre\" ou \"savoir\". Seul le premier module est accessible au depart, les suivants se deverrouillent au fur et a mesure. IMPORTANT : chaque module cree ou modifie doit ensuite recevoir son contenu complet via write_module_content avant de pouvoir commencer l'evaluation initiale (ask_written_exercise refuse techniquement sinon).",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
objective: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Objectif final mesurable et concret : "Tu seras capable de [faire X] dans [situation Y]"'
|
||||
},
|
||||
modules: {
|
||||
type: 'array',
|
||||
description:
|
||||
"Modules dans l'ordre d'enseignement souhaite. SEUL le nom est fourni ici : le contenu complet (6 sections, voir write_module_content) est redige SEPAREMENT par write_module_content, jamais ici — tout champ de contenu passe a cet outil est ignore.",
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string', description: 'Nom court du module/concept' }
|
||||
},
|
||||
required: ['name']
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['subject', 'objective', 'modules']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const objective = asString(args.objective).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!objective) throw new Error('objective manquant')
|
||||
|
||||
if (!getResearchSummary(subject)) {
|
||||
throw new Error(
|
||||
`Aucune recherche enregistree pour "${subject}" : appelle research_topic d'abord.`
|
||||
)
|
||||
}
|
||||
|
||||
const rawModules = Array.isArray(args.modules) ? args.modules : []
|
||||
const modules = rawModules
|
||||
.filter((m): m is Record<string, unknown> => typeof m === 'object' && m !== null)
|
||||
.map((m) => ({ name: asString(m.name).trim() }))
|
||||
.filter((m) => m.name)
|
||||
.slice(0, MAX_MODULES)
|
||||
|
||||
if (modules.length === 0) throw new Error('Aucun module valide fourni')
|
||||
|
||||
createModules(subject, modules)
|
||||
setSubjectObjective(subject, objective)
|
||||
|
||||
return `Plan de cours enregistre pour "${subject}" : ${modules.length} module(s) (${modules.map((m) => m.name).join(', ')}). Appelle maintenant write_module_content pour CHAQUE module afin d'ecrire son contenu complet avant de commencer l'evaluation initiale (ask_written_exercise refuse sinon).`
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import {
|
||||
getResearchSummary,
|
||||
listModules,
|
||||
getProgress,
|
||||
getModuleDetail
|
||||
} from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const getCoursePlan: SkillDefinition = {
|
||||
name: 'get_course_plan',
|
||||
description:
|
||||
"Lit l'etat actuel d'un sujet (recherche deja faite, niveau evalue, modules et leur statut/verrouillage, contenu complet du module en cours). A appeler en debut de session si l'utilisateur mentionne un sujet deja entame (pour reprendre exactement la ou le plan de cours en etait reste), ou avant d'enseigner/evaluer un module pour relire ce qui a deja ete ecrit et rester coherent.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" }
|
||||
},
|
||||
required: ['subject']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
|
||||
const research = getResearchSummary(subject)
|
||||
const modules = listModules(subject)
|
||||
const progress = getProgress(subject)[0]
|
||||
|
||||
if (!research && modules.length === 0) {
|
||||
return `Aucun plan de cours existant pour "${subject}" : commence par research_topic.`
|
||||
}
|
||||
|
||||
const modulesText = modules.length
|
||||
? modules.map((m) => `- ${m.name} : ${m.status}${m.locked ? ' (verrouille)' : ''}`).join('\n')
|
||||
: "Aucun module cree pour l'instant (fais generate_course_plan apres l'evaluation initiale)."
|
||||
|
||||
const currentModule = modules.find((m) => !m.locked && m.status !== 'acquired')
|
||||
const currentModuleDetail = currentModule ? getModuleDetail(subject, currentModule.name) : null
|
||||
|
||||
const lines = [
|
||||
`Sujet "${subject}" — statut: ${progress?.status ?? 'inconnu'}, niveau: ${progress?.level ?? 'non evalue'}.`,
|
||||
research ? 'Recherche deja effectuee.' : 'Recherche pas encore faite.',
|
||||
'Modules:',
|
||||
modulesText
|
||||
]
|
||||
|
||||
if (currentModuleDetail) {
|
||||
lines.push(
|
||||
`\nModule en cours : "${currentModuleDetail.name}" (${currentModuleDetail.status}).`
|
||||
)
|
||||
lines.push(
|
||||
currentModuleDetail.theorySummary
|
||||
? `Contenu deja ecrit pour ce module :\n${currentModuleDetail.theorySummary}`
|
||||
: "Aucun contenu ecrit pour ce module pour l'instant : appelle write_module_content avant de l'enseigner."
|
||||
)
|
||||
}
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { trackConceptMastery } from './trackConceptMastery'
|
||||
import { askWrittenExercise } from './askWrittenExercise'
|
||||
import { recordSubjectLevel } from './recordSubjectLevel'
|
||||
import { drawSchema } from './drawSchema'
|
||||
import { drawFlowDiagram } from './drawFlowDiagram'
|
||||
import { researchTopic } from './researchTopic'
|
||||
import { getCoursePlan } from './getCoursePlan'
|
||||
import { generateCoursePlan } from './generateCoursePlan'
|
||||
import { completeModule } from './completeModule'
|
||||
import { completeSubject } from './completeSubject'
|
||||
import { writeModuleContent } from './writeModuleContent'
|
||||
import { openModuleForUser } from './openModuleForUser'
|
||||
|
||||
export const coachSkills: SkillDefinition[] = [
|
||||
trackConceptMastery,
|
||||
askWrittenExercise,
|
||||
recordSubjectLevel,
|
||||
drawSchema,
|
||||
drawFlowDiagram,
|
||||
researchTopic,
|
||||
getCoursePlan,
|
||||
generateCoursePlan,
|
||||
completeModule,
|
||||
completeSubject,
|
||||
writeModuleContent,
|
||||
openModuleForUser
|
||||
]
|
||||
@@ -1,41 +0,0 @@
|
||||
import { getModuleDetail } from '../../coach/coachStore'
|
||||
import { openCoachProgressWindow } from '../../coach/progressWindow'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const openModuleForUser: SkillDefinition = {
|
||||
name: 'open_module_for_user',
|
||||
description:
|
||||
"Ouvre directement la page du module dans la fenetre de progression, pour que l'utilisateur l'etudie par lui-meme (texte complet + schemas deja prets) — Max ne fait plus de cours a l'oral (demande utilisateur explicite) : annonce l'ouverture en une phrase courte, appelle cet outil, puis ARRETE-TOI LA. Si l'utilisateur pose une question orale ensuite, reponds-y normalement ; si elle revele un trou dans le contenu, enrichis-le via write_module_content.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
module: { type: 'string', description: 'Module a ouvrir (deja deverrouille et ecrit)' }
|
||||
},
|
||||
required: ['subject', 'module']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const module = asString(args.module).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!module) throw new Error('module manquant')
|
||||
|
||||
const detail = getModuleDetail(subject, module)
|
||||
if (!detail) throw new Error(`Module "${module}" introuvable pour "${subject}"`)
|
||||
if (detail.locked) {
|
||||
throw new Error(
|
||||
`Le module "${module}" est encore verrouille : le module precedent doit etre valide avant.`
|
||||
)
|
||||
}
|
||||
if (!detail.theorySummary || !detail.theorySummary.trim()) {
|
||||
throw new Error(
|
||||
`Le contenu du module "${module}" n'est pas encore ecrit : appelle write_module_content avant de l'ouvrir.`
|
||||
)
|
||||
}
|
||||
|
||||
openCoachProgressWindow({ subject, module })
|
||||
|
||||
return `Module "${module}" ouvert pour l'utilisateur dans la page de progression.`
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { hasAssessment, setSubjectLevel, setSubjectStatus } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const recordSubjectLevel: SkillDefinition = {
|
||||
name: 'record_subject_level',
|
||||
description:
|
||||
"Enregistre le niveau evalue de l'utilisateur sur un sujet (debutant/intermediaire/avance), a l'issue de l'evaluation initiale. Necessite qu'au moins une question ait ete posee a l'ecrit via ask_written_exercise pour ce sujet : echoue sinon.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
level: {
|
||||
type: 'string',
|
||||
description: 'Niveau evalue (ex: "debutant", "intermediaire", "avance")'
|
||||
}
|
||||
},
|
||||
required: ['subject', 'level']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const level = asString(args.level).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!level) throw new Error('level manquant')
|
||||
|
||||
if (!hasAssessment(subject)) {
|
||||
throw new Error(
|
||||
`Aucune evaluation ecrite enregistree pour "${subject}" : appelle ask_written_exercise avant de fixer un niveau.`
|
||||
)
|
||||
}
|
||||
|
||||
setSubjectLevel(subject, level)
|
||||
setSubjectStatus(subject, 'in_progress')
|
||||
return `Niveau de "${subject}" enregistre : ${level}.`
|
||||
}
|
||||
}
|
||||
@@ -1,200 +0,0 @@
|
||||
import { setResearchSummary, setSubjectStatus } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
/** Limite chaque section pour eviter un stockage demesure, sans etre restrictif pour une vraie synthese. */
|
||||
const SECTION_MAX_LEN = 2000
|
||||
|
||||
function clamp(value: unknown): string {
|
||||
return asString(value).trim().slice(0, SECTION_MAX_LEN)
|
||||
}
|
||||
|
||||
const MIN_KEY_CONCEPTS = 5
|
||||
const MAX_KEY_CONCEPTS = 10
|
||||
const MIN_COMMON_ERRORS = 3
|
||||
|
||||
function clampList(value: unknown, max: number): string[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
return value
|
||||
.map((v) => asString(v).trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, max)
|
||||
}
|
||||
|
||||
// RÈGLE 2 de docs/Max_Recherche_Sources_Coach.md : minimum de sources selon le type de sujet
|
||||
// (borne basse retenue pour chaque plage, ex. "6 a 8" -> 6).
|
||||
const DOMAIN_MIN_SOURCES = new Map<string, number>([
|
||||
['math_science', 5],
|
||||
['computer_science', 6],
|
||||
['humanities', 7],
|
||||
['medicine_law_finance', 10],
|
||||
['specialized_rare', 5]
|
||||
])
|
||||
const VALID_DOMAINS = [...DOMAIN_MIN_SOURCES.keys()]
|
||||
const VALID_LEVELS = [1, 2, 3, 4]
|
||||
const MAX_SOURCES = 20
|
||||
|
||||
interface ParsedSource {
|
||||
title: string
|
||||
url: string
|
||||
level: number
|
||||
}
|
||||
|
||||
export const researchTopic: SkillDefinition = {
|
||||
name: 'research_topic',
|
||||
description:
|
||||
"Premiere etape OBLIGATOIRE quand l'utilisateur veut apprendre un sujet. Suit docs/Max_Recherche_Sources_Coach.md : Max ne genere JAMAIS un cours depuis sa seule memoire. Avant cet appel, mene une vraie recherche web avec search_web sur 5 axes (histoire/contexte, definition/theorie, applications concretes, erreurs typiques, ressources pedagogiques existantes), EN SILENCE (resultats texte uniquement, jamais annonce a l'oral). Compile ensuite les sources trouvees dans le champ 'sources' (titre, URL exacte renvoyee par search_web, niveau de fiabilite 1 a 4). Nombre minimum de sources selon le sujet : maths/sciences 5, informatique 6 a 8, sciences humaines 7 a 10, medecine/droit/finance 10, sujet rare 5 minimum + signalement explicite dans notDocumented. Jamais une source niveau 4 seule (Wikipedia, forums, blogs non identifies) : au moins une source niveau 1, 2 ou 3 requise. Precise aussi 5 a 10 concepts cles, les 3 erreurs typiques les plus frequentes, et une explication 'methode Feynman' (comme a un enfant de 12 ans, sans jargon) prouvant que tu maitrises le sujet avant de l'enseigner — si tu ne peux pas l'ecrire simplement, cherche davantage avant d'appeler cet outil.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
subjectDomain: {
|
||||
type: 'string',
|
||||
enum: VALID_DOMAINS,
|
||||
description:
|
||||
'Categorie du sujet, determine le nombre minimum de sources exige : math_science, computer_science, humanities, medicine_law_finance, specialized_rare'
|
||||
},
|
||||
sources: {
|
||||
type: 'array',
|
||||
description:
|
||||
"Sources reellement consultees via search_web (titre + URL exacte renvoyee par l'outil, jamais inventee). Niveau 1 = reference absolue (universites, documentation officielle, revues scientifiques, institutions) ; 2 = pedagogique fiable (Khan Academy, OpenStax, Eduscol) ; 3 = complementaire (blogs d'experts identifies, tutoriels officiels) ; 4 = a utiliser avec precaution (Wikipedia, forums) — jamais seul.",
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Titre de la page/source' },
|
||||
url: { type: 'string', description: 'URL exacte renvoyee par search_web' },
|
||||
level: { type: 'number', enum: VALID_LEVELS, description: 'Niveau de fiabilite 1 a 4' }
|
||||
},
|
||||
required: ['title', 'url', 'level']
|
||||
}
|
||||
},
|
||||
definition: { type: 'string', description: "Definition claire : qu'est-ce que c'est ?" },
|
||||
usageToday: { type: 'string', description: "A quoi ca sert aujourd'hui ?" },
|
||||
whyUsedToday: { type: 'string', description: "Pourquoi on s'en sert aujourd'hui ?" },
|
||||
practicalCases: { type: 'string', description: 'Quels sont les cas pratiques ?' },
|
||||
application: { type: 'string', description: 'Comment mettre en application le sujet ?' },
|
||||
prerequisites: {
|
||||
type: 'string',
|
||||
description:
|
||||
"Prerequis necessaires avant de commencer ce sujet (ce que l'eleve doit deja savoir)"
|
||||
},
|
||||
keyConcepts: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description: '5 a 10 concepts cles du sujet, du plus simple au plus complexe'
|
||||
},
|
||||
commonErrors: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description: 'Les 3 erreurs typiques les plus frequentes sur ce sujet'
|
||||
},
|
||||
feynmanExplanation: {
|
||||
type: 'string',
|
||||
description:
|
||||
"Explication du sujet en langage simple, comme a un enfant de 12 ans, avec une analogie : preuve que tu maitrises le sujet avant de l'enseigner (technique Feynman)"
|
||||
},
|
||||
wellDocumented: {
|
||||
type: 'string',
|
||||
description: 'Aspects du sujet bien documentes par au moins 2 sources independantes'
|
||||
},
|
||||
partiallyDocumented: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Aspects documentes par une seule source (a mentionner avec nuance) — laisser vide si aucun'
|
||||
},
|
||||
notDocumented: {
|
||||
type: 'string',
|
||||
description:
|
||||
"Aspects pour lesquels aucune source fiable n'a ete trouvee, ou signalement si le sujet est rare/peu documente — laisser vide si aucun"
|
||||
}
|
||||
},
|
||||
required: [
|
||||
'subject',
|
||||
'subjectDomain',
|
||||
'sources',
|
||||
'definition',
|
||||
'usageToday',
|
||||
'whyUsedToday',
|
||||
'practicalCases',
|
||||
'application',
|
||||
'prerequisites',
|
||||
'keyConcepts',
|
||||
'commonErrors',
|
||||
'feynmanExplanation'
|
||||
]
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
|
||||
const subjectDomain = asString(args.subjectDomain).trim()
|
||||
if (!VALID_DOMAINS.includes(subjectDomain)) {
|
||||
throw new Error(`subjectDomain invalide : ${VALID_DOMAINS.join(', ')}`)
|
||||
}
|
||||
|
||||
const rawSources = Array.isArray(args.sources) ? args.sources : []
|
||||
const sources: ParsedSource[] = rawSources.slice(0, MAX_SOURCES).map((raw, index) => {
|
||||
const s = (typeof raw === 'object' && raw !== null ? raw : {}) as Record<string, unknown>
|
||||
const title = asString(s.title).trim()
|
||||
const url = asString(s.url).trim()
|
||||
const level = Number(s.level)
|
||||
if (!title) throw new Error(`source sans titre (item ${index + 1})`)
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
throw new Error(`source sans URL valide (item ${index + 1}) : "${url}"`)
|
||||
}
|
||||
if (!VALID_LEVELS.includes(level)) {
|
||||
throw new Error(`niveau de source invalide (item ${index + 1}) : doit etre 1, 2, 3 ou 4`)
|
||||
}
|
||||
return { title, url, level }
|
||||
})
|
||||
|
||||
const minSources = DOMAIN_MIN_SOURCES.get(subjectDomain) ?? 5
|
||||
if (sources.length < minSources) {
|
||||
throw new Error(
|
||||
`Au moins ${minSources} sources requises pour un sujet "${subjectDomain}" (${sources.length} fournie(s)). Utilise search_web sur les 5 axes (histoire, definition/theorie, applications, erreurs typiques, ressources pedagogiques) avant d'appeler research_topic.`
|
||||
)
|
||||
}
|
||||
if (!sources.some((s) => s.level <= 3)) {
|
||||
throw new Error(
|
||||
'Au moins une source de niveau 1, 2 ou 3 est requise : impossible de se baser uniquement sur des sources de niveau 4 (Wikipedia, forums, blogs non identifies).'
|
||||
)
|
||||
}
|
||||
|
||||
const keyConcepts = clampList(args.keyConcepts, MAX_KEY_CONCEPTS)
|
||||
const commonErrors = clampList(args.commonErrors, MIN_COMMON_ERRORS + 2)
|
||||
|
||||
const textSections = {
|
||||
definition: clamp(args.definition),
|
||||
usageToday: clamp(args.usageToday),
|
||||
whyUsedToday: clamp(args.whyUsedToday),
|
||||
practicalCases: clamp(args.practicalCases),
|
||||
application: clamp(args.application),
|
||||
prerequisites: clamp(args.prerequisites),
|
||||
feynmanExplanation: clamp(args.feynmanExplanation)
|
||||
}
|
||||
const sections = {
|
||||
...textSections,
|
||||
subjectDomain,
|
||||
sources,
|
||||
keyConcepts,
|
||||
commonErrors,
|
||||
wellDocumented: clamp(args.wellDocumented),
|
||||
partiallyDocumented: clamp(args.partiallyDocumented),
|
||||
notDocumented: clamp(args.notDocumented)
|
||||
}
|
||||
if (Object.values(textSections).some((s) => !s)) {
|
||||
throw new Error('Toutes les sections textuelles de la recherche sont requises')
|
||||
}
|
||||
if (keyConcepts.length < MIN_KEY_CONCEPTS) {
|
||||
throw new Error(`keyConcepts doit contenir au moins ${MIN_KEY_CONCEPTS} concepts`)
|
||||
}
|
||||
if (commonErrors.length < MIN_COMMON_ERRORS) {
|
||||
throw new Error(`commonErrors doit contenir au moins ${MIN_COMMON_ERRORS} erreurs typiques`)
|
||||
}
|
||||
|
||||
setResearchSummary(subject, JSON.stringify(sections))
|
||||
setSubjectStatus(subject, 'assessing')
|
||||
|
||||
return `Recherche sur "${subject}" enregistree (${sources.length} sources, prerequis, ${keyConcepts.length} concepts cles, ${commonErrors.length} erreurs typiques, explication Feynman). Passe maintenant au plan de cours (generate_course_plan).`
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
import { upsertConceptStatus, hasAssessment, type ConceptStatus } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const VALID_STATUSES: ConceptStatus[] = ['not_started', 'in_progress', 'acquired', 'to_review']
|
||||
const EVALUATED_STATUSES: ConceptStatus[] = ['acquired', 'to_review']
|
||||
|
||||
export const trackConceptMastery: SkillDefinition = {
|
||||
name: 'track_concept_mastery',
|
||||
description:
|
||||
"Enregistre l'etat de maitrise d'un concept pour un sujet d'apprentissage en cours (not_started, in_progress, acquired, to_review). not_started/in_progress sont de simples marqueurs de progression pendant l'enseignement. acquired/to_review sont des jugements d'evaluation : ils exigent qu'une question ait ete posee a l'ecrit via ask_written_exercise pour ce concept au prealable, sinon l'appel echoue.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: {
|
||||
type: 'string',
|
||||
description: 'Sujet d’apprentissage en cours (ex: "trigonometrie")'
|
||||
},
|
||||
concept: { type: 'string', description: 'Nom du concept precis' },
|
||||
status: {
|
||||
type: 'string',
|
||||
enum: VALID_STATUSES,
|
||||
description: 'Etat de maitrise du concept'
|
||||
}
|
||||
},
|
||||
required: ['subject', 'concept', 'status']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const concept = asString(args.concept).trim()
|
||||
const status = asString(args.status) as ConceptStatus
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!concept) throw new Error('concept manquant')
|
||||
if (!VALID_STATUSES.includes(status)) throw new Error('status invalide')
|
||||
|
||||
if (EVALUATED_STATUSES.includes(status) && !hasAssessment(subject, concept)) {
|
||||
throw new Error(
|
||||
`Aucune evaluation ecrite enregistree pour "${concept}" (${subject}) : appelle ask_written_exercise avant de juger ce statut.`
|
||||
)
|
||||
}
|
||||
|
||||
upsertConceptStatus(subject, concept, status)
|
||||
return `Concept "${concept}" (${subject}) marque comme "${status}".`
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import {
|
||||
setModuleTheory,
|
||||
validateModuleContent,
|
||||
canWriteModuleContent,
|
||||
REQUIRED_CONTENT_SECTIONS
|
||||
} from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
// Releve de 8000 a 20000 : la structure imposee par docs/Max_Regles_Strictes_Module_Coach.md
|
||||
// (6 sections, ~800 mots minimum, 6 exercices detailles + un exercice de debogage) depasse
|
||||
// largement l'ancienne limite pensee pour une structure plus sommaire a 5 sections.
|
||||
const CONTENT_MAX_LEN = 20000
|
||||
|
||||
export const writeModuleContent: SkillDefinition = {
|
||||
name: 'write_module_content',
|
||||
description: `Redige ou met a jour le contenu COMPLET d'un module existant : c'est ce que l'utilisateur va lire lui-meme pour apprendre (Max n'enseigne plus a l'oral). A appeler pour CHAQUE module juste apres generate_course_plan, avant la moindre question d'evaluation, puis a nouveau a tout moment pour l'enrichir si une question de l'utilisateur revele un trou. Structure OBLIGATOIRE, dans cet ordre, chaque section introduite par son titre en clair : ${REQUIRED_CONTENT_SECTIONS.join(', ')}. Avant d'ecrire, VERIFIE deux fois chaque calcul/definition/analogie (une erreur factuelle invalide le module). Refuse techniquement si une section manque, est hors ordre, trop courte, ou si un module ANTERIEUR n'est pas encore acquis (interdiction de rediger un module plus loin avant que le precedent soit valide, une fois le parcours commence).`,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
module: { type: 'string', description: 'Nom du module' },
|
||||
content: {
|
||||
type: 'string',
|
||||
description:
|
||||
"Contenu complet et structure du module (voir description de l'outil pour les 6 sections obligatoires et leurs exigences : longueurs minimales, phase guidee avec etapes numerotees, 6 exercices numerotes repartis sur 3 niveaux de difficulte, exercice de debogage)."
|
||||
}
|
||||
},
|
||||
required: ['subject', 'module', 'content']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const module = asString(args.module).trim()
|
||||
const content = asString(args.content).trim().slice(0, CONTENT_MAX_LEN)
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!module) throw new Error('module manquant')
|
||||
if (!content) throw new Error('content manquant')
|
||||
|
||||
const { ok, blockedBy } = canWriteModuleContent(subject, module)
|
||||
if (!ok) {
|
||||
throw new Error(
|
||||
`Le module "${blockedBy}" n'est pas encore acquis : interdit de rediger/modifier le contenu de "${module}" avant de l'avoir valide (complete_module). Concentre-toi sur "${blockedBy}".`
|
||||
)
|
||||
}
|
||||
|
||||
const violations = validateModuleContent(content)
|
||||
if (violations.length > 0) {
|
||||
throw new Error(
|
||||
`Contenu invalide, corrige avant d'enregistrer :\n- ${violations.join('\n- ')}`
|
||||
)
|
||||
}
|
||||
|
||||
const updated = setModuleTheory(subject, module, content)
|
||||
if (!updated) throw new Error(`Module "${module}" introuvable pour "${subject}"`)
|
||||
|
||||
return `Contenu du module "${module}" enregistre (${content.length} caracteres, structure conforme).`
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,16 @@
|
||||
import type { SkillDefinition } from './types'
|
||||
import { windowsSkills } from './windows'
|
||||
import { macSkills } from './mac'
|
||||
import { visionSkills } from './vision'
|
||||
import { memorySkills } from './memory'
|
||||
import { webSkills } from './web'
|
||||
import { browserSkills } from './browser'
|
||||
import { meetingSkills } from './meeting'
|
||||
import { coachSkills } from './coach'
|
||||
|
||||
export type { SkillDefinition } from './types'
|
||||
|
||||
export function loadSkills(): SkillDefinition[] {
|
||||
const platformSkills = process.platform === 'darwin' ? macSkills : windowsSkills
|
||||
return [
|
||||
...platformSkills,
|
||||
...visionSkills,
|
||||
...memorySkills,
|
||||
...webSkills,
|
||||
...browserSkills,
|
||||
...meetingSkills,
|
||||
...coachSkills
|
||||
]
|
||||
return [...platformSkills, ...memorySkills, ...webSkills, ...browserSkills, ...meetingSkills]
|
||||
}
|
||||
|
||||
export function findSkill(name: string): SkillDefinition | undefined {
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import { desktopCapturer, screen } from 'electron'
|
||||
import { analyzeImage } from '../../ai/vision'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const analyzeScreen: SkillDefinition = {
|
||||
name: 'analyze_screen',
|
||||
description:
|
||||
"Regarde ce qui s'affiche actuellement a l'ecran et repond a une question dessus (expliquer une erreur affichee, commenter un jeu ou une image, lire du texte affiche, decrire une interface...).",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
question: {
|
||||
type: 'string',
|
||||
description: "Ce que l'utilisateur veut savoir sur ce qui s'affiche"
|
||||
}
|
||||
},
|
||||
required: ['question']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const question = asString(args.question, "Decris ce que tu vois a l'ecran.")
|
||||
|
||||
const display = screen.getPrimaryDisplay()
|
||||
const sources = await desktopCapturer.getSources({
|
||||
types: ['screen'],
|
||||
thumbnailSize: display.size
|
||||
})
|
||||
const source = sources[0]
|
||||
if (!source) throw new Error('Aucun ecran detecte')
|
||||
|
||||
const base64 = source.thumbnail.toPNG().toString('base64')
|
||||
return await analyzeImage(`data:image/png;base64,${base64}`, question)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { analyzeScreen } from './analyzeScreen'
|
||||
import { watchCamera } from './watchCamera'
|
||||
|
||||
// Competences communes a toutes les plateformes (Electron fournit desktopCapturer et
|
||||
// getUserMedia de maniere identique sur Windows/Mac).
|
||||
export const visionSkills: SkillDefinition[] = [analyzeScreen, watchCamera]
|
||||
@@ -1,25 +0,0 @@
|
||||
import { requestCameraFrame } from '../../windowBridge'
|
||||
import { analyzeImage } from '../../ai/vision'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const watchCamera: SkillDefinition = {
|
||||
name: 'watch_camera',
|
||||
description:
|
||||
"Prend une photo instantanee via la webcam de l'utilisateur et repond a une question sur ce qu'elle montre (ex: 'que vois-tu ?', 'comment je suis habille ?', 'montre-moi cet objet'). Ne filme pas en continu, une seule photo a chaque appel.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
question: {
|
||||
type: 'string',
|
||||
description: "Ce que l'utilisateur veut savoir sur ce que montre la camera"
|
||||
}
|
||||
},
|
||||
required: ['question']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const question = asString(args.question, 'Decris ce que tu vois.')
|
||||
const dataUrl = await requestCameraFrame()
|
||||
return await analyzeImage(dataUrl, question)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { randomUUID } from 'crypto'
|
||||
import { ipcMain, type BrowserWindow, type IpcMainEvent } from 'electron'
|
||||
import type { BrowserWindow } from 'electron'
|
||||
|
||||
let mainWindow: BrowserWindow | null = null
|
||||
|
||||
@@ -10,35 +9,3 @@ export function setMainWindow(window: BrowserWindow): void {
|
||||
export function sendToRenderer(channel: string, ...args: unknown[]): void {
|
||||
mainWindow?.webContents.send(channel, ...args)
|
||||
}
|
||||
|
||||
/**
|
||||
* Demande au renderer de capturer une image (ex: webcam) et attend sa reponse.
|
||||
* Le renderer doit ecouter 'capture-camera-frame' et repondre via ipcRenderer.send sur
|
||||
* 'camera-frame-result' avec le meme requestId et soit une data URL, soit null en cas d'echec.
|
||||
*/
|
||||
export function requestCameraFrame(timeoutMs = 10000): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!mainWindow) {
|
||||
reject(new Error('Fenetre indisponible'))
|
||||
return
|
||||
}
|
||||
|
||||
const requestId = randomUUID()
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
ipcMain.removeListener('camera-frame-result', handler)
|
||||
reject(new Error('Timeout en attendant la camera'))
|
||||
}, timeoutMs)
|
||||
|
||||
function handler(_event: IpcMainEvent, id: string, dataUrl: string | null): void {
|
||||
if (id !== requestId) return
|
||||
clearTimeout(timeout)
|
||||
ipcMain.removeListener('camera-frame-result', handler)
|
||||
if (dataUrl) resolve(dataUrl)
|
||||
else reject(new Error("Impossible d'acceder a la camera"))
|
||||
}
|
||||
|
||||
ipcMain.on('camera-frame-result', handler)
|
||||
sendToRenderer('capture-camera-frame', requestId)
|
||||
})
|
||||
}
|
||||
|
||||
Vendored
-36
@@ -1,15 +1,6 @@
|
||||
import { ElectronAPI } from '@electron-toolkit/preload'
|
||||
import type { VoiceTurnResult } from '../shared/voice'
|
||||
import type { AuthStatus, LoginResult } from '../shared/auth'
|
||||
import type {
|
||||
SubjectProgress,
|
||||
ExerciseForm,
|
||||
ExerciseFormAnswer,
|
||||
ModuleDetail,
|
||||
CourseComplianceReport
|
||||
} from '../shared/coach'
|
||||
import type { DrawShape } from '../shared/drawing'
|
||||
import type { CourseBuildState } from '../shared/courseBuild'
|
||||
|
||||
export interface ForgeAvatarApi {
|
||||
setIgnoreMouseEvents: (ignore: boolean, options?: { forward: boolean }) => void
|
||||
@@ -21,36 +12,9 @@ export interface ForgeAvatarApi {
|
||||
onToggleMeetingTranscription: (callback: (transcribing: boolean) => void) => () => void
|
||||
sendMeetingAudioChunk: (audio: ArrayBuffer, mimeType: string) => void
|
||||
sendMeetingRecordingStopped: () => void
|
||||
getCoachProgress: () => Promise<SubjectProgress[]>
|
||||
getModuleDetail: (subject: string, moduleName: string) => Promise<ModuleDetail | null>
|
||||
requestModuleEvaluation: (subject: string, moduleName: string) => void
|
||||
onNavigateToModule: (
|
||||
callback: (target: { subject: string; module: string }) => void
|
||||
) => () => void
|
||||
onCourseBuildStep: (callback: (state: CourseBuildState | null) => void) => () => void
|
||||
getCourseCompliance: (subject: string) => Promise<CourseComplianceReport | null>
|
||||
onAskWrittenForm: (callback: (form: ExerciseForm) => void) => () => void
|
||||
submitWrittenForm: (requestId: string, answers: ExerciseFormAnswer[]) => void
|
||||
onInitDrawing: (
|
||||
callback: (init: { title: string; width: number; height: number }) => void
|
||||
) => () => void
|
||||
onRevealShape: (
|
||||
callback: (payload: { requestId: string; shape: DrawShape; audio: ArrayBuffer | null }) => void
|
||||
) => () => void
|
||||
acknowledgeShapeReveal: (requestId: string) => void
|
||||
onRenderMermaid: (
|
||||
callback: (payload: { requestId: string; title: string; mermaidCode: string }) => void
|
||||
) => () => void
|
||||
acknowledgeMermaidRendered: (requestId: string, ok: boolean, error?: string) => void
|
||||
onPlayCaption: (
|
||||
callback: (payload: { requestId: string; audio: ArrayBuffer }) => void
|
||||
) => () => void
|
||||
acknowledgeCaptionDone: (requestId: string) => void
|
||||
onProactiveSpeech: (callback: (audio: ArrayBuffer) => void) => () => void
|
||||
getPathForFile: (file: File) => string
|
||||
sendDroppedFiles: (paths: string[]) => void
|
||||
onCaptureCameraFrame: (callback: (requestId: string) => void) => () => void
|
||||
sendCameraFrameResult: (requestId: string, dataUrl: string | null) => void
|
||||
onUpdateAvailable: (callback: () => void) => () => void
|
||||
onUpdateReady: (callback: () => void) => () => void
|
||||
login: (email: string, password: string) => Promise<LoginResult>
|
||||
|
||||
@@ -2,15 +2,6 @@ import { contextBridge, ipcRenderer, webUtils } from 'electron'
|
||||
import { electronAPI } from '@electron-toolkit/preload'
|
||||
import type { VoiceTurnResult } from '../shared/voice'
|
||||
import type { AuthStatus, LoginResult } from '../shared/auth'
|
||||
import type {
|
||||
SubjectProgress,
|
||||
ExerciseForm,
|
||||
ExerciseFormAnswer,
|
||||
ModuleDetail,
|
||||
CourseComplianceReport
|
||||
} from '../shared/coach'
|
||||
import type { DrawShape } from '../shared/drawing'
|
||||
import type { CourseBuildState } from '../shared/courseBuild'
|
||||
|
||||
const api = {
|
||||
setIgnoreMouseEvents: (ignore: boolean, options?: { forward: boolean }): void => {
|
||||
@@ -44,87 +35,6 @@ const api = {
|
||||
sendMeetingRecordingStopped: (): void => {
|
||||
ipcRenderer.send('meeting-recording-stopped')
|
||||
},
|
||||
getCoachProgress: (): Promise<SubjectProgress[]> => ipcRenderer.invoke('get-coach-progress'),
|
||||
getModuleDetail: (subject: string, moduleName: string): Promise<ModuleDetail | null> =>
|
||||
ipcRenderer.invoke('get-module-detail', subject, moduleName),
|
||||
getCourseCompliance: (subject: string): Promise<CourseComplianceReport | null> =>
|
||||
ipcRenderer.invoke('get-course-compliance', subject),
|
||||
requestModuleEvaluation: (subject: string, moduleName: string): void => {
|
||||
ipcRenderer.send('evaluate-module', subject, moduleName)
|
||||
},
|
||||
onNavigateToModule: (
|
||||
callback: (target: { subject: string; module: string }) => void
|
||||
): (() => void) => {
|
||||
const handler = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
target: { subject: string; module: string }
|
||||
): void => callback(target)
|
||||
ipcRenderer.on('navigate-to-module', handler)
|
||||
return () => ipcRenderer.removeListener('navigate-to-module', handler)
|
||||
},
|
||||
onCourseBuildStep: (callback: (state: CourseBuildState | null) => void): (() => void) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, state: CourseBuildState | null): void =>
|
||||
callback(state)
|
||||
ipcRenderer.on('course-build-step', handler)
|
||||
return () => ipcRenderer.removeListener('course-build-step', handler)
|
||||
},
|
||||
onAskWrittenForm: (callback: (form: ExerciseForm) => void): (() => void) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, form: ExerciseForm): void => callback(form)
|
||||
ipcRenderer.on('ask-written-form', handler)
|
||||
return () => ipcRenderer.removeListener('ask-written-form', handler)
|
||||
},
|
||||
submitWrittenForm: (requestId: string, answers: ExerciseFormAnswer[]): void => {
|
||||
ipcRenderer.send('written-form-result', requestId, answers)
|
||||
},
|
||||
onInitDrawing: (
|
||||
callback: (init: { title: string; width: number; height: number }) => void
|
||||
): (() => void) => {
|
||||
const handler = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
init: { title: string; width: number; height: number }
|
||||
): void => callback(init)
|
||||
ipcRenderer.on('init-drawing', handler)
|
||||
return () => ipcRenderer.removeListener('init-drawing', handler)
|
||||
},
|
||||
onRevealShape: (
|
||||
callback: (payload: { requestId: string; shape: DrawShape; audio: ArrayBuffer | null }) => void
|
||||
): (() => void) => {
|
||||
const handler = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
payload: { requestId: string; shape: DrawShape; audio: ArrayBuffer | null }
|
||||
): void => callback(payload)
|
||||
ipcRenderer.on('reveal-shape', handler)
|
||||
return () => ipcRenderer.removeListener('reveal-shape', handler)
|
||||
},
|
||||
acknowledgeShapeReveal: (requestId: string): void => {
|
||||
ipcRenderer.send('shape-reveal-done', requestId)
|
||||
},
|
||||
onRenderMermaid: (
|
||||
callback: (payload: { requestId: string; title: string; mermaidCode: string }) => void
|
||||
): (() => void) => {
|
||||
const handler = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
payload: { requestId: string; title: string; mermaidCode: string }
|
||||
): void => callback(payload)
|
||||
ipcRenderer.on('render-mermaid', handler)
|
||||
return () => ipcRenderer.removeListener('render-mermaid', handler)
|
||||
},
|
||||
acknowledgeMermaidRendered: (requestId: string, ok: boolean, error?: string): void => {
|
||||
ipcRenderer.send('mermaid-render-done', requestId, ok, error)
|
||||
},
|
||||
onPlayCaption: (
|
||||
callback: (payload: { requestId: string; audio: ArrayBuffer }) => void
|
||||
): (() => void) => {
|
||||
const handler = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
payload: { requestId: string; audio: ArrayBuffer }
|
||||
): void => callback(payload)
|
||||
ipcRenderer.on('play-caption', handler)
|
||||
return () => ipcRenderer.removeListener('play-caption', handler)
|
||||
},
|
||||
acknowledgeCaptionDone: (requestId: string): void => {
|
||||
ipcRenderer.send('caption-done', requestId)
|
||||
},
|
||||
onProactiveSpeech: (callback: (audio: ArrayBuffer) => void): (() => void) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, audio: ArrayBuffer): void => callback(audio)
|
||||
ipcRenderer.on('proactive-speech', handler)
|
||||
@@ -134,15 +44,6 @@ const api = {
|
||||
sendDroppedFiles: (paths: string[]): void => {
|
||||
ipcRenderer.send('dropped-files', paths)
|
||||
},
|
||||
onCaptureCameraFrame: (callback: (requestId: string) => void): (() => void) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, requestId: string): void =>
|
||||
callback(requestId)
|
||||
ipcRenderer.on('capture-camera-frame', handler)
|
||||
return () => ipcRenderer.removeListener('capture-camera-frame', handler)
|
||||
},
|
||||
sendCameraFrameResult: (requestId: string, dataUrl: string | null): void => {
|
||||
ipcRenderer.send('camera-frame-result', requestId, dataUrl)
|
||||
},
|
||||
onUpdateAvailable: (callback: () => void): (() => void) => {
|
||||
const handler = (): void => callback()
|
||||
ipcRenderer.on('update:available', handler)
|
||||
|
||||
@@ -3,11 +3,8 @@ import AvatarViewer, { type AvatarHandle } from './components/AvatarViewer'
|
||||
import ThinkingIndicator from './components/ThinkingIndicator'
|
||||
import VoiceErrorBanner from './components/VoiceErrorBanner'
|
||||
import UpdateBanner from './components/UpdateBanner'
|
||||
import CourseBuildStepper from './components/CourseBuildStepper'
|
||||
import type { CourseBuildState } from '../../shared/courseBuild'
|
||||
import { useVoiceAssistant, type VoiceState } from './voice/useVoiceAssistant'
|
||||
import { useProactiveSpeech } from './voice/useProactiveSpeech'
|
||||
import { useCameraCapture } from './voice/useCameraCapture'
|
||||
import { useMeetingRecorder } from './voice/useMeetingRecorder'
|
||||
|
||||
function App(): React.JSX.Element {
|
||||
@@ -20,8 +17,6 @@ function App(): React.JSX.Element {
|
||||
const transcribingRef = useRef(transcribing)
|
||||
const [voiceState, setVoiceState] = useState<VoiceState>('idle')
|
||||
const [voiceError, setVoiceError] = useState<string | null>(null)
|
||||
const [courseBuild, setCourseBuild] = useState<CourseBuildState | null>(null)
|
||||
useEffect(() => window.api.onCourseBuildStep(setCourseBuild), [])
|
||||
const [updateStatus, setUpdateStatus] = useState<'available' | 'ready' | null>(null)
|
||||
useEffect(() => window.api.onUpdateAvailable(() => setUpdateStatus('available')), [])
|
||||
useEffect(() => window.api.onUpdateReady(() => setUpdateStatus('ready')), [])
|
||||
@@ -37,7 +32,6 @@ function App(): React.JSX.Element {
|
||||
}, [])
|
||||
useVoiceAssistant(avatar, listening, handleVoiceStateChange, handleVoiceError)
|
||||
useProactiveSpeech(avatar)
|
||||
useCameraCapture()
|
||||
useMeetingRecorder()
|
||||
|
||||
useEffect(() => {
|
||||
@@ -145,7 +139,6 @@ function App(): React.JSX.Element {
|
||||
<AvatarViewer onReady={handleReady} />
|
||||
{voiceState === 'processing' && <ThinkingIndicator />}
|
||||
{voiceError && voiceState !== 'processing' && <VoiceErrorBanner message={voiceError} />}
|
||||
{courseBuild && <CourseBuildStepper state={courseBuild} />}
|
||||
{updateStatus && <UpdateBanner status={updateStatus} />}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import rough from 'roughjs'
|
||||
import mermaid from 'mermaid'
|
||||
import type { RoughCanvas } from 'roughjs/bin/canvas'
|
||||
import { drawShape, type LabelBox } from './drawRoughShapes'
|
||||
|
||||
let mermaidInitialized = false
|
||||
function ensureMermaidInitialized(): void {
|
||||
if (mermaidInitialized) return
|
||||
mermaidInitialized = true
|
||||
// 'sandbox' (rendu dans un iframe isole) a ete teste mais reste blanc sous Electron/file:// —
|
||||
// erreurs d'origine liees au sandboxing d'iframe. 'strict' (defaut documente de Mermaid) sanitise
|
||||
// deja les labels et interdit le HTML brut : suffisant ici puisqu'on ne passe jamais de HTML/SVG
|
||||
// arbitraire a la main, seulement la syntaxe Mermaid validee par son propre parseur.
|
||||
mermaid.initialize({ startOnLoad: false, securityLevel: 'strict' })
|
||||
}
|
||||
|
||||
/** Joue un audio et accuse reception (via le callback donne) a la fin, meme en cas d'erreur. */
|
||||
function playAudioAndAck(audio: ArrayBuffer, onDone: () => void): void {
|
||||
const url = URL.createObjectURL(new Blob([audio], { type: 'audio/mpeg' }))
|
||||
const audioEl = new Audio(url)
|
||||
const done = (): void => {
|
||||
URL.revokeObjectURL(url)
|
||||
onDone()
|
||||
}
|
||||
audioEl.onended = done
|
||||
audioEl.onerror = done
|
||||
audioEl.play().catch(done)
|
||||
}
|
||||
|
||||
export default function CoachDrawingView(): React.JSX.Element {
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null)
|
||||
const roughRef = useRef<RoughCanvas | null>(null)
|
||||
const placedLabelsRef = useRef<LabelBox[]>([])
|
||||
const mermaidContainerRef = useRef<HTMLDivElement | null>(null)
|
||||
const processedMermaidRequestRef = useRef<string | null>(null)
|
||||
const [title, setTitle] = useState<string | null>(null)
|
||||
const [size, setSize] = useState({ width: 700, height: 500 })
|
||||
const [mode, setMode] = useState<'drawing' | 'mermaid'>('drawing')
|
||||
const [pendingMermaid, setPendingMermaid] = useState<{
|
||||
requestId: string
|
||||
mermaidCode: string
|
||||
} | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
return window.api.onInitDrawing((init) => {
|
||||
setMode('drawing')
|
||||
setTitle(init.title)
|
||||
setSize({ width: init.width, height: init.height })
|
||||
placedLabelsRef.current = []
|
||||
roughRef.current = null
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
return window.api.onRevealShape(({ requestId, shape, audio }) => {
|
||||
const canvas = canvasRef.current
|
||||
const ctx = canvas?.getContext('2d')
|
||||
if (canvas && ctx) {
|
||||
if (!roughRef.current) roughRef.current = rough.canvas(canvas)
|
||||
drawShape(roughRef.current, ctx, shape, placedLabelsRef.current)
|
||||
}
|
||||
|
||||
if (!audio) {
|
||||
window.api.acknowledgeShapeReveal(requestId)
|
||||
return
|
||||
}
|
||||
playAudioAndAck(audio, () => window.api.acknowledgeShapeReveal(requestId))
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
return window.api.onRenderMermaid(({ requestId, title: diagramTitle, mermaidCode }) => {
|
||||
ensureMermaidInitialized()
|
||||
setMode('mermaid')
|
||||
setTitle(diagramTitle)
|
||||
// Le conteneur du diagramme n'existe que lorsque mode==='mermaid' : au premier rendu, ce mode
|
||||
// vient d'etre demande ci-dessus mais React n'a pas encore commite le changement, donc la ref
|
||||
// est encore celle du canvas (ou null). Le rendu reel est reporte dans l'effet ci-dessous,
|
||||
// declenche une fois le conteneur effectivement monte (constate en test reel : le tout premier
|
||||
// diagramme Mermaid d'une session echouait toujours avec "Conteneur indisponible").
|
||||
setPendingMermaid({ requestId, mermaidCode })
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingMermaid || processedMermaidRequestRef.current === pendingMermaid.requestId) return
|
||||
processedMermaidRequestRef.current = pendingMermaid.requestId
|
||||
const { requestId, mermaidCode } = pendingMermaid
|
||||
const container = mermaidContainerRef.current
|
||||
if (!container) {
|
||||
window.api.acknowledgeMermaidRendered(requestId, false, 'Conteneur indisponible')
|
||||
return
|
||||
}
|
||||
mermaid
|
||||
.render(`mermaid-${requestId}`, mermaidCode)
|
||||
.then(({ svg }) => {
|
||||
container.innerHTML = svg
|
||||
const svgEl = container.querySelector('svg')
|
||||
if (svgEl) {
|
||||
svgEl.style.maxWidth = '100%'
|
||||
svgEl.style.height = 'auto'
|
||||
}
|
||||
window.api.acknowledgeMermaidRendered(requestId, true)
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
window.api.acknowledgeMermaidRendered(requestId, false, message)
|
||||
})
|
||||
}, [pendingMermaid])
|
||||
|
||||
useEffect(() => {
|
||||
return window.api.onPlayCaption(({ requestId, audio }) => {
|
||||
playAudioAndAck(audio, () => window.api.acknowledgeCaptionDone(requestId))
|
||||
})
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
background: '#f5f3ee',
|
||||
minHeight: '100vh',
|
||||
padding: 20,
|
||||
fontFamily: 'sans-serif',
|
||||
boxSizing: 'border-box'
|
||||
}}
|
||||
>
|
||||
<h1 style={{ fontSize: 16, marginBottom: 12, color: '#333' }}>
|
||||
{title ?? 'En attente d’un dessin de Max...'}
|
||||
</h1>
|
||||
{mode === 'drawing' ? (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={size.width}
|
||||
height={size.height}
|
||||
style={{ background: '#fff', border: '1px solid #ddd', borderRadius: 4 }}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
ref={mermaidContainerRef}
|
||||
style={{
|
||||
background: '#fff',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: 4,
|
||||
padding: 16,
|
||||
minHeight: 400
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { DONT_KNOW_ANSWER } from '../../../shared/coach'
|
||||
import type { ExerciseForm } from '../../../shared/coach'
|
||||
|
||||
export default function CoachExerciseView(): React.JSX.Element {
|
||||
const [form, setForm] = useState<ExerciseForm | null>(null)
|
||||
const [answers, setAnswers] = useState<Record<string, string>>({})
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
return window.api.onAskWrittenForm((incoming) => {
|
||||
setForm(incoming)
|
||||
setAnswers({})
|
||||
setSubmitted(false)
|
||||
})
|
||||
}, [])
|
||||
|
||||
const setAnswer = (id: string, answer: string): void => {
|
||||
setAnswers((prev) => ({ ...prev, [id]: answer }))
|
||||
}
|
||||
|
||||
const allAnswered = form ? form.items.every((item) => !!answers[item.id]?.trim()) : false
|
||||
|
||||
const submitAll = (): void => {
|
||||
if (!form) return
|
||||
window.api.submitWrittenForm(
|
||||
form.requestId,
|
||||
form.items.map((item) => ({ id: item.id, answer: answers[item.id] ?? DONT_KNOW_ANSWER }))
|
||||
)
|
||||
setSubmitted(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
background: '#1e1e1e',
|
||||
color: '#eee',
|
||||
minHeight: '100vh',
|
||||
padding: 24,
|
||||
fontFamily: 'sans-serif',
|
||||
boxSizing: 'border-box'
|
||||
}}
|
||||
>
|
||||
<h1 style={{ fontSize: 18, marginBottom: 20 }}>Exercice</h1>
|
||||
|
||||
{!form && <p style={{ color: '#aaa' }}>En attente de questions de Max...</p>}
|
||||
|
||||
{form && submitted && (
|
||||
<p style={{ color: '#8bc34a' }}>
|
||||
Reponses envoyees a Max. Cette fenetre se ferme automatiquement...
|
||||
</p>
|
||||
)}
|
||||
|
||||
{form && !submitted && (
|
||||
<div>
|
||||
{form.items.map((item, index) => (
|
||||
<div
|
||||
key={item.id}
|
||||
style={{
|
||||
marginBottom: 24,
|
||||
paddingBottom: 20,
|
||||
borderBottom: '1px solid #333'
|
||||
}}
|
||||
>
|
||||
<p style={{ marginBottom: 12, fontSize: 15, lineHeight: 1.5 }}>
|
||||
{index + 1}. {item.question}
|
||||
</p>
|
||||
|
||||
{item.type === 'free_text' && (
|
||||
<textarea
|
||||
value={answers[item.id] === DONT_KNOW_ANSWER ? '' : (answers[item.id] ?? '')}
|
||||
onChange={(e) => setAnswer(item.id, e.target.value)}
|
||||
rows={4}
|
||||
style={{
|
||||
width: '100%',
|
||||
boxSizing: 'border-box',
|
||||
fontFamily: 'ui-monospace, monospace',
|
||||
fontSize: 13,
|
||||
background: '#111',
|
||||
color: '#eee',
|
||||
border: '1px solid #444',
|
||||
borderRadius: 4,
|
||||
padding: 10,
|
||||
resize: 'vertical'
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{item.type === 'multiple_choice' && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{(item.options ?? []).map((option) => (
|
||||
<button
|
||||
key={option}
|
||||
onClick={() => setAnswer(item.id, option)}
|
||||
style={{
|
||||
textAlign: 'left',
|
||||
padding: '10px 14px',
|
||||
background: answers[item.id] === option ? '#3f6fd1' : undefined,
|
||||
color: answers[item.id] === option ? '#fff' : undefined
|
||||
}}
|
||||
>
|
||||
{option}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.type === 'true_false' && (
|
||||
<div style={{ display: 'flex', gap: 12 }}>
|
||||
<button
|
||||
onClick={() => setAnswer(item.id, 'Vrai')}
|
||||
style={{
|
||||
padding: '10px 24px',
|
||||
background: answers[item.id] === 'Vrai' ? '#3f6fd1' : undefined,
|
||||
color: answers[item.id] === 'Vrai' ? '#fff' : undefined
|
||||
}}
|
||||
>
|
||||
Vrai
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setAnswer(item.id, 'Faux')}
|
||||
style={{
|
||||
padding: '10px 24px',
|
||||
background: answers[item.id] === 'Faux' ? '#3f6fd1' : undefined,
|
||||
color: answers[item.id] === 'Faux' ? '#fff' : undefined
|
||||
}}
|
||||
>
|
||||
Faux
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => setAnswer(item.id, DONT_KNOW_ANSWER)}
|
||||
style={{
|
||||
marginTop: 10,
|
||||
padding: '6px 14px',
|
||||
fontSize: 13,
|
||||
color: answers[item.id] === DONT_KNOW_ANSWER ? '#fff' : '#aaa',
|
||||
background: answers[item.id] === DONT_KNOW_ANSWER ? '#555' : 'transparent',
|
||||
border: '1px solid #555'
|
||||
}}
|
||||
>
|
||||
Je ne sais pas
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<p style={{ color: '#777', fontSize: 12, marginBottom: 16 }}>
|
||||
Pas de souci si tu ne sais pas certaines reponses : c'est juste une base pour
|
||||
savoir quoi t'enseigner, pas une note.
|
||||
</p>
|
||||
|
||||
<button
|
||||
onClick={submitAll}
|
||||
disabled={!allAnswered}
|
||||
style={{
|
||||
padding: '10px 24px',
|
||||
fontSize: 14,
|
||||
background: allAnswered ? '#3f6fd1' : '#444',
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
borderRadius: 4,
|
||||
cursor: allAnswered ? 'pointer' : 'not-allowed'
|
||||
}}
|
||||
>
|
||||
Soumettre tout le formulaire
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,421 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import rough from 'roughjs'
|
||||
import mermaid from 'mermaid'
|
||||
import type {
|
||||
SubjectProgress,
|
||||
ConceptStatus,
|
||||
ModuleDetail,
|
||||
ModuleDiagram,
|
||||
CourseComplianceReport
|
||||
} from '../../../shared/coach'
|
||||
import type { Drawing } from '../../../shared/drawing'
|
||||
import { drawShape, type LabelBox } from './drawRoughShapes'
|
||||
|
||||
let mermaidInitialized = false
|
||||
function ensureMermaidInitialized(): void {
|
||||
if (mermaidInitialized) return
|
||||
mermaidInitialized = true
|
||||
mermaid.initialize({ startOnLoad: false, securityLevel: 'strict' })
|
||||
}
|
||||
|
||||
let mermaidRenderCounter = 0
|
||||
|
||||
function ShapesDiagram({ drawing }: { drawing: Drawing }): React.JSX.Element {
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current
|
||||
const ctx = canvas?.getContext('2d')
|
||||
if (!canvas || !ctx) return
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height)
|
||||
const rc = rough.canvas(canvas)
|
||||
const placedLabels: LabelBox[] = []
|
||||
for (const shape of drawing.shapes) drawShape(rc, ctx, shape, placedLabels)
|
||||
}, [drawing])
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={drawing.width}
|
||||
height={drawing.height}
|
||||
style={{ background: '#fff', border: '1px solid #444', borderRadius: 4, maxWidth: '100%' }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MermaidDiagram({ mermaidCode }: { mermaidCode: string }): React.JSX.Element {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
ensureMermaidInitialized()
|
||||
const container = containerRef.current
|
||||
if (!container) return
|
||||
mermaidRenderCounter += 1
|
||||
mermaid
|
||||
.render(`mermaid-review-${mermaidRenderCounter}`, mermaidCode)
|
||||
.then(({ svg }) => {
|
||||
container.innerHTML = svg
|
||||
const svgEl = container.querySelector('svg')
|
||||
if (svgEl) {
|
||||
svgEl.style.maxWidth = '100%'
|
||||
svgEl.style.height = 'auto'
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
container.textContent =
|
||||
error instanceof Error ? error.message : 'Erreur de rendu du diagramme'
|
||||
})
|
||||
}, [mermaidCode])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
style={{ background: '#fff', border: '1px solid #444', borderRadius: 4, padding: 12 }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ModuleDiagramView({ diagram }: { diagram: ModuleDiagram }): React.JSX.Element | null {
|
||||
if (diagram.kind === 'shapes') {
|
||||
return <ShapesDiagram drawing={diagram.data as Drawing} />
|
||||
}
|
||||
if (diagram.kind === 'mermaid') {
|
||||
const { mermaidCode } = diagram.data as { mermaidCode: string }
|
||||
return <MermaidDiagram mermaidCode={mermaidCode} />
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const STATUS_COLOR: Record<ConceptStatus, string> = {
|
||||
acquired: '#4caf50',
|
||||
in_progress: '#ff9800',
|
||||
to_review: '#f44336',
|
||||
not_started: '#9e9e9e'
|
||||
}
|
||||
|
||||
const STATUS_LABEL: Record<ConceptStatus, string> = {
|
||||
acquired: 'Acquis',
|
||||
in_progress: 'En cours',
|
||||
to_review: 'A reviser',
|
||||
not_started: 'Non aborde'
|
||||
}
|
||||
|
||||
const SUBJECT_STATUS_LABEL: Record<string, string> = {
|
||||
researching: 'Recherche en cours',
|
||||
assessing: 'Evaluation initiale',
|
||||
in_progress: 'En cours',
|
||||
mastered: 'Maitrise'
|
||||
}
|
||||
|
||||
type View =
|
||||
| { level: 'subjects' }
|
||||
| { level: 'modules'; subject: SubjectProgress }
|
||||
| { level: 'module'; subject: SubjectProgress; moduleName: string }
|
||||
|
||||
const backButtonStyle: React.CSSProperties = {
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
color: '#8ab4f8',
|
||||
cursor: 'pointer',
|
||||
padding: 0,
|
||||
marginBottom: 16,
|
||||
fontSize: 13
|
||||
}
|
||||
|
||||
export default function CoachProgressView(): React.JSX.Element {
|
||||
const [subjects, setSubjects] = useState<SubjectProgress[] | null>(null)
|
||||
const [view, setView] = useState<View>({ level: 'subjects' })
|
||||
const [moduleDetail, setModuleDetail] = useState<ModuleDetail | null>(null)
|
||||
const [compliance, setCompliance] = useState<{
|
||||
subject: string
|
||||
report: CourseComplianceReport
|
||||
} | null>(null)
|
||||
|
||||
const reload = (): void => {
|
||||
window.api
|
||||
.getCoachProgress()
|
||||
.then(setSubjects)
|
||||
.catch((error: unknown) => console.error('Erreur chargement progression Coach:', error))
|
||||
}
|
||||
|
||||
useEffect(reload, [])
|
||||
|
||||
// Max n'enseigne plus a l'oral : il ouvre directement le module pour que l'utilisateur
|
||||
// l'apprenne par lui-meme (demande utilisateur explicite). Navigue vers ce module des reception.
|
||||
useEffect(() => {
|
||||
return window.api.onNavigateToModule(({ subject, module }) => {
|
||||
window.api
|
||||
.getCoachProgress()
|
||||
.then((all) => {
|
||||
setSubjects(all)
|
||||
const found = all.find((s) => s.subject === subject)
|
||||
if (found) setView({ level: 'module', subject: found, moduleName: module })
|
||||
})
|
||||
.catch((error: unknown) => console.error('Erreur navigation vers module:', error))
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (view.level !== 'module') return
|
||||
let cancelled = false
|
||||
window.api
|
||||
.getModuleDetail(view.subject.subject, view.moduleName)
|
||||
.then((detail) => {
|
||||
if (!cancelled) setModuleDetail(detail)
|
||||
})
|
||||
.catch((error: unknown) => console.error('Erreur chargement detail module:', error))
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [view])
|
||||
|
||||
useEffect(() => {
|
||||
if (view.level !== 'modules') return
|
||||
let cancelled = false
|
||||
const subject = view.subject.subject
|
||||
window.api
|
||||
.getCourseCompliance(subject)
|
||||
.then((report) => {
|
||||
if (!cancelled && report) setCompliance({ subject, report })
|
||||
})
|
||||
.catch((error: unknown) => console.error('Erreur chargement conformite du cours:', error))
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [view])
|
||||
|
||||
if (view.level === 'module') {
|
||||
const detail = moduleDetail?.name === view.moduleName ? moduleDetail : null
|
||||
return (
|
||||
<Shell title={view.moduleName}>
|
||||
<button
|
||||
style={backButtonStyle}
|
||||
onClick={() => setView({ level: 'modules', subject: view.subject })}
|
||||
>
|
||||
← Retour aux modules
|
||||
</button>
|
||||
{!detail && <p>Chargement...</p>}
|
||||
{detail && (
|
||||
<>
|
||||
<p style={{ color: STATUS_COLOR[detail.status], marginBottom: 16 }}>
|
||||
{STATUS_LABEL[detail.status]}
|
||||
</p>
|
||||
{!detail.locked && detail.status !== 'acquired' && (
|
||||
<button
|
||||
onClick={() =>
|
||||
window.api.requestModuleEvaluation(view.subject.subject, view.moduleName)
|
||||
}
|
||||
style={{
|
||||
marginBottom: 20,
|
||||
padding: '8px 14px',
|
||||
background: '#3f6fd1',
|
||||
border: 'none',
|
||||
borderRadius: 4,
|
||||
color: '#fff',
|
||||
cursor: 'pointer',
|
||||
fontSize: 13
|
||||
}}
|
||||
>
|
||||
Evaluer ce module
|
||||
</button>
|
||||
)}
|
||||
{detail.theorySummary && (
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<h2 style={{ fontSize: 14, color: '#aaa', marginBottom: 6 }}>Theorie</h2>
|
||||
<p style={{ lineHeight: 1.5, whiteSpace: 'pre-wrap' }}>{detail.theorySummary}</p>
|
||||
</div>
|
||||
)}
|
||||
{detail.diagrams.length > 0 && (
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<h2 style={{ fontSize: 14, color: '#aaa', marginBottom: 6 }}>Schemas</h2>
|
||||
{detail.diagrams.map((diagram, i) => (
|
||||
<div key={i} style={{ marginBottom: 14 }}>
|
||||
<p style={{ margin: '0 0 6px', fontSize: 13, color: '#ccc' }}>
|
||||
{diagram.title}
|
||||
</p>
|
||||
<ModuleDiagramView diagram={diagram} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<h2 style={{ fontSize: 14, color: '#aaa', marginBottom: 6 }}>Evaluations</h2>
|
||||
{detail.assessments.length === 0 && (
|
||||
<p style={{ color: '#777' }}>Aucune evaluation pour ce module pour l'instant.</p>
|
||||
)}
|
||||
{detail.assessments.map((a, i) => (
|
||||
<div
|
||||
key={i}
|
||||
style={{ marginBottom: 12, padding: 10, background: '#262626', borderRadius: 4 }}
|
||||
>
|
||||
<p style={{ margin: 0, fontSize: 13 }}>{a.question}</p>
|
||||
<p
|
||||
style={{
|
||||
margin: '6px 0 0',
|
||||
fontSize: 13,
|
||||
color: a.dontKnow ? '#f44336' : '#8bc34a'
|
||||
}}
|
||||
>
|
||||
{a.answer}
|
||||
</p>
|
||||
{(a.difficulty || a.exerciseStyle) && (
|
||||
<p style={{ margin: '6px 0 0', fontSize: 11, color: '#888' }}>
|
||||
{a.difficulty ?? ''}
|
||||
{a.difficulty && a.exerciseStyle ? ' — ' : ''}
|
||||
{a.exerciseStyle ?? ''}
|
||||
{a.targetsCommonError ? ` (cible : ${a.targetsCommonError})` : ''}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</Shell>
|
||||
)
|
||||
}
|
||||
|
||||
if (view.level === 'modules') {
|
||||
const subject = subjects?.find((s) => s.subject === view.subject.subject) ?? view.subject
|
||||
return (
|
||||
<Shell title={subject.subject}>
|
||||
<button style={backButtonStyle} onClick={() => setView({ level: 'subjects' })}>
|
||||
← Retour aux sujets
|
||||
</button>
|
||||
{subject.level && (
|
||||
<p style={{ color: '#aaa', marginBottom: 4 }}>Niveau : {subject.level}</p>
|
||||
)}
|
||||
<p style={{ color: '#aaa', marginBottom: 4 }}>
|
||||
Statut : {SUBJECT_STATUS_LABEL[subject.status] ?? subject.status}
|
||||
</p>
|
||||
{subject.objective && (
|
||||
<p style={{ color: '#8bc34a', marginBottom: 16, fontStyle: 'italic' }}>
|
||||
Objectif : {subject.objective}
|
||||
</p>
|
||||
)}
|
||||
{compliance && compliance.subject === subject.subject && (
|
||||
<details style={{ marginBottom: 16 }}>
|
||||
<summary style={{ cursor: 'pointer', color: '#aaa', fontSize: 13 }}>
|
||||
Conformite a la methode pedagogique (
|
||||
{compliance.report.checks.filter((c) => c.ok).length}/
|
||||
{compliance.report.checks.length})
|
||||
</summary>
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: '8px 0 0' }}>
|
||||
{compliance.report.checks.map((check) => (
|
||||
<li
|
||||
key={check.key}
|
||||
style={{ fontSize: 12, marginBottom: 4, color: check.ok ? '#8bc34a' : '#f44336' }}
|
||||
>
|
||||
{check.ok ? '✅' : '❌'} {check.label} — {check.detail}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
{subject.concepts.length === 0 && (
|
||||
<p style={{ color: '#777' }}>Aucun module cree pour l'instant.</p>
|
||||
)}
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
|
||||
{subject.concepts.map((module) => (
|
||||
<li key={module.name} style={{ marginBottom: 6 }}>
|
||||
<button
|
||||
disabled={module.locked}
|
||||
onClick={() => setView({ level: 'module', subject, moduleName: module.name })}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '8px 10px',
|
||||
background: '#262626',
|
||||
border: 'none',
|
||||
borderRadius: 4,
|
||||
color: module.locked ? '#666' : '#eee',
|
||||
cursor: module.locked ? 'not-allowed' : 'pointer'
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
width: 10,
|
||||
height: 10,
|
||||
borderRadius: '50%',
|
||||
background: STATUS_COLOR[module.status],
|
||||
flexShrink: 0
|
||||
}}
|
||||
/>
|
||||
<span style={{ flex: 1 }}>{module.name}</span>
|
||||
{module.locked && <span title="Verrouille">🔒</span>}
|
||||
{module.nextReviewAt && (
|
||||
<span style={{ color: '#666', fontSize: 11 }}>
|
||||
Revision : {new Date(module.nextReviewAt).toLocaleDateString()}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Shell>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Shell title="Courbe d'apprentissage">
|
||||
{subjects === null && <p>Chargement...</p>}
|
||||
{subjects?.length === 0 && (
|
||||
<p style={{ color: '#aaa' }}>
|
||||
Aucun sujet d'apprentissage pour l'instant. Active le mode Coach et commence un
|
||||
sujet avec Max pour voir ta progression ici.
|
||||
</p>
|
||||
)}
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
|
||||
{subjects?.map((subject) => (
|
||||
<li key={subject.subject} style={{ marginBottom: 8 }}>
|
||||
<button
|
||||
onClick={() => setView({ level: 'modules', subject })}
|
||||
style={{
|
||||
display: 'block',
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '10px 12px',
|
||||
background: '#262626',
|
||||
border: 'none',
|
||||
borderRadius: 4,
|
||||
color: '#eee',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: 15 }}>{subject.subject}</span>
|
||||
<span style={{ display: 'block', color: '#888', fontSize: 12, marginTop: 2 }}>
|
||||
{SUBJECT_STATUS_LABEL[subject.status] ?? subject.status}
|
||||
{subject.level ? ` — ${subject.level}` : ''}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Shell>
|
||||
)
|
||||
}
|
||||
|
||||
function Shell({
|
||||
title,
|
||||
children
|
||||
}: {
|
||||
title: string
|
||||
children: React.ReactNode
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
background: '#1e1e1e',
|
||||
color: '#eee',
|
||||
minHeight: '100vh',
|
||||
padding: 24,
|
||||
fontFamily: 'sans-serif',
|
||||
boxSizing: 'border-box'
|
||||
}}
|
||||
>
|
||||
<h1 style={{ fontSize: 20, marginBottom: 16 }}>{title}</h1>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import type { CourseBuildState } from '../../../shared/courseBuild'
|
||||
|
||||
const ICON: Record<string, string> = {
|
||||
pending: '○',
|
||||
active: '◐',
|
||||
done: '✓'
|
||||
}
|
||||
|
||||
const COLOR: Record<string, string> = {
|
||||
pending: '#777',
|
||||
active: '#ffb84d',
|
||||
done: '#8bc34a'
|
||||
}
|
||||
|
||||
/**
|
||||
* Affiche visuellement la construction du plan de cours (recherche, plan, redaction des modules...)
|
||||
* a la place de la narration orale de Max pour ces etapes (demande utilisateur explicite). Pilote
|
||||
* par le process principal (courseBuildStepper.ts) a partir des outils reellement executes.
|
||||
*/
|
||||
function CourseBuildStepper({ state }: { state: CourseBuildState }): React.JSX.Element {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: '4%',
|
||||
left: '50%',
|
||||
transform: 'translateX(-50%)',
|
||||
width: '88%',
|
||||
padding: '12px 16px',
|
||||
borderRadius: 10,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.78)',
|
||||
boxShadow: '0 0 0 2px rgba(255, 255, 255, 0.2)',
|
||||
pointerEvents: 'none',
|
||||
fontFamily: 'sans-serif'
|
||||
}}
|
||||
>
|
||||
<p style={{ margin: '0 0 8px', fontSize: 12, color: '#ccc' }}>
|
||||
Construction du cours : {state.subject}
|
||||
</p>
|
||||
{state.steps.map((step) => (
|
||||
<div
|
||||
key={step.key}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
marginBottom: 4,
|
||||
opacity: step.status === 'pending' ? 0.5 : 1
|
||||
}}
|
||||
>
|
||||
<span style={{ color: COLOR[step.status], fontSize: 13, width: 16 }}>
|
||||
{ICON[step.status]}
|
||||
</span>
|
||||
<span style={{ color: '#fff', fontSize: 12 }}>{step.label}</span>
|
||||
{step.detail && (
|
||||
<span style={{ color: '#aaa', fontSize: 11, marginLeft: 'auto' }}>{step.detail}</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CourseBuildStepper
|
||||
@@ -1,142 +0,0 @@
|
||||
import type { RoughCanvas } from 'roughjs/bin/canvas'
|
||||
import type { DrawShape } from '../../../shared/drawing'
|
||||
|
||||
export interface LabelBox {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export function boxesOverlap(a: LabelBox, b: LabelBox): boolean {
|
||||
return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y
|
||||
}
|
||||
|
||||
/** Decale verticalement une position de label tant qu'elle chevauche une boite deja placee. */
|
||||
export function findFreeLabelPosition(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
text: string,
|
||||
startX: number,
|
||||
startY: number,
|
||||
placed: LabelBox[]
|
||||
): LabelBox {
|
||||
const width = ctx.measureText(text).width
|
||||
const height = 16
|
||||
let y = startY
|
||||
for (let attempt = 0; attempt < 20; attempt++) {
|
||||
const candidate: LabelBox = { x: startX, y: y - height, width, height }
|
||||
if (!placed.some((box) => boxesOverlap(candidate, box))) return candidate
|
||||
y += height
|
||||
}
|
||||
return { x: startX, y: y - height, width, height }
|
||||
}
|
||||
|
||||
export function drawArrowHead(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
color: string
|
||||
): void {
|
||||
const angle = Math.atan2(y2 - y1, x2 - x1)
|
||||
const size = 12
|
||||
ctx.save()
|
||||
ctx.fillStyle = color
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(x2, y2)
|
||||
ctx.lineTo(x2 - size * Math.cos(angle - Math.PI / 6), y2 - size * Math.sin(angle - Math.PI / 6))
|
||||
ctx.lineTo(x2 - size * Math.cos(angle + Math.PI / 6), y2 - size * Math.sin(angle + Math.PI / 6))
|
||||
ctx.closePath()
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
export function drawShape(
|
||||
rc: RoughCanvas,
|
||||
ctx: CanvasRenderingContext2D,
|
||||
shape: DrawShape,
|
||||
placedLabels: LabelBox[]
|
||||
): void {
|
||||
const color = shape.color ?? '#2a2a2a'
|
||||
const options = { stroke: color, strokeWidth: 2 }
|
||||
// Point d'ancrage par defaut du label : au-dessus de la forme pour rect/circle, au milieu du
|
||||
// segment (decale) pour line/arrow — evite que plusieurs traits partant du meme sommet se
|
||||
// chevauchent au point de depart.
|
||||
let labelAnchorX = shape.x ?? 0
|
||||
let labelAnchorY = (shape.y ?? 0) - 6
|
||||
|
||||
switch (shape.type) {
|
||||
case 'rect':
|
||||
rc.rectangle(shape.x ?? 0, shape.y ?? 0, shape.width ?? 50, shape.height ?? 50, options)
|
||||
break
|
||||
case 'circle':
|
||||
rc.circle(shape.x ?? 0, shape.y ?? 0, (shape.radius ?? 25) * 2, options)
|
||||
break
|
||||
case 'line':
|
||||
rc.line(shape.x ?? 0, shape.y ?? 0, shape.x2 ?? 0, shape.y2 ?? 0, options)
|
||||
labelAnchorX = ((shape.x ?? 0) + (shape.x2 ?? 0)) / 2
|
||||
labelAnchorY = ((shape.y ?? 0) + (shape.y2 ?? 0)) / 2 - 8
|
||||
break
|
||||
case 'arrow':
|
||||
rc.line(shape.x ?? 0, shape.y ?? 0, shape.x2 ?? 0, shape.y2 ?? 0, options)
|
||||
drawArrowHead(ctx, shape.x ?? 0, shape.y ?? 0, shape.x2 ?? 0, shape.y2 ?? 0, color)
|
||||
labelAnchorX = ((shape.x ?? 0) + (shape.x2 ?? 0)) / 2
|
||||
labelAnchorY = ((shape.y ?? 0) + (shape.y2 ?? 0)) / 2 - 8
|
||||
break
|
||||
case 'stroke':
|
||||
if (shape.points && shape.points.length >= 2) {
|
||||
rc.curve(
|
||||
shape.points.map((p) => [p.x, p.y] as [number, number]),
|
||||
options
|
||||
)
|
||||
}
|
||||
break
|
||||
case 'arc': {
|
||||
const radius = shape.radius ?? 25
|
||||
const startRad = ((shape.startAngle ?? 0) * Math.PI) / 180
|
||||
const endRad = ((shape.endAngle ?? 90) * Math.PI) / 180
|
||||
rc.arc(
|
||||
shape.x ?? 0,
|
||||
shape.y ?? 0,
|
||||
radius * 2,
|
||||
radius * 2,
|
||||
startRad,
|
||||
endRad,
|
||||
shape.closed ?? false,
|
||||
options
|
||||
)
|
||||
const midAngle = ((shape.startAngle ?? 0) + (shape.endAngle ?? 90)) / 2
|
||||
const midRad = (midAngle * Math.PI) / 180
|
||||
labelAnchorX = (shape.x ?? 0) + (radius + 14) * Math.cos(midRad)
|
||||
labelAnchorY = (shape.y ?? 0) + (radius + 14) * Math.sin(midRad)
|
||||
break
|
||||
}
|
||||
case 'text':
|
||||
ctx.save()
|
||||
ctx.fillStyle = color
|
||||
ctx.font = '16px sans-serif'
|
||||
ctx.fillText(shape.content ?? '', shape.x ?? 0, shape.y ?? 0)
|
||||
ctx.restore()
|
||||
placedLabels.push(
|
||||
findFreeLabelPosition(ctx, shape.content ?? '', shape.x ?? 0, shape.y ?? 0, placedLabels)
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
if (shape.label && shape.type !== 'text') {
|
||||
ctx.save()
|
||||
ctx.fillStyle = color
|
||||
ctx.font = '13px sans-serif'
|
||||
const box = findFreeLabelPosition(
|
||||
ctx,
|
||||
shape.label,
|
||||
labelAnchorX + 4,
|
||||
labelAnchorY,
|
||||
placedLabels
|
||||
)
|
||||
ctx.fillText(shape.label, box.x, box.y + box.height - 3)
|
||||
placedLabels.push(box)
|
||||
ctx.restore()
|
||||
}
|
||||
}
|
||||
@@ -3,18 +3,12 @@ import './assets/main.css'
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import App from './App'
|
||||
import CoachProgressView from './components/CoachProgressView'
|
||||
import CoachExerciseView from './components/CoachExerciseView'
|
||||
import CoachDrawingView from './components/CoachDrawingView'
|
||||
import LoginView from './components/LoginView'
|
||||
|
||||
// Fenetres secondaires (ouvertes via le menu contextuel ou par Max en mode Coach) : chargent ce
|
||||
// meme bundle avec un hash different pour afficher une autre vue que l'avatar. La fenetre avatar,
|
||||
// chargee sans hash, continue de monter <App /> comme avant, sans aucun changement.
|
||||
// Fenetre secondaire (ouverte via le menu contextuel) : charge ce meme bundle avec un hash
|
||||
// different pour afficher une autre vue que l'avatar. La fenetre avatar, chargee sans hash,
|
||||
// continue de monter <App /> comme avant, sans aucun changement.
|
||||
function renderForHash(): React.JSX.Element {
|
||||
if (location.hash === '#coach-progress') return <CoachProgressView />
|
||||
if (location.hash === '#coach-exercise') return <CoachExerciseView />
|
||||
if (location.hash === '#coach-drawing') return <CoachDrawingView />
|
||||
if (location.hash === '#login') return <LoginView />
|
||||
return <App />
|
||||
}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { useEffect } from 'react'
|
||||
|
||||
async function captureFrame(): Promise<string | null> {
|
||||
let stream: MediaStream | null = null
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({ video: true })
|
||||
const video = document.createElement('video')
|
||||
video.srcObject = stream
|
||||
await video.play()
|
||||
// Laisse la camera ajuster l'exposition/la mise au point avant la capture.
|
||||
await new Promise((resolve) => setTimeout(resolve, 400))
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = video.videoWidth
|
||||
canvas.height = video.videoHeight
|
||||
canvas.getContext('2d')?.drawImage(video, 0, 0)
|
||||
return canvas.toDataURL('image/png')
|
||||
} catch (error) {
|
||||
console.error('[camera] capture impossible', error)
|
||||
return null
|
||||
} finally {
|
||||
stream?.getTracks().forEach((track) => track.stop())
|
||||
}
|
||||
}
|
||||
|
||||
// Capture une seule photo a la demande du process principal (jamais de flux continu).
|
||||
export function useCameraCapture(): void {
|
||||
useEffect(() => {
|
||||
return window.api.onCaptureCameraFrame((requestId) => {
|
||||
void captureFrame().then((dataUrl) => {
|
||||
window.api.sendCameraFrameResult(requestId, dataUrl)
|
||||
})
|
||||
})
|
||||
}, [])
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
export type ConceptStatus = 'not_started' | 'in_progress' | 'acquired' | 'to_review'
|
||||
export type SubjectStatus = 'researching' | 'assessing' | 'in_progress' | 'mastered'
|
||||
export type AssessmentKind = 'initial' | 'module' | 'final'
|
||||
export type ExerciseDifficulty = 'facile' | 'moyen' | 'difficile'
|
||||
export type ExerciseStyle = 'prediction' | 'debogage' | 'probleme_ouvert' | 'projet' | 'qcm_cible'
|
||||
|
||||
export interface SubjectProgress {
|
||||
subject: string
|
||||
level: string | null
|
||||
status: SubjectStatus
|
||||
objective: string | null
|
||||
lastSessionAt: string
|
||||
concepts: {
|
||||
name: string
|
||||
status: ConceptStatus
|
||||
lastReviewedAt: string
|
||||
nextReviewAt: string | null
|
||||
locked: boolean
|
||||
orderIndex: number
|
||||
}[]
|
||||
}
|
||||
|
||||
export interface ModuleAssessment {
|
||||
question: string
|
||||
answer: string
|
||||
dontKnow: boolean
|
||||
difficulty: ExerciseDifficulty | null
|
||||
exerciseStyle: ExerciseStyle | null
|
||||
targetsCommonError: string | null
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
/** Resultat d'une exigence du guide pedagogique, calcule a partir des donnees stockees (non-LLM). */
|
||||
export interface ComplianceCheck {
|
||||
key: string
|
||||
label: string
|
||||
ok: boolean
|
||||
detail: string
|
||||
}
|
||||
|
||||
export interface CourseComplianceReport {
|
||||
subject: string
|
||||
checks: ComplianceCheck[]
|
||||
}
|
||||
|
||||
export type ModuleDiagramKind = 'shapes' | 'mermaid'
|
||||
|
||||
export interface ModuleDiagram {
|
||||
kind: ModuleDiagramKind
|
||||
title: string
|
||||
data: unknown
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface ModuleDetail {
|
||||
name: string
|
||||
status: ConceptStatus
|
||||
locked: boolean
|
||||
theorySummary: string | null
|
||||
assessments: ModuleAssessment[]
|
||||
diagrams: ModuleDiagram[]
|
||||
}
|
||||
|
||||
export type ExerciseType = 'free_text' | 'multiple_choice' | 'true_false'
|
||||
|
||||
/** Une question parmi plusieurs posees en une seule fois (formulaire groupe, pas une par une). */
|
||||
export interface ExerciseFormItem {
|
||||
id: string
|
||||
question: string
|
||||
type: ExerciseType
|
||||
options: string[] | null
|
||||
}
|
||||
|
||||
export interface ExerciseForm {
|
||||
requestId: string
|
||||
items: ExerciseFormItem[]
|
||||
}
|
||||
|
||||
export interface ExerciseFormAnswer {
|
||||
id: string
|
||||
answer: string
|
||||
}
|
||||
|
||||
/** Reponse sentinelle soumise par le bouton "Je ne sais pas", toujours disponible. */
|
||||
export const DONT_KNOW_ANSWER = 'Je ne sais pas'
|
||||
@@ -1,13 +0,0 @@
|
||||
export type CourseBuildStepStatus = 'pending' | 'active' | 'done'
|
||||
|
||||
export interface CourseBuildStep {
|
||||
key: string
|
||||
label: string
|
||||
status: CourseBuildStepStatus
|
||||
detail?: string
|
||||
}
|
||||
|
||||
export interface CourseBuildState {
|
||||
subject: string
|
||||
steps: CourseBuildStep[]
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
export type ShapeType = 'rect' | 'circle' | 'line' | 'arrow' | 'text' | 'stroke' | 'arc' | 'preset'
|
||||
|
||||
export interface DrawShape {
|
||||
type: ShapeType
|
||||
x?: number | undefined
|
||||
y?: number | undefined
|
||||
x2?: number | undefined
|
||||
y2?: number | undefined
|
||||
width?: number | undefined
|
||||
height?: number | undefined
|
||||
radius?: number | undefined
|
||||
content?: string | undefined
|
||||
label?: string | undefined
|
||||
color?: string | undefined
|
||||
points?: { x: number; y: number }[] | undefined
|
||||
/** Legende orale dite au moment ou cette forme apparait (narration pas-a-pas). */
|
||||
caption?: string | undefined
|
||||
/** Pour type 'arc' : portion de cercle en degres (0 = droite, sens horaire). */
|
||||
startAngle?: number | undefined
|
||||
endAngle?: number | undefined
|
||||
/** Pour type 'arc' : true = part de camembert (reliee au centre), false/absent = arc ouvert. */
|
||||
closed?: boolean | undefined
|
||||
/** Pour type 'preset' : nom du preset (ex: "right_triangle") et ses parametres bruts. */
|
||||
preset?: string | undefined
|
||||
presetParams?: Record<string, unknown> | undefined
|
||||
}
|
||||
|
||||
export interface Drawing {
|
||||
title: string
|
||||
width: number
|
||||
height: number
|
||||
shapes: DrawShape[]
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const writeFileSyncMock = vi.fn()
|
||||
const readdirSyncMock = vi.fn(() => ['old.png', 'new.png'])
|
||||
const statSyncMock = vi.fn((path: string) => ({
|
||||
mtimeMs: path.includes('old') ? 0 : Date.now()
|
||||
}))
|
||||
const unlinkSyncMock = vi.fn()
|
||||
vi.mock('fs', () => ({
|
||||
writeFileSync: writeFileSyncMock,
|
||||
readdirSync: readdirSyncMock,
|
||||
statSync: statSyncMock,
|
||||
unlinkSync: unlinkSyncMock
|
||||
}))
|
||||
|
||||
const parentPort = new EventEmitter() as EventEmitter & { postMessage: (msg: unknown) => void }
|
||||
parentPort.postMessage = vi.fn()
|
||||
vi.mock('node:worker_threads', () => ({ parentPort }))
|
||||
|
||||
await import('../../src/main/coach/captureWorker')
|
||||
|
||||
describe('captureWorker (worker_thread message handler)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should write the given PNG buffer to disk and acknowledge success', () => {
|
||||
const png = Buffer.from([1, 2, 3])
|
||||
parentPort.emit('message', { filePath: 'C:\\captures\\shot.png', png })
|
||||
expect(writeFileSyncMock).toHaveBeenCalledWith('C:\\captures\\shot.png', png)
|
||||
expect(parentPort.postMessage).toHaveBeenCalledWith({
|
||||
ok: true,
|
||||
filePath: 'C:\\captures\\shot.png'
|
||||
})
|
||||
})
|
||||
|
||||
it('should report failure when writing fails', () => {
|
||||
writeFileSyncMock.mockImplementationOnce(() => {
|
||||
throw new Error('disk full')
|
||||
})
|
||||
parentPort.emit('message', { filePath: 'C:\\captures\\shot.png', png: Buffer.from([1]) })
|
||||
expect(parentPort.postMessage).toHaveBeenCalledWith({ ok: false, error: 'disk full' })
|
||||
})
|
||||
|
||||
it('should delete only files older than the cutoff when purging', () => {
|
||||
const purgeDir = 'C:\\captures'
|
||||
parentPort.emit('message', { purgeDir, cutoff: 1000 })
|
||||
expect(unlinkSyncMock).toHaveBeenCalledTimes(1)
|
||||
expect(unlinkSyncMock).toHaveBeenCalledWith(join(purgeDir, 'old.png'))
|
||||
expect(parentPort.postMessage).toHaveBeenCalledWith({ ok: true })
|
||||
})
|
||||
|
||||
it('should report failure when purging fails', () => {
|
||||
readdirSyncMock.mockImplementationOnce(() => {
|
||||
throw new Error('dir gone')
|
||||
})
|
||||
parentPort.emit('message', { purgeDir: 'C:\\captures', cutoff: 1000 })
|
||||
expect(parentPort.postMessage).toHaveBeenCalledWith({ ok: false, error: 'dir gone' })
|
||||
})
|
||||
})
|
||||
@@ -1,194 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeAll } from 'vitest'
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-coach-test-'))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tempDir }
|
||||
}))
|
||||
|
||||
// Importe apres le mock : getDb() lit app.getPath('userData') au premier appel et cree le fichier
|
||||
// sqlite dans un dossier temporaire dedie a ce fichier de test (jamais la vraie base utilisateur).
|
||||
const {
|
||||
setSubjectObjective,
|
||||
getSubjectObjective,
|
||||
setSubjectLevel,
|
||||
getSubjectLevel,
|
||||
createModules,
|
||||
listModules,
|
||||
allModulesHaveContent,
|
||||
modulesMissingContent,
|
||||
setModuleTheory,
|
||||
canWriteModuleContent,
|
||||
saveAssessment,
|
||||
hasAssessment,
|
||||
hasMultipleDifficulties,
|
||||
moduleDontKnowRatio,
|
||||
upsertConceptStatus,
|
||||
getProgress,
|
||||
getCourseComplianceReport,
|
||||
getResearchSummary
|
||||
} = await import('../../src/main/coach/coachStore')
|
||||
|
||||
const VALID_CONTENT = [
|
||||
'Accroche',
|
||||
'Un vendeur doit calculer rapidement combien de tissu acheter pour un mur triangulaire. '.repeat(
|
||||
16
|
||||
),
|
||||
'Developpement theorique',
|
||||
'Idee centrale, analogie, definition formelle, exemple resolu et contre-exemple. '.repeat(35),
|
||||
'Phase guidee',
|
||||
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier.',
|
||||
'Exercices progressifs',
|
||||
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
|
||||
'Exercice de debogage',
|
||||
"Trouve l'erreur dans ce calcul errone et corrige-la.",
|
||||
'Synthese',
|
||||
'Resume final avec question de meta-cognition et test Feynman. '.repeat(15)
|
||||
].join('\n\n')
|
||||
|
||||
describe('coachStore — objective', () => {
|
||||
it('should return null for a subject objective that was never set', () => {
|
||||
expect(getSubjectObjective('sujet-sans-objectif')).toBeNull()
|
||||
})
|
||||
|
||||
it('should return null when the subject exists but its objective/research were never set', () => {
|
||||
createModules('sujet-existant-sans-objectif', [{ name: 'Module unique' }])
|
||||
expect(getSubjectObjective('sujet-existant-sans-objectif')).toBeNull()
|
||||
expect(getResearchSummary('sujet-existant-sans-objectif')).toBeNull()
|
||||
})
|
||||
|
||||
it('should persist and retrieve a subject objective', () => {
|
||||
setSubjectObjective(
|
||||
'algebre-test',
|
||||
'Tu seras capable de resoudre une equation du premier degre'
|
||||
)
|
||||
expect(getSubjectObjective('algebre-test')).toBe(
|
||||
'Tu seras capable de resoudre une equation du premier degre'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('coachStore — modules et verrouillage sequentiel', () => {
|
||||
const subject = 'fractions-test'
|
||||
|
||||
it('should create modules with only the first one unlocked', () => {
|
||||
createModules(subject, [{ name: 'Module A' }, { name: 'Module B' }])
|
||||
const modules = listModules(subject)
|
||||
expect(modules.map((m) => m.name)).toEqual(['Module A', 'Module B'])
|
||||
expect(modules[0]?.locked).toBe(false)
|
||||
expect(modules[1]?.locked).toBe(true)
|
||||
})
|
||||
|
||||
it('should report missing content for every module before any is written', () => {
|
||||
expect(allModulesHaveContent(subject)).toBe(false)
|
||||
expect(modulesMissingContent(subject)).toEqual(['Module A', 'Module B'])
|
||||
})
|
||||
|
||||
it('should allow writing module content before a subject level is recorded', () => {
|
||||
expect(canWriteModuleContent(subject, 'Module A')).toEqual({ ok: true, blockedBy: null })
|
||||
expect(canWriteModuleContent(subject, 'Module B')).toEqual({ ok: true, blockedBy: null })
|
||||
})
|
||||
|
||||
it('should accept well-structured content and reflect it as no-longer-missing', () => {
|
||||
expect(setModuleTheory(subject, 'Module A', VALID_CONTENT)).toBe(true)
|
||||
expect(modulesMissingContent(subject)).toEqual(['Module B'])
|
||||
})
|
||||
|
||||
it('should block writing a later module once a subject level is recorded and an earlier module is unfinished', () => {
|
||||
setSubjectLevel(subject, 'debutant')
|
||||
expect(getSubjectLevel(subject)).toBe('debutant')
|
||||
const result = canWriteModuleContent(subject, 'Module B')
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.blockedBy).toBe('Module A')
|
||||
})
|
||||
})
|
||||
|
||||
describe("coachStore — evaluations et validation d'un module", () => {
|
||||
const subject = 'geometrie-test'
|
||||
const module = 'Module unique'
|
||||
|
||||
beforeAll(() => {
|
||||
createModules(subject, [{ name: module }])
|
||||
})
|
||||
|
||||
it('should report no assessment and a 100% "dont know" ratio before any is saved', () => {
|
||||
expect(hasAssessment(subject, module, 'module')).toBe(false)
|
||||
expect(moduleDontKnowRatio(subject, module)).toBe(1)
|
||||
expect(hasMultipleDifficulties(subject, module)).toBe(false)
|
||||
})
|
||||
|
||||
it('should track multiple distinct difficulties and a correct dont-know ratio after saving assessments', () => {
|
||||
saveAssessment(
|
||||
subject,
|
||||
module,
|
||||
'Question facile',
|
||||
'short_answer',
|
||||
null,
|
||||
'reponse',
|
||||
'module',
|
||||
false,
|
||||
'facile',
|
||||
'prediction',
|
||||
null
|
||||
)
|
||||
saveAssessment(
|
||||
subject,
|
||||
module,
|
||||
'Question moyenne',
|
||||
'short_answer',
|
||||
null,
|
||||
'je ne sais pas',
|
||||
'module',
|
||||
true,
|
||||
'moyen',
|
||||
'debogage',
|
||||
'erreur de signe'
|
||||
)
|
||||
|
||||
expect(hasAssessment(subject, module, 'module')).toBe(true)
|
||||
expect(hasMultipleDifficulties(subject, module)).toBe(true)
|
||||
expect(moduleDontKnowRatio(subject, module)).toBeCloseTo(0.5)
|
||||
})
|
||||
|
||||
it('should default to false/1 (blocking) for a subject that does not exist at all', () => {
|
||||
expect(hasMultipleDifficulties('sujet-totalement-inconnu', module)).toBe(false)
|
||||
expect(moduleDontKnowRatio('sujet-totalement-inconnu', module)).toBe(1)
|
||||
})
|
||||
|
||||
it('should persist multiple-choice options as JSON on the assessment', () => {
|
||||
saveAssessment(
|
||||
subject,
|
||||
module,
|
||||
'QCM',
|
||||
'multiple_choice',
|
||||
['A', 'B', 'C'],
|
||||
'A',
|
||||
'module',
|
||||
false,
|
||||
'difficile',
|
||||
'qcm_cible',
|
||||
null
|
||||
)
|
||||
expect(hasAssessment(subject, module, 'module')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('coachStore — progression et conformite', () => {
|
||||
it('should return an empty list when no subject exists yet', () => {
|
||||
expect(getProgress('sujet-totalement-inconnu')).toEqual([])
|
||||
})
|
||||
|
||||
it('should return null compliance for an unknown subject', () => {
|
||||
expect(getCourseComplianceReport('sujet-totalement-inconnu')).toBeNull()
|
||||
})
|
||||
|
||||
it('should include the source-documentation check in the compliance report for a known subject', () => {
|
||||
upsertConceptStatus('conformite-test', 'Un concept', 'not_started')
|
||||
const report = getCourseComplianceReport('conformite-test')
|
||||
expect(report).not.toBeNull()
|
||||
expect(report?.checks.some((c) => c.key === 'sources')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,88 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { validateModuleContent, missingContentSections } from '../../src/main/coach/coachStore'
|
||||
|
||||
function buildValidContent(): string {
|
||||
return [
|
||||
'Accroche',
|
||||
'Un vendeur doit calculer rapidement combien de tissu acheter pour couvrir un mur triangulaire. '.repeat(
|
||||
16
|
||||
),
|
||||
'Developpement theorique',
|
||||
'Idee centrale, analogie, definition formelle, exemple resolu et contre-exemple. '.repeat(35),
|
||||
'Phase guidee',
|
||||
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier le resultat.',
|
||||
'Exercices progressifs',
|
||||
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
|
||||
'Exercice de debogage',
|
||||
"Trouve l'erreur dans ce calcul errone et corrige-la.",
|
||||
'Synthese',
|
||||
'Resume final avec question de meta-cognition et test Feynman. '.repeat(15)
|
||||
].join('\n\n')
|
||||
}
|
||||
|
||||
describe('missingContentSections()', () => {
|
||||
it('should return every required section when content is empty', () => {
|
||||
const missing = missingContentSections('')
|
||||
expect(missing).toContain('Accroche')
|
||||
expect(missing).toContain('Synthese')
|
||||
expect(missing.length).toBe(6)
|
||||
})
|
||||
|
||||
it('should return no missing section when all section headers are present', () => {
|
||||
expect(missingContentSections(buildValidContent())).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateModuleContent()', () => {
|
||||
it('should accept well-structured content meeting all requirements', () => {
|
||||
expect(validateModuleContent(buildValidContent())).toEqual([])
|
||||
})
|
||||
|
||||
it('should reject content with missing sections', () => {
|
||||
const violations = validateModuleContent('Accroche\nTrop court.')
|
||||
expect(violations.length).toBeGreaterThan(0)
|
||||
expect(violations[0]).toMatch(/Sections manquantes/)
|
||||
})
|
||||
|
||||
it('should accept accented "ETAPE"/"EXERCICE" headers (regression: accent-insensitive match)', () => {
|
||||
const content = buildValidContent().replace('ETAPE', 'ÉTAPE').replace('EXERCICE', 'ÉXERCICE')
|
||||
expect(validateModuleContent(content)).toEqual([])
|
||||
})
|
||||
|
||||
it('should reject a "Phase guidee" section with fewer than 3 numbered steps', () => {
|
||||
const content = buildValidContent().replace(
|
||||
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier le resultat.',
|
||||
'ETAPE 1 : identifier les donnees.'
|
||||
)
|
||||
const violations = validateModuleContent(content)
|
||||
expect(violations.some((v) => /Phase guidee/.test(v))).toBe(true)
|
||||
})
|
||||
|
||||
it('should reject an "Exercices progressifs" section with fewer than 6 numbered exercises', () => {
|
||||
const content = buildValidContent().replace(
|
||||
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
|
||||
'EXERCICE 1 facile. EXERCICE 2 moyen.'
|
||||
)
|
||||
const violations = validateModuleContent(content)
|
||||
expect(violations.some((v) => /Exercices progressifs/.test(v))).toBe(true)
|
||||
})
|
||||
|
||||
it('should reject an "Exercice de debogage" section that never mentions an error', () => {
|
||||
const content = buildValidContent().replace(
|
||||
"Trouve l'erreur dans ce calcul errone et corrige-la.",
|
||||
'Resous ce calcul.'
|
||||
)
|
||||
const violations = validateModuleContent(content)
|
||||
expect(violations.some((v) => /debogage/.test(v))).toBe(true)
|
||||
})
|
||||
|
||||
it('should reject a section shorter than its required minimum word count', () => {
|
||||
const shortAccroche =
|
||||
'Un vendeur doit calculer rapidement combien de tissu acheter pour couvrir un mur triangulaire. '.repeat(
|
||||
16
|
||||
)
|
||||
const content = buildValidContent().replace(shortAccroche, 'Phrase courte.')
|
||||
const violations = validateModuleContent(content)
|
||||
expect(violations.some((v) => /Accroche.*trop courte/.test(v))).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -26,12 +26,10 @@ vi.mock('../../../src/renderer/src/voice/useVoiceAssistant', () => ({ useVoiceAs
|
||||
vi.mock('../../../src/renderer/src/voice/useProactiveSpeech', () => ({
|
||||
useProactiveSpeech: vi.fn()
|
||||
}))
|
||||
vi.mock('../../../src/renderer/src/voice/useCameraCapture', () => ({ useCameraCapture: vi.fn() }))
|
||||
vi.mock('../../../src/renderer/src/voice/useMeetingRecorder', () => ({
|
||||
useMeetingRecorder: vi.fn()
|
||||
}))
|
||||
|
||||
let onCourseBuildStepCb: ((state: unknown) => void) | undefined
|
||||
let onUpdateAvailableCb: (() => void) | undefined
|
||||
let onUpdateReadyCb: (() => void) | undefined
|
||||
const sendDroppedFiles = vi.fn()
|
||||
@@ -46,10 +44,6 @@ const getAuthStatus = vi.fn(async (): Promise<{ loggedIn: boolean; email: string
|
||||
|
||||
function setupWindowApi(): void {
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
onCourseBuildStep: vi.fn((cb: (s: unknown) => void) => {
|
||||
onCourseBuildStepCb = cb
|
||||
return () => {}
|
||||
}),
|
||||
onUpdateAvailable: vi.fn((cb: () => void) => {
|
||||
onUpdateAvailableCb = cb
|
||||
return () => {}
|
||||
@@ -109,17 +103,6 @@ describe('<App />', () => {
|
||||
expect(screen.queryByText(/Erreur reseau/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display the course build stepper once a state arrives', () => {
|
||||
render(<App />)
|
||||
act(() =>
|
||||
onCourseBuildStepCb?.({
|
||||
subject: 'algebre',
|
||||
steps: [{ key: 'recherche', label: 'Recherche', status: 'done' }]
|
||||
})
|
||||
)
|
||||
expect(screen.getByText(/algebre/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display the update banner when an update is available, then ready', () => {
|
||||
render(<App />)
|
||||
act(() => onUpdateAvailableCb?.())
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor, act } from '@testing-library/react'
|
||||
|
||||
const drawShape = vi.fn()
|
||||
vi.mock('../../../src/renderer/src/components/drawRoughShapes', () => ({ drawShape }))
|
||||
|
||||
const roughCanvas = vi.fn(() => ({}))
|
||||
vi.mock('roughjs', () => ({ default: { canvas: roughCanvas } }))
|
||||
|
||||
const mermaidRender = vi.fn(async () => ({ svg: '<svg></svg>' }))
|
||||
const mermaidInitialize = vi.fn()
|
||||
vi.mock('mermaid', () => ({
|
||||
default: { initialize: mermaidInitialize, render: mermaidRender }
|
||||
}))
|
||||
|
||||
interface InitDrawingPayload {
|
||||
title: string
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
interface RevealShapePayload {
|
||||
requestId: string
|
||||
shape: { type: string }
|
||||
audio: ArrayBuffer | null
|
||||
}
|
||||
interface RenderMermaidPayload {
|
||||
requestId: string
|
||||
title: string
|
||||
mermaidCode: string
|
||||
}
|
||||
interface PlayCaptionPayload {
|
||||
requestId: string
|
||||
audio: ArrayBuffer
|
||||
}
|
||||
|
||||
const listeners: {
|
||||
onInitDrawing?: (payload: InitDrawingPayload) => void
|
||||
onRevealShape?: (payload: RevealShapePayload) => void
|
||||
onRenderMermaid?: (payload: RenderMermaidPayload) => void
|
||||
onPlayCaption?: (payload: PlayCaptionPayload) => void
|
||||
} = {}
|
||||
|
||||
function setupWindowApi(): void {
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
onInitDrawing: vi.fn((cb: (payload: InitDrawingPayload) => void) => {
|
||||
listeners.onInitDrawing = cb
|
||||
return () => {}
|
||||
}),
|
||||
onRevealShape: vi.fn((cb: (payload: RevealShapePayload) => void) => {
|
||||
listeners.onRevealShape = cb
|
||||
return () => {}
|
||||
}),
|
||||
onRenderMermaid: vi.fn((cb: (payload: RenderMermaidPayload) => void) => {
|
||||
listeners.onRenderMermaid = cb
|
||||
return () => {}
|
||||
}),
|
||||
onPlayCaption: vi.fn((cb: (payload: PlayCaptionPayload) => void) => {
|
||||
listeners.onPlayCaption = cb
|
||||
return () => {}
|
||||
}),
|
||||
acknowledgeShapeReveal: vi.fn(),
|
||||
acknowledgeMermaidRendered: vi.fn(),
|
||||
acknowledgeCaptionDone: vi.fn()
|
||||
}
|
||||
}
|
||||
|
||||
const { default: CoachDrawingView } =
|
||||
await import('../../../src/renderer/src/components/CoachDrawingView')
|
||||
|
||||
describe('<CoachDrawingView />', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setupWindowApi()
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(
|
||||
{} as CanvasRenderingContext2D
|
||||
)
|
||||
})
|
||||
|
||||
it('should show a waiting message before any drawing is initialized', () => {
|
||||
render(<CoachDrawingView />)
|
||||
expect(screen.getByText(/En attente/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display the title once a drawing is initialized', () => {
|
||||
render(<CoachDrawingView />)
|
||||
act(() => listeners.onInitDrawing?.({ title: 'Mon dessin', width: 700, height: 500 }))
|
||||
expect(screen.getByText('Mon dessin')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should draw a revealed shape and acknowledge it when there is no audio', () => {
|
||||
render(<CoachDrawingView />)
|
||||
act(() => listeners.onInitDrawing?.({ title: 'Mon dessin', width: 700, height: 500 }))
|
||||
const api = (window as unknown as { api: { acknowledgeShapeReveal: ReturnType<typeof vi.fn> } })
|
||||
.api
|
||||
act(() =>
|
||||
listeners.onRevealShape?.({ requestId: 'r1', shape: { type: 'circle' }, audio: null })
|
||||
)
|
||||
expect(drawShape).toHaveBeenCalled()
|
||||
expect(api.acknowledgeShapeReveal).toHaveBeenCalledWith('r1')
|
||||
})
|
||||
|
||||
it('should switch to mermaid mode and render the diagram on success, waiting for the container to mount', async () => {
|
||||
render(<CoachDrawingView />)
|
||||
act(() =>
|
||||
listeners.onRenderMermaid?.({
|
||||
requestId: 'r2',
|
||||
title: 'Cycle de l-eau',
|
||||
mermaidCode: 'graph LR; A --> B'
|
||||
})
|
||||
)
|
||||
expect(screen.getByText('Cycle de l-eau')).toBeInTheDocument()
|
||||
const api = (
|
||||
window as unknown as { api: { acknowledgeMermaidRendered: ReturnType<typeof vi.fn> } }
|
||||
).api
|
||||
await waitFor(() => expect(api.acknowledgeMermaidRendered).toHaveBeenCalledWith('r2', true))
|
||||
})
|
||||
|
||||
it('should report a mermaid render failure', async () => {
|
||||
mermaidRender.mockRejectedValueOnce(new Error('syntaxe invalide'))
|
||||
render(<CoachDrawingView />)
|
||||
act(() =>
|
||||
listeners.onRenderMermaid?.({ requestId: 'r3', title: 'Echec', mermaidCode: 'invalide' })
|
||||
)
|
||||
const api = (
|
||||
window as unknown as { api: { acknowledgeMermaidRendered: ReturnType<typeof vi.fn> } }
|
||||
).api
|
||||
await waitFor(() =>
|
||||
expect(api.acknowledgeMermaidRendered).toHaveBeenCalledWith('r3', false, 'syntaxe invalide')
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,111 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, act } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { ExerciseForm } from '../../../src/shared/coach'
|
||||
|
||||
let onFormCallback: ((form: ExerciseForm) => void) | undefined
|
||||
const submitWrittenForm = vi.fn()
|
||||
|
||||
function setupWindowApi(): void {
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
onAskWrittenForm: vi.fn((cb: (form: ExerciseForm) => void) => {
|
||||
onFormCallback = cb
|
||||
return () => {}
|
||||
}),
|
||||
submitWrittenForm
|
||||
}
|
||||
}
|
||||
|
||||
const { default: CoachExerciseView } =
|
||||
await import('../../../src/renderer/src/components/CoachExerciseView')
|
||||
|
||||
const FORM: ExerciseForm = {
|
||||
requestId: 'req-1',
|
||||
items: [
|
||||
{
|
||||
id: '0',
|
||||
question: 'Quelle est la capitale de la France ?',
|
||||
type: 'free_text',
|
||||
options: null
|
||||
},
|
||||
{ id: '1', question: 'Vrai ou faux : 2+2=4', type: 'true_false', options: null },
|
||||
{ id: '2', question: 'Choisis la bonne reponse', type: 'multiple_choice', options: ['A', 'B'] }
|
||||
]
|
||||
}
|
||||
|
||||
describe('<CoachExerciseView />', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setupWindowApi()
|
||||
})
|
||||
|
||||
it('should show a waiting message before any form is received', () => {
|
||||
render(<CoachExerciseView />)
|
||||
expect(screen.getByText(/En attente de questions/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display every question once a form is received', () => {
|
||||
render(<CoachExerciseView />)
|
||||
act(() => onFormCallback?.(FORM))
|
||||
expect(screen.getByText(/capitale de la France/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/2\+2=4/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/bonne reponse/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should keep the submit button disabled until every question is answered', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachExerciseView />)
|
||||
act(() => onFormCallback?.(FORM))
|
||||
|
||||
const submitButton = screen.getByText('Soumettre tout le formulaire')
|
||||
expect(submitButton).toBeDisabled()
|
||||
|
||||
await user.type(screen.getByRole('textbox'), 'Paris')
|
||||
await user.click(screen.getByText('Vrai'))
|
||||
await user.click(screen.getByText('A'))
|
||||
|
||||
expect(submitButton).toBeEnabled()
|
||||
})
|
||||
|
||||
it('should allow answering "Je ne sais pas" to satisfy a question', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachExerciseView />)
|
||||
act(() => onFormCallback?.({ requestId: 'req-2', items: [FORM.items[0]!] }))
|
||||
|
||||
const submitButton = screen.getByText('Soumettre tout le formulaire')
|
||||
expect(submitButton).toBeDisabled()
|
||||
await user.click(screen.getByText('Je ne sais pas'))
|
||||
expect(submitButton).toBeEnabled()
|
||||
})
|
||||
|
||||
it('should submit all answers and show the confirmation message', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachExerciseView />)
|
||||
act(() => onFormCallback?.(FORM))
|
||||
|
||||
await user.type(screen.getByRole('textbox'), 'Paris')
|
||||
await user.click(screen.getByText('Vrai'))
|
||||
await user.click(screen.getByText('A'))
|
||||
await user.click(screen.getByText('Soumettre tout le formulaire'))
|
||||
|
||||
expect(submitWrittenForm).toHaveBeenCalledWith('req-1', [
|
||||
{ id: '0', answer: 'Paris' },
|
||||
{ id: '1', answer: 'Vrai' },
|
||||
{ id: '2', answer: 'A' }
|
||||
])
|
||||
expect(screen.getByText(/Reponses envoyees a Max/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should reset state and show a fresh form when a second form arrives', () => {
|
||||
render(<CoachExerciseView />)
|
||||
act(() => onFormCallback?.(FORM))
|
||||
act(() =>
|
||||
onFormCallback?.({
|
||||
requestId: 'req-3',
|
||||
items: [{ id: '0', question: 'Autre question', type: 'free_text', options: null }]
|
||||
})
|
||||
)
|
||||
expect(screen.getByText(/Autre question/)).toBeInTheDocument()
|
||||
expect(screen.queryByText(/capitale de la France/)).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,236 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type {
|
||||
SubjectProgress,
|
||||
ModuleDetail,
|
||||
CourseComplianceReport
|
||||
} from '../../../src/shared/coach'
|
||||
|
||||
const drawShape = vi.fn()
|
||||
vi.mock('../../../src/renderer/src/components/drawRoughShapes', () => ({ drawShape }))
|
||||
vi.mock('roughjs', () => ({ default: { canvas: vi.fn(() => ({})) } }))
|
||||
const mermaidRender = vi.fn(async () => ({ svg: '<svg></svg>' }))
|
||||
vi.mock('mermaid', () => ({ default: { initialize: vi.fn(), render: mermaidRender } }))
|
||||
|
||||
let navigateCallback: ((payload: { subject: string; module: string }) => void) | undefined
|
||||
const getCoachProgress = vi.fn()
|
||||
const getModuleDetail = vi.fn()
|
||||
const getCourseCompliance = vi.fn(async (): Promise<CourseComplianceReport | null> => null)
|
||||
const requestModuleEvaluation = vi.fn()
|
||||
|
||||
function setupWindowApi(): void {
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
getCoachProgress,
|
||||
getModuleDetail,
|
||||
getCourseCompliance,
|
||||
requestModuleEvaluation,
|
||||
onNavigateToModule: vi.fn((cb: (payload: { subject: string; module: string }) => void) => {
|
||||
navigateCallback = cb
|
||||
return () => {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const { default: CoachProgressView } =
|
||||
await import('../../../src/renderer/src/components/CoachProgressView')
|
||||
|
||||
const SUBJECT: SubjectProgress = {
|
||||
subject: 'algebre',
|
||||
level: 'debutant',
|
||||
status: 'in_progress',
|
||||
objective: 'Tu seras capable de resoudre une equation',
|
||||
lastSessionAt: new Date().toISOString(),
|
||||
concepts: [
|
||||
{
|
||||
name: 'Module A',
|
||||
status: 'acquired',
|
||||
lastReviewedAt: new Date().toISOString(),
|
||||
nextReviewAt: null,
|
||||
locked: false,
|
||||
orderIndex: 0
|
||||
},
|
||||
{
|
||||
name: 'Module B',
|
||||
status: 'not_started',
|
||||
lastReviewedAt: new Date().toISOString(),
|
||||
nextReviewAt: null,
|
||||
locked: true,
|
||||
orderIndex: 1
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const MODULE_DETAIL: ModuleDetail = {
|
||||
name: 'Module A',
|
||||
status: 'acquired',
|
||||
locked: false,
|
||||
theorySummary: 'Contenu du module.',
|
||||
assessments: [
|
||||
{
|
||||
question: 'Question 1 ?',
|
||||
answer: 'Reponse',
|
||||
dontKnow: false,
|
||||
difficulty: 'facile',
|
||||
exerciseStyle: 'prediction',
|
||||
targetsCommonError: null,
|
||||
createdAt: new Date().toISOString()
|
||||
}
|
||||
],
|
||||
diagrams: []
|
||||
}
|
||||
|
||||
describe('<CoachProgressView />', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setupWindowApi()
|
||||
getCoachProgress.mockResolvedValue([SUBJECT])
|
||||
getModuleDetail.mockResolvedValue(MODULE_DETAIL)
|
||||
getCourseCompliance.mockResolvedValue(null)
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
|
||||
clearRect: vi.fn()
|
||||
} as unknown as CanvasRenderingContext2D)
|
||||
})
|
||||
|
||||
it('should show a loading state before subjects arrive', () => {
|
||||
getCoachProgress.mockReturnValue(new Promise(() => {}))
|
||||
render(<CoachProgressView />)
|
||||
expect(screen.getByText('Chargement...')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should list the loaded subjects', async () => {
|
||||
render(<CoachProgressView />)
|
||||
expect(await screen.findByText('algebre')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should show an empty state when there are no subjects yet', async () => {
|
||||
getCoachProgress.mockResolvedValue([])
|
||||
render(<CoachProgressView />)
|
||||
expect(await screen.findByText(/Aucun sujet d.apprentissage/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should navigate to the modules view and list each module', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
expect(screen.getByText('Module A')).toBeInTheDocument()
|
||||
expect(screen.getByText('Module B')).toBeInTheDocument()
|
||||
expect(screen.getByText(/Niveau : debutant/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/resoudre une equation/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should disable a locked module button', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
expect(screen.getByText('Module B').closest('button')).toBeDisabled()
|
||||
})
|
||||
|
||||
it('should show the compliance checklist once loaded', async () => {
|
||||
getCourseCompliance.mockResolvedValue({
|
||||
subject: 'algebre',
|
||||
checks: [
|
||||
{ key: 'sources', label: 'Recherche sourcee', ok: true, detail: 'ok' },
|
||||
{ key: 'objective', label: 'Objectif mesurable', ok: false, detail: 'manquant' }
|
||||
]
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await waitFor(() => expect(screen.getByText(/1\/2/)).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('should navigate to a module detail view and show its content', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
expect(await screen.findByText('Contenu du module.')).toBeInTheDocument()
|
||||
expect(screen.getByText('Question 1 ?')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should show the "evaluer ce module" button for an unlocked, unacquired module', async () => {
|
||||
getModuleDetail.mockResolvedValue({ ...MODULE_DETAIL, status: 'in_progress' })
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
const evalButton = await screen.findByText('Evaluer ce module')
|
||||
await user.click(evalButton)
|
||||
expect(requestModuleEvaluation).toHaveBeenCalledWith('algebre', 'Module A')
|
||||
})
|
||||
|
||||
it('should not show the evaluation button once the module is acquired', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
await screen.findByText('Contenu du module.')
|
||||
expect(screen.queryByText('Evaluer ce module')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should navigate directly to a module detail view on an incoming navigate-to-module event', async () => {
|
||||
render(<CoachProgressView />)
|
||||
await waitFor(() => expect(navigateCallback).toBeDefined())
|
||||
navigateCallback?.({ subject: 'algebre', module: 'Module A' })
|
||||
expect(await screen.findByText('Contenu du module.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render a shapes diagram for a module', async () => {
|
||||
getModuleDetail.mockResolvedValue({
|
||||
...MODULE_DETAIL,
|
||||
diagrams: [
|
||||
{
|
||||
kind: 'shapes',
|
||||
title: 'Mon schema',
|
||||
data: { title: 'Mon schema', width: 400, height: 300, shapes: [] },
|
||||
createdAt: new Date().toISOString()
|
||||
}
|
||||
]
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
expect(await screen.findByText('Mon schema')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should render a mermaid diagram for a module', async () => {
|
||||
getModuleDetail.mockResolvedValue({
|
||||
...MODULE_DETAIL,
|
||||
diagrams: [
|
||||
{
|
||||
kind: 'mermaid',
|
||||
title: 'Mon diagramme',
|
||||
data: { mermaidCode: 'graph LR; A --> B' },
|
||||
createdAt: new Date().toISOString()
|
||||
}
|
||||
]
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
expect(await screen.findByText('Mon diagramme')).toBeInTheDocument()
|
||||
await waitFor(() => expect(mermaidRender).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('should go back from the module view to the modules list', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText('Module A'))
|
||||
await screen.findByText('Contenu du module.')
|
||||
await user.click(screen.getByText(/Retour aux modules/))
|
||||
expect(screen.getByText('Module A')).toBeInTheDocument()
|
||||
expect(screen.getByText('Module B')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should go back from the modules view to the subjects list', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<CoachProgressView />)
|
||||
await user.click(await screen.findByText('algebre'))
|
||||
await user.click(screen.getByText(/Retour aux sujets/))
|
||||
expect(await screen.findByText('algebre')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,32 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import CourseBuildStepper from '../../../src/renderer/src/components/CourseBuildStepper'
|
||||
import type { CourseBuildState } from '../../../src/shared/courseBuild'
|
||||
|
||||
const STATE: CourseBuildState = {
|
||||
subject: 'algebre',
|
||||
steps: [
|
||||
{ key: 'recherche', label: 'Recherche approfondie', status: 'done', detail: '5 source(s)' },
|
||||
{ key: 'plan', label: 'Objectif et plan de modules', status: 'active' },
|
||||
{ key: 'redaction', label: 'Redaction des modules', status: 'pending' }
|
||||
]
|
||||
}
|
||||
|
||||
describe('<CourseBuildStepper />', () => {
|
||||
it('should display the subject name', () => {
|
||||
render(<CourseBuildStepper state={STATE} />)
|
||||
expect(screen.getByText(/algebre/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display every step label', () => {
|
||||
render(<CourseBuildStepper state={STATE} />)
|
||||
expect(screen.getByText('Recherche approfondie')).toBeInTheDocument()
|
||||
expect(screen.getByText('Objectif et plan de modules')).toBeInTheDocument()
|
||||
expect(screen.getByText('Redaction des modules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should display the detail text only for steps that have one', () => {
|
||||
render(<CourseBuildStepper state={STATE} />)
|
||||
expect(screen.getByText('5 source(s)')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,174 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import {
|
||||
boxesOverlap,
|
||||
findFreeLabelPosition,
|
||||
drawArrowHead,
|
||||
drawShape,
|
||||
type LabelBox
|
||||
} from '../../../src/renderer/src/components/drawRoughShapes'
|
||||
import type { RoughCanvas } from 'roughjs/bin/canvas'
|
||||
|
||||
function fakeCtx(): {
|
||||
ctx: CanvasRenderingContext2D
|
||||
fillText: ReturnType<typeof vi.fn>
|
||||
beginPath: ReturnType<typeof vi.fn>
|
||||
fill: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
const fillText = vi.fn()
|
||||
const beginPath = vi.fn()
|
||||
const fill = vi.fn()
|
||||
const ctx = {
|
||||
measureText: vi.fn(() => ({ width: 40 })),
|
||||
save: vi.fn(),
|
||||
restore: vi.fn(),
|
||||
beginPath,
|
||||
moveTo: vi.fn(),
|
||||
lineTo: vi.fn(),
|
||||
closePath: vi.fn(),
|
||||
fill,
|
||||
fillText,
|
||||
fillStyle: '',
|
||||
font: ''
|
||||
} as unknown as CanvasRenderingContext2D
|
||||
return { ctx, fillText, beginPath, fill }
|
||||
}
|
||||
|
||||
function fakeRoughCanvas(): {
|
||||
rc: RoughCanvas
|
||||
rectangle: ReturnType<typeof vi.fn>
|
||||
circle: ReturnType<typeof vi.fn>
|
||||
line: ReturnType<typeof vi.fn>
|
||||
curve: ReturnType<typeof vi.fn>
|
||||
arc: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
const rectangle = vi.fn()
|
||||
const circle = vi.fn()
|
||||
const line = vi.fn()
|
||||
const curve = vi.fn()
|
||||
const arc = vi.fn()
|
||||
const rc = { rectangle, circle, line, curve, arc } as unknown as RoughCanvas
|
||||
return { rc, rectangle, circle, line, curve, arc }
|
||||
}
|
||||
|
||||
describe('boxesOverlap()', () => {
|
||||
it('should detect overlapping boxes', () => {
|
||||
const a: LabelBox = { x: 0, y: 0, width: 10, height: 10 }
|
||||
const b: LabelBox = { x: 5, y: 5, width: 10, height: 10 }
|
||||
expect(boxesOverlap(a, b)).toBe(true)
|
||||
})
|
||||
|
||||
it('should detect non-overlapping boxes', () => {
|
||||
const a: LabelBox = { x: 0, y: 0, width: 10, height: 10 }
|
||||
const b: LabelBox = { x: 100, y: 100, width: 10, height: 10 }
|
||||
expect(boxesOverlap(a, b)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('findFreeLabelPosition()', () => {
|
||||
it('should return the starting position when nothing is placed yet', () => {
|
||||
const { ctx } = fakeCtx()
|
||||
const box = findFreeLabelPosition(ctx, 'Label', 10, 30, [])
|
||||
expect(box).toEqual({ x: 10, y: 14, width: 40, height: 16 })
|
||||
})
|
||||
|
||||
it('should shift downward to avoid an already-placed overlapping box', () => {
|
||||
const { ctx } = fakeCtx()
|
||||
const placed: LabelBox[] = [{ x: 10, y: 14, width: 40, height: 16 }]
|
||||
const box = findFreeLabelPosition(ctx, 'Label', 10, 30, placed)
|
||||
expect(box.y).toBeGreaterThan(14)
|
||||
})
|
||||
|
||||
it('should fall back to the last attempted position after 20 attempts if always overlapping', () => {
|
||||
const { ctx } = fakeCtx()
|
||||
const placed: LabelBox[] = Array.from({ length: 25 }, (_, i) => ({
|
||||
x: 10,
|
||||
y: 14 + i * 16,
|
||||
width: 40,
|
||||
height: 16
|
||||
}))
|
||||
const box = findFreeLabelPosition(ctx, 'Label', 10, 30, placed)
|
||||
expect(box).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('drawArrowHead()', () => {
|
||||
it('should draw a filled triangle at the arrow tip', () => {
|
||||
const { ctx, beginPath, fill } = fakeCtx()
|
||||
drawArrowHead(ctx, 0, 0, 10, 10, '#000')
|
||||
expect(beginPath).toHaveBeenCalled()
|
||||
expect(fill).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('drawShape()', () => {
|
||||
it('should draw a rectangle', () => {
|
||||
const { rc, rectangle } = fakeRoughCanvas()
|
||||
const { ctx } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'rect', x: 1, y: 2, width: 10, height: 20 }, [])
|
||||
expect(rectangle).toHaveBeenCalledWith(1, 2, 10, 20, expect.anything())
|
||||
})
|
||||
|
||||
it('should draw a circle', () => {
|
||||
const { rc, circle } = fakeRoughCanvas()
|
||||
const { ctx } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'circle', x: 1, y: 2, radius: 5 }, [])
|
||||
expect(circle).toHaveBeenCalledWith(1, 2, 10, expect.anything())
|
||||
})
|
||||
|
||||
it('should draw a line and position its label at the segment midpoint', () => {
|
||||
const { rc, line } = fakeRoughCanvas()
|
||||
const { ctx, fillText } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'line', x: 0, y: 0, x2: 10, y2: 0, label: 'AB' }, [])
|
||||
expect(line).toHaveBeenCalledWith(0, 0, 10, 0, expect.anything())
|
||||
expect(fillText).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should draw an arrow with an arrowhead', () => {
|
||||
const { rc, line } = fakeRoughCanvas()
|
||||
const { ctx, fill } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'arrow', x: 0, y: 0, x2: 10, y2: 10 }, [])
|
||||
expect(line).toHaveBeenCalled()
|
||||
expect(fill).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should draw a stroke curve only when at least 2 points are given', () => {
|
||||
const { rc, curve } = fakeRoughCanvas()
|
||||
const { ctx } = fakeCtx()
|
||||
drawShape(
|
||||
rc,
|
||||
ctx,
|
||||
{
|
||||
type: 'stroke',
|
||||
points: [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 1 }
|
||||
]
|
||||
},
|
||||
[]
|
||||
)
|
||||
expect(curve).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should not draw a stroke with fewer than 2 points', () => {
|
||||
const { rc, curve } = fakeRoughCanvas()
|
||||
const { ctx } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'stroke', points: [{ x: 0, y: 0 }] }, [])
|
||||
expect(curve).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should draw an arc', () => {
|
||||
const { rc, arc } = fakeRoughCanvas()
|
||||
const { ctx } = fakeCtx()
|
||||
drawShape(rc, ctx, { type: 'arc', x: 0, y: 0, radius: 10, startAngle: 0, endAngle: 90 }, [])
|
||||
expect(arc).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should draw text content directly and record its label box', () => {
|
||||
const { rc } = fakeRoughCanvas()
|
||||
const { ctx, fillText } = fakeCtx()
|
||||
const placed: LabelBox[] = []
|
||||
drawShape(rc, ctx, { type: 'text', x: 0, y: 0, content: 'Bonjour' }, placed)
|
||||
expect(fillText).toHaveBeenCalledWith('Bonjour', 0, 0)
|
||||
expect(placed.length).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -1,51 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
|
||||
let onCaptureCallback: ((requestId: string) => void) | undefined
|
||||
const sendCameraFrameResult = vi.fn()
|
||||
const onCaptureCameraFrame = vi.fn((cb: (requestId: string) => void) => {
|
||||
onCaptureCallback = cb
|
||||
return () => {}
|
||||
})
|
||||
|
||||
const stopTrack = vi.fn()
|
||||
const getUserMedia = vi.fn(async () => ({
|
||||
getTracks: () => [{ stop: stopTrack }]
|
||||
}))
|
||||
|
||||
const { useCameraCapture } = await import('../../../src/renderer/src/voice/useCameraCapture')
|
||||
|
||||
describe('useCameraCapture()', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
onCaptureCameraFrame,
|
||||
sendCameraFrameResult
|
||||
}
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia },
|
||||
configurable: true
|
||||
})
|
||||
vi.spyOn(HTMLMediaElement.prototype, 'play').mockResolvedValue()
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
|
||||
drawImage: vi.fn()
|
||||
} as unknown as CanvasRenderingContext2D)
|
||||
HTMLCanvasElement.prototype.toDataURL = vi.fn(() => 'data:image/png;base64,abc')
|
||||
})
|
||||
|
||||
it('should capture a frame and send it back on request', async () => {
|
||||
renderHook(() => useCameraCapture())
|
||||
onCaptureCallback?.('req-1')
|
||||
await vi.waitFor(() => expect(sendCameraFrameResult).toHaveBeenCalled())
|
||||
expect(sendCameraFrameResult).toHaveBeenCalledWith('req-1', 'data:image/png;base64,abc')
|
||||
expect(stopTrack).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should send null when the camera is unavailable', async () => {
|
||||
getUserMedia.mockRejectedValueOnce(new Error('no camera'))
|
||||
renderHook(() => useCameraCapture())
|
||||
onCaptureCallback?.('req-2')
|
||||
await vi.waitFor(() => expect(sendCameraFrameResult).toHaveBeenCalled())
|
||||
expect(sendCameraFrameResult).toHaveBeenCalledWith('req-2', null)
|
||||
})
|
||||
})
|
||||
@@ -1,108 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const sendToRenderer = vi.fn()
|
||||
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer }))
|
||||
|
||||
const { recordCourseBuildTool, clearCourseBuild } =
|
||||
await import('../../src/main/coach/courseBuildStepper')
|
||||
|
||||
interface Payload {
|
||||
subject: string
|
||||
steps: { key: string; status: string; detail?: string }[]
|
||||
}
|
||||
|
||||
function lastPayload(): Payload {
|
||||
const call = sendToRenderer.mock.calls.at(-1) as [string, Payload] | undefined
|
||||
if (!call) throw new Error('sendToRenderer was never called')
|
||||
return call[1]
|
||||
}
|
||||
|
||||
describe('courseBuildStepper', () => {
|
||||
beforeEach(() => {
|
||||
sendToRenderer.mockClear()
|
||||
})
|
||||
|
||||
it('should ignore a tool call with no subject', () => {
|
||||
recordCourseBuildTool('research_topic', {})
|
||||
expect(sendToRenderer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should ignore an unrecognized tool name', () => {
|
||||
recordCourseBuildTool('unknown_tool', { subject: 'algebre' })
|
||||
expect(sendToRenderer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should mark recherche done and plan active after research_topic, with source count', () => {
|
||||
recordCourseBuildTool('research_topic', { subject: 'algebre', sources: [{}, {}, {}] })
|
||||
const payload = lastPayload()
|
||||
expect(payload.subject).toBe('algebre')
|
||||
const recherche = payload.steps.find((s) => s.key === 'recherche')
|
||||
const plan = payload.steps.find((s) => s.key === 'plan')
|
||||
expect(recherche?.status).toBe('done')
|
||||
expect(recherche?.detail).toBe('3 source(s)')
|
||||
expect(plan?.status).toBe('active')
|
||||
})
|
||||
|
||||
it('should mark plan done and redaction active after generate_course_plan with modules', () => {
|
||||
recordCourseBuildTool('generate_course_plan', {
|
||||
subject: 'algebre',
|
||||
modules: [{ name: 'A' }, { name: 'B' }]
|
||||
})
|
||||
const payload = lastPayload()
|
||||
const plan = payload.steps.find((s) => s.key === 'plan')
|
||||
const redaction = payload.steps.find((s) => s.key === 'redaction')
|
||||
expect(plan?.status).toBe('done')
|
||||
expect(redaction?.status).toBe('active')
|
||||
expect(redaction?.detail).toBe('0/2')
|
||||
})
|
||||
|
||||
it('should mark redaction done and evaluation_initiale active once every module is written', () => {
|
||||
recordCourseBuildTool('write_module_content', { subject: 'algebre' })
|
||||
let payload = lastPayload()
|
||||
expect(payload.steps.find((s) => s.key === 'redaction')?.detail).toBe('1/2')
|
||||
expect(payload.steps.find((s) => s.key === 'redaction')?.status).toBe('active')
|
||||
|
||||
recordCourseBuildTool('write_module_content', { subject: 'algebre' })
|
||||
payload = lastPayload()
|
||||
expect(payload.steps.find((s) => s.key === 'redaction')?.status).toBe('done')
|
||||
expect(payload.steps.find((s) => s.key === 'evaluation_initiale')?.status).toBe('active')
|
||||
})
|
||||
|
||||
it('should mark evaluation_initiale done and niveau active on an initial assessment', () => {
|
||||
recordCourseBuildTool('ask_written_exercise', { subject: 'algebre', kind: 'initial' })
|
||||
const payload = lastPayload()
|
||||
expect(payload.steps.find((s) => s.key === 'evaluation_initiale')?.status).toBe('done')
|
||||
expect(payload.steps.find((s) => s.key === 'niveau')?.status).toBe('active')
|
||||
})
|
||||
|
||||
it('should not progress the "niveau" step on a non-initial assessment', () => {
|
||||
recordCourseBuildTool('ask_written_exercise', { subject: 'algebre', kind: 'module' })
|
||||
const payload = lastPayload()
|
||||
expect(payload.steps.find((s) => s.key === 'niveau')?.status).toBe('active')
|
||||
})
|
||||
|
||||
it('should mark niveau done after record_subject_level', () => {
|
||||
recordCourseBuildTool('record_subject_level', { subject: 'algebre' })
|
||||
const payload = lastPayload()
|
||||
expect(payload.steps.find((s) => s.key === 'niveau')?.status).toBe('done')
|
||||
})
|
||||
|
||||
it('should mark revision done on a second generate_course_plan call after the level is recorded', () => {
|
||||
recordCourseBuildTool('generate_course_plan', { subject: 'algebre', modules: [{ name: 'A' }] })
|
||||
const payload = lastPayload()
|
||||
expect(payload.steps.find((s) => s.key === 'revision')?.status).toBe('done')
|
||||
})
|
||||
|
||||
it('should reset the stepper state when a different subject starts', () => {
|
||||
recordCourseBuildTool('research_topic', { subject: 'geometrie', sources: [] })
|
||||
const payload = lastPayload()
|
||||
expect(payload.subject).toBe('geometrie')
|
||||
expect(payload.steps.find((s) => s.key === 'niveau')?.status).toBe('pending')
|
||||
})
|
||||
|
||||
it('should clear the stepper state and notify the renderer with null', () => {
|
||||
sendToRenderer.mockClear()
|
||||
clearCourseBuild()
|
||||
expect(sendToRenderer).toHaveBeenCalledWith('course-build-step', null)
|
||||
})
|
||||
})
|
||||
@@ -1,155 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { EventEmitter } from 'node:events'
|
||||
|
||||
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
|
||||
|
||||
class FakeWebContents extends EventEmitter {
|
||||
send = vi.fn()
|
||||
isLoading = vi.fn(() => false)
|
||||
}
|
||||
|
||||
class FakeBrowserWindow extends EventEmitter {
|
||||
webContents = new FakeWebContents()
|
||||
show = vi.fn()
|
||||
moveTop = vi.fn()
|
||||
focus = vi.fn()
|
||||
setAlwaysOnTop = vi.fn()
|
||||
maximize = vi.fn()
|
||||
loadURL = vi.fn()
|
||||
loadFile = vi.fn()
|
||||
destroyed = false
|
||||
isDestroyed(): boolean {
|
||||
return this.destroyed
|
||||
}
|
||||
}
|
||||
|
||||
let lastWindow: FakeBrowserWindow | null = null
|
||||
const ipcMainListeners = new Map<string, Set<(...args: unknown[]) => void>>()
|
||||
const ipcMain = {
|
||||
on: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
|
||||
if (!ipcMainListeners.has(event)) ipcMainListeners.set(event, new Set())
|
||||
ipcMainListeners.get(event)?.add(handler)
|
||||
}),
|
||||
removeListener: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
|
||||
ipcMainListeners.get(event)?.delete(handler)
|
||||
})
|
||||
}
|
||||
function fireIpc(event: string, ...args: unknown[]): void {
|
||||
for (const handler of ipcMainListeners.get(event) ?? []) handler(...args)
|
||||
}
|
||||
|
||||
function createBrowserWindow(): FakeBrowserWindow {
|
||||
const window = new FakeBrowserWindow()
|
||||
lastWindow = window
|
||||
return window
|
||||
}
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
BrowserWindow: vi.fn(createBrowserWindow),
|
||||
ipcMain
|
||||
}))
|
||||
|
||||
const { openDrawingWindow, revealShape, renderMermaid, playCaption } =
|
||||
await import('../../src/main/coach/drawingWindow')
|
||||
|
||||
describe('openDrawingWindow()', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
ipcMainListeners.clear()
|
||||
})
|
||||
|
||||
it('should create the window, load it and send init-drawing once ready', async () => {
|
||||
await openDrawingWindow('Mon titre', 700, 500)
|
||||
expect(lastWindow?.show).toHaveBeenCalled()
|
||||
expect(lastWindow?.webContents.send).toHaveBeenCalledWith('init-drawing', {
|
||||
title: 'Mon titre',
|
||||
width: 700,
|
||||
height: 500
|
||||
})
|
||||
})
|
||||
|
||||
it('should reuse the existing window on a second call rather than creating a new one', async () => {
|
||||
await openDrawingWindow('Titre 1', 700, 500)
|
||||
const firstWindow = lastWindow
|
||||
await openDrawingWindow('Titre 2', 700, 500)
|
||||
expect(lastWindow).toBe(firstWindow)
|
||||
})
|
||||
})
|
||||
|
||||
describe('revealShape()', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
ipcMainListeners.clear()
|
||||
await openDrawingWindow('Titre', 700, 500)
|
||||
})
|
||||
|
||||
it('should resolve once the renderer acknowledges the reveal with the matching request id', async () => {
|
||||
const promise = revealShape({ type: 'circle', x: 1, y: 1 }, null)
|
||||
const sentPayload = lastWindow?.webContents.send.mock.calls.find(
|
||||
(c) => c[0] === 'reveal-shape'
|
||||
)?.[1] as { requestId: string }
|
||||
fireIpc('shape-reveal-done', {}, sentPayload.requestId)
|
||||
await expect(promise).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('should resolve immediately when there is no open window', async () => {
|
||||
lastWindow!.destroyed = true
|
||||
await expect(revealShape({ type: 'circle', x: 1, y: 1 }, null)).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('should resolve after the timeout even without an acknowledgement', async () => {
|
||||
vi.useFakeTimers()
|
||||
const promise = revealShape({ type: 'circle', x: 1, y: 1 }, null, 1000)
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
await expect(promise).resolves.toBeUndefined()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
|
||||
describe('renderMermaid()', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
ipcMainListeners.clear()
|
||||
await openDrawingWindow('Titre', 700, 500)
|
||||
})
|
||||
|
||||
it('should resolve when the renderer reports a successful render', async () => {
|
||||
const promise = renderMermaid('Cycle', 'graph LR; A --> B')
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
const sentPayload = lastWindow?.webContents.send.mock.calls.find(
|
||||
(c) => c[0] === 'render-mermaid'
|
||||
)?.[1] as { requestId: string }
|
||||
fireIpc('mermaid-render-done', {}, sentPayload.requestId, true)
|
||||
await expect(promise).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('should reject with the renderer-provided error on a failed render', async () => {
|
||||
const promise = renderMermaid('Cycle', 'graph LR; A --> B')
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
const sentPayload = lastWindow?.webContents.send.mock.calls.find(
|
||||
(c) => c[0] === 'render-mermaid'
|
||||
)?.[1] as { requestId: string }
|
||||
fireIpc('mermaid-render-done', {}, sentPayload.requestId, false, 'syntaxe invalide')
|
||||
await expect(promise).rejects.toThrow('syntaxe invalide')
|
||||
})
|
||||
})
|
||||
|
||||
describe('playCaption()', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
ipcMainListeners.clear()
|
||||
await openDrawingWindow('Titre', 700, 500)
|
||||
})
|
||||
|
||||
it('should resolve once the renderer acknowledges the caption is done', async () => {
|
||||
const audio = new ArrayBuffer(4)
|
||||
const promise = playCaption(audio)
|
||||
const sentPayload = lastWindow?.webContents.send.mock.calls.find(
|
||||
(c) => c[0] === 'play-caption'
|
||||
)?.[1] as { requestId: string }
|
||||
fireIpc('caption-done', {}, sentPayload.requestId)
|
||||
await expect(promise).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -1,124 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { EventEmitter } from 'node:events'
|
||||
|
||||
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
|
||||
|
||||
class FakeWebContents extends EventEmitter {
|
||||
send = vi.fn()
|
||||
isLoading = vi.fn(() => false)
|
||||
}
|
||||
|
||||
class FakeBrowserWindow extends EventEmitter {
|
||||
webContents = new FakeWebContents()
|
||||
show = vi.fn()
|
||||
moveTop = vi.fn()
|
||||
focus = vi.fn()
|
||||
setAlwaysOnTop = vi.fn()
|
||||
maximize = vi.fn()
|
||||
loadURL = vi.fn()
|
||||
loadFile = vi.fn()
|
||||
close = vi.fn()
|
||||
destroyed = false
|
||||
isDestroyed(): boolean {
|
||||
return this.destroyed
|
||||
}
|
||||
}
|
||||
|
||||
let lastWindow: FakeBrowserWindow | null = null
|
||||
let nextWindowStartsLoading = false
|
||||
function createBrowserWindow(): FakeBrowserWindow {
|
||||
const window = new FakeBrowserWindow()
|
||||
if (nextWindowStartsLoading) {
|
||||
window.webContents.isLoading.mockReturnValue(true)
|
||||
nextWindowStartsLoading = false
|
||||
}
|
||||
lastWindow = window
|
||||
return window
|
||||
}
|
||||
|
||||
const ipcMainListeners = new Map<string, Set<(...args: unknown[]) => void>>()
|
||||
const ipcMain = {
|
||||
on: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
|
||||
if (!ipcMainListeners.has(event)) ipcMainListeners.set(event, new Set())
|
||||
ipcMainListeners.get(event)?.add(handler)
|
||||
}),
|
||||
removeListener: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
|
||||
ipcMainListeners.get(event)?.delete(handler)
|
||||
})
|
||||
}
|
||||
function fireIpc(event: string, ...args: unknown[]): void {
|
||||
for (const handler of ipcMainListeners.get(event) ?? []) handler(...args)
|
||||
}
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
BrowserWindow: vi.fn(createBrowserWindow),
|
||||
ipcMain
|
||||
}))
|
||||
|
||||
const { requestWrittenAnswers } = await import('../../src/main/coach/exerciseWindow')
|
||||
|
||||
describe('requestWrittenAnswers()', () => {
|
||||
beforeEach(() => {
|
||||
// Reinitialise le singleton interne du module (win = null) en simulant la fermeture de la
|
||||
// fenetre precedente, pour qu'un nouveau test reparte toujours d'une fenetre fraiche.
|
||||
lastWindow?.emit('closed')
|
||||
vi.clearAllMocks()
|
||||
ipcMainListeners.clear()
|
||||
lastWindow = null
|
||||
})
|
||||
|
||||
it('should send the question list to the renderer and show the window', async () => {
|
||||
const promise = requestWrittenAnswers([{ question: 'Q1', type: 'free_text', options: null }])
|
||||
expect(lastWindow?.show).toHaveBeenCalled()
|
||||
expect(lastWindow?.webContents.send).toHaveBeenCalledWith(
|
||||
'ask-written-form',
|
||||
expect.objectContaining({
|
||||
items: [{ id: '0', question: 'Q1', type: 'free_text', options: null }]
|
||||
})
|
||||
)
|
||||
const sentPayload = lastWindow?.webContents.send.mock.calls[0]?.[1] as { requestId: string }
|
||||
fireIpc('written-form-result', {}, sentPayload.requestId, [{ id: '0', answer: 'ma reponse' }])
|
||||
await expect(promise).resolves.toEqual(['ma reponse'])
|
||||
})
|
||||
|
||||
it('should resolve with nulls for items missing from the submitted answers', async () => {
|
||||
const promise = requestWrittenAnswers([
|
||||
{ question: 'Q1', type: 'free_text', options: null },
|
||||
{ question: 'Q2', type: 'free_text', options: null }
|
||||
])
|
||||
const sentPayload = lastWindow?.webContents.send.mock.calls[0]?.[1] as { requestId: string }
|
||||
fireIpc('written-form-result', {}, sentPayload.requestId, [{ id: '0', answer: 'reponse 1' }])
|
||||
await expect(promise).resolves.toEqual(['reponse 1', null])
|
||||
})
|
||||
|
||||
it('should ignore a submission for a different request id', () => {
|
||||
void requestWrittenAnswers([{ question: 'Q1', type: 'free_text', options: null }])
|
||||
fireIpc('written-form-result', {}, 'un-autre-id', [{ id: '0', answer: 'ignore' }])
|
||||
expect(lastWindow?.close).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should resolve with all nulls when the window is closed before submission', async () => {
|
||||
const promise = requestWrittenAnswers([{ question: 'Q1', type: 'free_text', options: null }])
|
||||
lastWindow?.emit('closed')
|
||||
await expect(promise).resolves.toEqual([null])
|
||||
})
|
||||
|
||||
it('should resolve with all nulls when the timeout elapses with no submission', async () => {
|
||||
vi.useFakeTimers()
|
||||
const promise = requestWrittenAnswers(
|
||||
[{ question: 'Q1', type: 'free_text', options: null }],
|
||||
1000
|
||||
)
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
await expect(promise).resolves.toEqual([null])
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should wait for did-finish-load before sending the form when the page is still loading', () => {
|
||||
nextWindowStartsLoading = true
|
||||
void requestWrittenAnswers([{ question: 'Q1', type: 'free_text', options: null }])
|
||||
expect(lastWindow?.webContents.send).not.toHaveBeenCalled()
|
||||
lastWindow?.webContents.emit('did-finish-load')
|
||||
expect(lastWindow?.webContents.send).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -24,16 +24,6 @@ vi.mock('../../src/main/ai/elevenlabs', () => ({ synthesizeSpeech }))
|
||||
const sendToRenderer = vi.fn()
|
||||
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer }))
|
||||
|
||||
const getSubjectLevel = vi.fn((): string | null => null)
|
||||
vi.mock('../../src/main/coach/coachStore', () => ({ getSubjectLevel }))
|
||||
|
||||
const recordCourseBuildTool = vi.fn()
|
||||
const clearCourseBuild = vi.fn()
|
||||
vi.mock('../../src/main/coach/courseBuildStepper', () => ({
|
||||
recordCourseBuildTool,
|
||||
clearCourseBuild
|
||||
}))
|
||||
|
||||
const { getAssistantReply } = await import('../../src/main/ai/openrouter')
|
||||
|
||||
function okResponse(body: unknown): Response {
|
||||
@@ -65,7 +55,6 @@ describe('getAssistantReply()', () => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
currentSkills = []
|
||||
getSubjectLevel.mockReturnValue(null)
|
||||
process.env.OPENROUTER_API_KEY = 'test-key'
|
||||
setCurrentUserEmail('test@example.com')
|
||||
})
|
||||
@@ -198,64 +187,3 @@ describe('getAssistantReply()', () => {
|
||||
await expect(getAssistantReply('boucle indefiniment')).rejects.toThrow(/Trop d'appels d'outils/)
|
||||
}, 20000)
|
||||
})
|
||||
|
||||
describe('getAssistantReply() — garde-fous du pipeline Coach', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
getSubjectLevel.mockReturnValue(null)
|
||||
process.env.OPENROUTER_API_KEY = 'test-key'
|
||||
setCurrentUserEmail('test@example.com')
|
||||
currentSkills = [
|
||||
{
|
||||
name: 'research_topic',
|
||||
description: '',
|
||||
parameters: {},
|
||||
execute: vi.fn(async () => 'Recherche enregistree.')
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
it('should force a retry toward generate_course_plan when research_topic was called but not the plan', async () => {
|
||||
const executeGeneratePlan = vi.fn(async () => 'Plan enregistre.')
|
||||
currentSkills.push({
|
||||
name: 'generate_course_plan',
|
||||
description: '',
|
||||
parameters: {},
|
||||
execute: executeGeneratePlan
|
||||
})
|
||||
// Des que le nudge a ete pousse une fois (verifie par l'appel ci-dessous), on simule que le
|
||||
// niveau vient d'etre enregistre pour ne pas enchainer sur tous les nudges suivants du pipeline
|
||||
// (plan -> contenu -> evaluation) : seul le declenchement de CE nudge precis est teste ici.
|
||||
getSubjectLevel.mockImplementation(() =>
|
||||
executeGeneratePlan.mock.calls.length > 0 ? 'debutant' : null
|
||||
)
|
||||
vi.mocked(fetch)
|
||||
.mockResolvedValueOnce(okResponse(toolCallMessage('research_topic', { subject: 'algebre' })))
|
||||
.mockResolvedValueOnce(okResponse(textMessage("J'ai fini pour l'instant.")))
|
||||
.mockResolvedValueOnce(
|
||||
okResponse(toolCallMessage('generate_course_plan', { subject: 'algebre' }))
|
||||
)
|
||||
.mockResolvedValueOnce(okResponse(textMessage('Plan en cours.')))
|
||||
|
||||
const reply = await getAssistantReply('apprends-moi algebre')
|
||||
expect(executeGeneratePlan).toHaveBeenCalled()
|
||||
expect(reply).toBe('Plan en cours.')
|
||||
})
|
||||
|
||||
it('should force a retry when the model announces an action at round 0 without calling any tool', async () => {
|
||||
// "subject" est volontairement omis : on isole ici le garde-fou "annonce au round 0", pas celui
|
||||
// du pipeline (recherche -> plan), qui se redeclencherait sinon des que trackedSubject est fixe.
|
||||
vi.mocked(fetch)
|
||||
.mockResolvedValueOnce(
|
||||
okResponse(
|
||||
textMessage("Je vais t'apprendre la trigonometrie ! Commencons par une recherche.")
|
||||
)
|
||||
)
|
||||
.mockResolvedValueOnce(okResponse(toolCallMessage('research_topic', {})))
|
||||
.mockResolvedValueOnce(okResponse(textMessage('Recherche terminee, module prepare.')))
|
||||
|
||||
const reply = await getAssistantReply('apprends-moi la trigonometrie')
|
||||
expect(reply).toBe('Recherche terminee, module prepare.')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { PRESET_GENERATORS } from '../../src/main/coach/presets'
|
||||
|
||||
describe('PRESET_GENERATORS', () => {
|
||||
it('should register a generator for every documented preset name', () => {
|
||||
const expectedNames = [
|
||||
'right_triangle',
|
||||
'triangle',
|
||||
'regular_polygon',
|
||||
'circle_sector',
|
||||
'venn_diagram',
|
||||
'coordinate_axes'
|
||||
]
|
||||
for (const name of expectedNames) {
|
||||
expect(PRESET_GENERATORS.get(name)).toBeTypeOf('function')
|
||||
}
|
||||
})
|
||||
|
||||
it('should return undefined for an unknown preset name', () => {
|
||||
expect(PRESET_GENERATORS.get('inexistant')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -1,134 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildCircleSector } from '../../src/main/coach/presets/circleSector'
|
||||
import { buildCoordinateAxes } from '../../src/main/coach/presets/coordinateAxes'
|
||||
import { buildRegularPolygon } from '../../src/main/coach/presets/regularPolygon'
|
||||
import { buildRightTriangle } from '../../src/main/coach/presets/rightTriangle'
|
||||
import { buildTriangle } from '../../src/main/coach/presets/triangle'
|
||||
import { buildVennDiagram } from '../../src/main/coach/presets/vennDiagram'
|
||||
|
||||
describe('buildCircleSector()', () => {
|
||||
it('should return one arc shape per slice, with angles summing to 360 degrees', () => {
|
||||
const shapes = buildCircleSector({
|
||||
slices: [
|
||||
{ value: 50, label: 'A' },
|
||||
{ value: 50, label: 'B' }
|
||||
]
|
||||
})
|
||||
expect(shapes).toHaveLength(2)
|
||||
expect(shapes[0]?.startAngle).toBe(-90)
|
||||
expect(shapes[1]?.endAngle).toBe(270)
|
||||
})
|
||||
|
||||
it('should ignore slices with a zero or negative value', () => {
|
||||
const shapes = buildCircleSector({ slices: [{ value: 0 }, { value: -5 }, { value: 10 }] })
|
||||
expect(shapes).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('should return an empty array when there are no valid slices', () => {
|
||||
expect(buildCircleSector({ slices: [] })).toEqual([])
|
||||
expect(buildCircleSector({})).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildCoordinateAxes()', () => {
|
||||
it('should always return the two perpendicular axis arrows plus axis labels', () => {
|
||||
const shapes = buildCoordinateAxes({})
|
||||
const arrows = shapes.filter((s) => s.type === 'arrow')
|
||||
expect(arrows).toHaveLength(2)
|
||||
expect(arrows[0]?.y).toBe(arrows[0]?.y2)
|
||||
expect(arrows[1]?.x).toBe(arrows[1]?.x2)
|
||||
})
|
||||
|
||||
it('should add a circle for each valid point provided', () => {
|
||||
const shapes = buildCoordinateAxes({
|
||||
points: [
|
||||
{ x: 1, y: 2, label: 'P' },
|
||||
{ x: 3, y: 4 }
|
||||
]
|
||||
})
|
||||
const circles = shapes.filter((s) => s.type === 'circle')
|
||||
expect(circles).toHaveLength(2)
|
||||
expect(circles[0]?.label).toBe('P')
|
||||
})
|
||||
|
||||
it('should ignore non-object entries in the points array', () => {
|
||||
const shapes = buildCoordinateAxes({ points: [null, 'invalid', { x: 1, y: 1 }] })
|
||||
expect(shapes.filter((s) => s.type === 'circle')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildRegularPolygon()', () => {
|
||||
it('should return exactly as many line segments as sides requested', () => {
|
||||
const shapes = buildRegularPolygon({ sides: 5 })
|
||||
expect(shapes).toHaveLength(5)
|
||||
expect(shapes.every((s) => s.type === 'line')).toBe(true)
|
||||
})
|
||||
|
||||
it('should clamp the number of sides between 3 and 12', () => {
|
||||
expect(buildRegularPolygon({ sides: 1 })).toHaveLength(3)
|
||||
expect(buildRegularPolygon({ sides: 100 })).toHaveLength(12)
|
||||
})
|
||||
|
||||
it('should attach the provided labels/captions by index', () => {
|
||||
const shapes = buildRegularPolygon({ sides: 3, labels: ['a', 'b', 'c'] })
|
||||
expect(shapes.map((s) => s.label)).toEqual(['a', 'b', 'c'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildRightTriangle()', () => {
|
||||
it('should return the three sides, the right-angle marker and the angle arc', () => {
|
||||
const shapes = buildRightTriangle({})
|
||||
expect(shapes.filter((s) => s.type === 'line')).toHaveLength(3)
|
||||
expect(shapes.some((s) => s.type === 'rect')).toBe(true)
|
||||
expect(shapes.some((s) => s.type === 'arc')).toBe(true)
|
||||
})
|
||||
|
||||
it('should use the default labels when none are provided', () => {
|
||||
const shapes = buildRightTriangle({})
|
||||
const labels = shapes.map((s) => s.label)
|
||||
expect(labels).toContain('Adjacent')
|
||||
expect(labels).toContain('Opposé')
|
||||
expect(labels).toContain('Hypoténuse')
|
||||
})
|
||||
|
||||
it('should use custom labels when provided', () => {
|
||||
const shapes = buildRightTriangle({ adjacentLabel: 'Cote A' })
|
||||
expect(shapes.some((s) => s.label === 'Cote A')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildTriangle()', () => {
|
||||
it('should return the three sides of the triangle', () => {
|
||||
const shapes = buildTriangle({})
|
||||
expect(shapes.filter((s) => s.type === 'line')).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('should include an apex text label when apexLabel is provided', () => {
|
||||
const shapes = buildTriangle({ apexLabel: 'A' })
|
||||
expect(shapes.some((s) => s.type === 'text' && s.content === 'A')).toBe(true)
|
||||
})
|
||||
|
||||
it('should omit the apex text shape when no apexLabel is provided', () => {
|
||||
const shapes = buildTriangle({})
|
||||
expect(shapes.some((s) => s.type === 'text')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildVennDiagram()', () => {
|
||||
it('should return 2 circles by default', () => {
|
||||
const shapes = buildVennDiagram({})
|
||||
expect(shapes).toHaveLength(2)
|
||||
expect(shapes.every((s) => s.type === 'circle')).toBe(true)
|
||||
})
|
||||
|
||||
it('should return 3 circles when 3 labels are given', () => {
|
||||
const shapes = buildVennDiagram({ labels: ['A', 'B', 'C'] })
|
||||
expect(shapes).toHaveLength(3)
|
||||
expect(shapes.map((s) => s.label)).toEqual(['A', 'B', 'C'])
|
||||
})
|
||||
|
||||
it('should clamp to at most 3 circles even with more labels', () => {
|
||||
const shapes = buildVennDiagram({ labels: ['A', 'B', 'C', 'D', 'E'] })
|
||||
expect(shapes).toHaveLength(3)
|
||||
})
|
||||
})
|
||||
@@ -1,45 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { num, str, strOrUndefined } from '../../src/main/coach/presets/utils'
|
||||
|
||||
describe('num()', () => {
|
||||
it('should parse a numeric value within range', () => {
|
||||
expect(num(5, 0, 0, 10)).toBe(5)
|
||||
})
|
||||
|
||||
it('should return the fallback for a non-finite value', () => {
|
||||
expect(num('abc', 42)).toBe(42)
|
||||
expect(num(undefined, 42)).toBe(42)
|
||||
expect(num(NaN, 42)).toBe(42)
|
||||
})
|
||||
|
||||
it('should clamp a value above the max', () => {
|
||||
expect(num(100, 0, 0, 10)).toBe(10)
|
||||
})
|
||||
|
||||
it('should clamp a value below the min', () => {
|
||||
expect(num(-100, 0, 0, 10)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('str()', () => {
|
||||
it('should return the trimmed string when given a non-empty string', () => {
|
||||
expect(str(' hello ')).toBe('hello')
|
||||
})
|
||||
|
||||
it('should return the fallback for a non-string or blank value', () => {
|
||||
expect(str(42)).toBe('')
|
||||
expect(str(' ')).toBe('')
|
||||
expect(str(undefined, 'defaut')).toBe('defaut')
|
||||
})
|
||||
})
|
||||
|
||||
describe('strOrUndefined()', () => {
|
||||
it('should return the trimmed string when given a non-empty string', () => {
|
||||
expect(strOrUndefined(' hello ')).toBe('hello')
|
||||
})
|
||||
|
||||
it('should return undefined for a non-string or blank value', () => {
|
||||
expect(strOrUndefined(42)).toBeUndefined()
|
||||
expect(strOrUndefined(' ')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -1,87 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { EventEmitter } from 'node:events'
|
||||
|
||||
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
|
||||
|
||||
class FakeWebContents extends EventEmitter {
|
||||
send = vi.fn()
|
||||
isLoading = vi.fn(() => false)
|
||||
}
|
||||
|
||||
class FakeBrowserWindow extends EventEmitter {
|
||||
webContents = new FakeWebContents()
|
||||
show = vi.fn()
|
||||
moveTop = vi.fn()
|
||||
focus = vi.fn()
|
||||
setAlwaysOnTop = vi.fn()
|
||||
maximize = vi.fn()
|
||||
loadURL = vi.fn()
|
||||
loadFile = vi.fn()
|
||||
destroyed = false
|
||||
isDestroyed(): boolean {
|
||||
return this.destroyed
|
||||
}
|
||||
}
|
||||
|
||||
let lastWindow: FakeBrowserWindow | null = null
|
||||
let nextWindowStartsLoading = false
|
||||
function createBrowserWindow(): FakeBrowserWindow {
|
||||
const window = new FakeBrowserWindow()
|
||||
if (nextWindowStartsLoading) {
|
||||
window.webContents.isLoading.mockReturnValue(true)
|
||||
nextWindowStartsLoading = false
|
||||
}
|
||||
lastWindow = window
|
||||
return window
|
||||
}
|
||||
|
||||
vi.mock('electron', () => ({ BrowserWindow: vi.fn(createBrowserWindow) }))
|
||||
|
||||
const { openCoachProgressWindow } = await import('../../src/main/coach/progressWindow')
|
||||
|
||||
describe('openCoachProgressWindow()', () => {
|
||||
beforeEach(() => {
|
||||
lastWindow?.emit('closed')
|
||||
vi.clearAllMocks()
|
||||
lastWindow = null
|
||||
})
|
||||
|
||||
it('should create and maximize a new window', () => {
|
||||
openCoachProgressWindow()
|
||||
expect(lastWindow?.maximize).toHaveBeenCalled()
|
||||
expect(lastWindow?.setAlwaysOnTop).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should reuse and re-show the existing window on a second call', () => {
|
||||
openCoachProgressWindow()
|
||||
const firstWindow = lastWindow
|
||||
openCoachProgressWindow()
|
||||
expect(lastWindow).toBe(firstWindow)
|
||||
expect(firstWindow?.show).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should send navigate-to-module immediately when the page is already loaded', () => {
|
||||
openCoachProgressWindow({ subject: 'algebre', module: 'Fractions' })
|
||||
expect(lastWindow?.webContents.send).toHaveBeenCalledWith('navigate-to-module', {
|
||||
subject: 'algebre',
|
||||
module: 'Fractions'
|
||||
})
|
||||
})
|
||||
|
||||
it('should wait for did-finish-load before navigating when the page is still loading', () => {
|
||||
nextWindowStartsLoading = true
|
||||
openCoachProgressWindow({ subject: 'algebre', module: 'Fractions' })
|
||||
expect(lastWindow?.webContents.send).not.toHaveBeenCalled()
|
||||
lastWindow?.webContents.emit('did-finish-load')
|
||||
expect(lastWindow?.webContents.send).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should navigate on an already-open window reused for a second target', () => {
|
||||
openCoachProgressWindow()
|
||||
openCoachProgressWindow({ subject: 'geometrie', module: 'Triangles' })
|
||||
expect(lastWindow?.webContents.send).toHaveBeenCalledWith('navigate-to-module', {
|
||||
subject: 'geometrie',
|
||||
module: 'Triangles'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,54 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const NotificationShow = vi.fn()
|
||||
class NotificationMock {
|
||||
show = NotificationShow
|
||||
constructor(public options: { title: string; body: string }) {}
|
||||
}
|
||||
vi.mock('electron', () => ({ Notification: NotificationMock }))
|
||||
|
||||
const synthesizeSpeech = vi.fn(async () => Buffer.from([1, 2, 3]))
|
||||
vi.mock('../../src/main/ai/elevenlabs', () => ({ synthesizeSpeech }))
|
||||
|
||||
const sendToRenderer = vi.fn()
|
||||
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer }))
|
||||
|
||||
interface DueReview {
|
||||
conceptId: number
|
||||
subject: string
|
||||
concept: string
|
||||
}
|
||||
const getDueReviews = vi.fn((): DueReview[] => [])
|
||||
const markReminded = vi.fn()
|
||||
vi.mock('../../src/main/coach/coachStore', () => ({ getDueReviews, markReminded }))
|
||||
|
||||
const { startReviewScheduler } = await import('../../src/main/coach/reviewScheduler')
|
||||
|
||||
describe('startReviewScheduler()', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
it('should not notify anything when no review is due', async () => {
|
||||
getDueReviews.mockReturnValue([])
|
||||
startReviewScheduler()
|
||||
await vi.advanceTimersByTimeAsync(5 * 60 * 1000)
|
||||
expect(NotificationShow).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should show a notification, speak and mark reviews as reminded when due', async () => {
|
||||
getDueReviews.mockReturnValue([
|
||||
{ conceptId: 1, subject: 'algebre', concept: 'equations' },
|
||||
{ conceptId: 2, subject: 'algebre', concept: 'fractions' }
|
||||
])
|
||||
startReviewScheduler()
|
||||
await vi.advanceTimersByTimeAsync(5 * 60 * 1000)
|
||||
expect(NotificationShow).toHaveBeenCalled()
|
||||
expect(sendToRenderer).toHaveBeenCalledWith('proactive-speech', expect.anything())
|
||||
expect(markReminded).toHaveBeenCalledWith(1)
|
||||
expect(markReminded).toHaveBeenCalledWith(2)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
@@ -1,246 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-askexercise-test-'))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tempDir }
|
||||
}))
|
||||
|
||||
const requestWrittenAnswers = vi.fn(
|
||||
async (items: { question: string }[]): Promise<(string | null)[]> =>
|
||||
items.map(() => 'une reponse')
|
||||
)
|
||||
vi.mock('../../src/main/coach/exerciseWindow', () => ({ requestWrittenAnswers }))
|
||||
|
||||
const {
|
||||
setResearchSummary,
|
||||
createModules,
|
||||
setModuleTheory,
|
||||
setSubjectLevel,
|
||||
upsertConceptStatus,
|
||||
getModuleOrderIndex,
|
||||
unlockNextModule
|
||||
} = await import('../../src/main/coach/coachStore')
|
||||
const { askWrittenExercise } = await import('../../src/main/skills/coach/askWrittenExercise')
|
||||
|
||||
const VALID_CONTENT = [
|
||||
'Accroche',
|
||||
'Un vendeur doit calculer rapidement combien de tissu acheter pour un mur triangulaire. '.repeat(
|
||||
16
|
||||
),
|
||||
'Developpement theorique',
|
||||
'Idee centrale, analogie, definition formelle, exemple resolu et contre-exemple. '.repeat(35),
|
||||
'Phase guidee',
|
||||
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier.',
|
||||
'Exercices progressifs',
|
||||
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
|
||||
'Exercice de debogage',
|
||||
"Trouve l'erreur dans ce calcul errone et corrige-la.",
|
||||
'Synthese',
|
||||
'Resume final avec question de meta-cognition et test Feynman. '.repeat(15)
|
||||
].join('\n\n')
|
||||
|
||||
describe('ask_written_exercise — kind="initial"', () => {
|
||||
const subject = 'geographie-initial-test'
|
||||
|
||||
it('should refuse missing questions array', async () => {
|
||||
await expect(
|
||||
askWrittenExercise.execute({ subject, kind: 'initial', questions: [] })
|
||||
).rejects.toThrow(/questions manquantes/)
|
||||
})
|
||||
|
||||
it('should refuse when no course plan exists yet', async () => {
|
||||
await expect(
|
||||
askWrittenExercise.execute({
|
||||
subject,
|
||||
kind: 'initial',
|
||||
questions: [{ question: 'Q ?', type: 'free_text', concept: 'Module A' }]
|
||||
})
|
||||
).rejects.toThrow(/Aucun plan de cours ecrit/)
|
||||
})
|
||||
|
||||
it('should refuse when module content is missing', async () => {
|
||||
setResearchSummary(subject, JSON.stringify({ sources: [] }))
|
||||
createModules(subject, [{ name: 'Module A' }, { name: 'Module B' }])
|
||||
const { setSubjectObjective } = await import('../../src/main/coach/coachStore')
|
||||
setSubjectObjective(subject, 'Tu seras capable de situer un pays sur une carte')
|
||||
await expect(
|
||||
askWrittenExercise.execute({
|
||||
subject,
|
||||
kind: 'initial',
|
||||
questions: [
|
||||
{ question: 'Q A ?', type: 'free_text', concept: 'Module A' },
|
||||
{ question: 'Q B ?', type: 'free_text', concept: 'Module B' }
|
||||
]
|
||||
})
|
||||
).rejects.toThrow(/contenu de certains modules/)
|
||||
})
|
||||
|
||||
it('should refuse when question coverage does not exactly match the modules', async () => {
|
||||
setModuleTheory(subject, 'Module A', VALID_CONTENT)
|
||||
setModuleTheory(subject, 'Module B', VALID_CONTENT)
|
||||
await expect(
|
||||
askWrittenExercise.execute({
|
||||
subject,
|
||||
kind: 'initial',
|
||||
questions: [{ question: 'Q A ?', type: 'free_text', concept: 'Module A' }]
|
||||
})
|
||||
).rejects.toThrow(/Modules non couverts/)
|
||||
})
|
||||
|
||||
it('should refuse a concept not matching any real module', async () => {
|
||||
await expect(
|
||||
askWrittenExercise.execute({
|
||||
subject,
|
||||
kind: 'initial',
|
||||
questions: [
|
||||
{ question: 'Q ?', type: 'free_text', concept: 'Module A' },
|
||||
{ question: 'Q2 ?', type: 'free_text', concept: 'Module Fantome' }
|
||||
]
|
||||
})
|
||||
).rejects.toThrow(/Concepts invalides/)
|
||||
})
|
||||
|
||||
it('should accept exactly one question per module and save the assessments', async () => {
|
||||
const result = await askWrittenExercise.execute({
|
||||
subject,
|
||||
kind: 'initial',
|
||||
questions: [
|
||||
{ question: 'Q A ?', type: 'free_text', concept: 'Module A' },
|
||||
{ question: 'Q B ?', type: 'free_text', concept: 'Module B' }
|
||||
]
|
||||
})
|
||||
expect(result).toMatch(/Formulaire soumis/)
|
||||
})
|
||||
|
||||
it('should refuse a second initial evaluation once the level is already recorded', async () => {
|
||||
setSubjectLevel(subject, 'debutant')
|
||||
await expect(
|
||||
askWrittenExercise.execute({
|
||||
subject,
|
||||
kind: 'initial',
|
||||
questions: [{ question: 'Q ?', type: 'free_text', concept: 'Module A' }]
|
||||
})
|
||||
).rejects.toThrow(/deja enregistre/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ask_written_exercise — kind="final"', () => {
|
||||
const subject = 'final-test'
|
||||
|
||||
it('should refuse when not all modules are acquired yet', async () => {
|
||||
createModules(subject, [{ name: 'Seul module' }])
|
||||
await expect(
|
||||
askWrittenExercise.execute({
|
||||
subject,
|
||||
kind: 'final',
|
||||
questions: [{ question: 'Q finale ?', type: 'free_text', difficulty: 'difficile' }]
|
||||
})
|
||||
).rejects.toThrow(/ne sont pas encore valides/)
|
||||
})
|
||||
|
||||
it('should refuse a final evaluation with no demanding question', async () => {
|
||||
const orderIndex = getModuleOrderIndex(subject, 'Seul module')
|
||||
upsertConceptStatus(subject, 'Seul module', 'acquired')
|
||||
if (orderIndex !== null) unlockNextModule(subject, orderIndex)
|
||||
await expect(
|
||||
askWrittenExercise.execute({
|
||||
subject,
|
||||
kind: 'final',
|
||||
questions: [{ question: 'Q facile ?', type: 'free_text', difficulty: 'facile' }]
|
||||
})
|
||||
).rejects.toThrow(/exigeante/)
|
||||
})
|
||||
|
||||
it('should accept a final evaluation with at least one demanding question', async () => {
|
||||
const result = await askWrittenExercise.execute({
|
||||
subject,
|
||||
kind: 'final',
|
||||
questions: [{ question: 'Q difficile ?', type: 'free_text', difficulty: 'difficile' }]
|
||||
})
|
||||
expect(result).toMatch(/Formulaire soumis/)
|
||||
})
|
||||
|
||||
it('should also accept a demanding exerciseStyle without difficulty="difficile"', async () => {
|
||||
const result = await askWrittenExercise.execute({
|
||||
subject,
|
||||
kind: 'final',
|
||||
questions: [{ question: 'Projet ?', type: 'free_text', exerciseStyle: 'projet' }]
|
||||
})
|
||||
expect(result).toMatch(/Formulaire soumis/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ask_written_exercise — validation generale', () => {
|
||||
it('should refuse an invalid kind', async () => {
|
||||
await expect(
|
||||
askWrittenExercise.execute({
|
||||
subject: 'autre-sujet',
|
||||
kind: 'invalide',
|
||||
questions: [{ question: 'Q ?', type: 'free_text' }]
|
||||
})
|
||||
).rejects.toThrow(/kind invalide/)
|
||||
})
|
||||
|
||||
it('should refuse a multiple_choice question without enough options', async () => {
|
||||
await expect(
|
||||
askWrittenExercise.execute({
|
||||
subject: 'autre-sujet',
|
||||
kind: 'module',
|
||||
questions: [{ question: 'Q ?', type: 'multiple_choice', options: ['A'] }]
|
||||
})
|
||||
).rejects.toThrow(/options manquantes/)
|
||||
})
|
||||
|
||||
it('should refuse an invalid difficulty value', async () => {
|
||||
await expect(
|
||||
askWrittenExercise.execute({
|
||||
subject: 'autre-sujet',
|
||||
kind: 'module',
|
||||
questions: [{ question: 'Q ?', type: 'free_text', difficulty: 'impossible' }]
|
||||
})
|
||||
).rejects.toThrow(/difficulty invalide/)
|
||||
})
|
||||
|
||||
it('should refuse an invalid exerciseStyle value', async () => {
|
||||
await expect(
|
||||
askWrittenExercise.execute({
|
||||
subject: 'autre-sujet',
|
||||
kind: 'module',
|
||||
questions: [{ question: 'Q ?', type: 'free_text', exerciseStyle: 'inexistant' }]
|
||||
})
|
||||
).rejects.toThrow(/exerciseStyle invalide/)
|
||||
})
|
||||
|
||||
it('should normalize an accented exerciseStyle value', async () => {
|
||||
const result = await askWrittenExercise.execute({
|
||||
subject: 'autre-sujet',
|
||||
kind: 'module',
|
||||
questions: [{ question: 'Q ?', type: 'free_text', exerciseStyle: 'problème_ouvert' }]
|
||||
})
|
||||
expect(result).toMatch(/Formulaire soumis/)
|
||||
})
|
||||
|
||||
it('should record a "dont know" answer distinctly from a real answer', async () => {
|
||||
requestWrittenAnswers.mockResolvedValueOnce(['Je ne sais pas'])
|
||||
const result = await askWrittenExercise.execute({
|
||||
subject: 'autre-sujet',
|
||||
kind: 'module',
|
||||
questions: [{ question: 'Q ?', type: 'free_text' }]
|
||||
})
|
||||
expect(result).toMatch(/lacune enregistree/)
|
||||
})
|
||||
|
||||
it('should report a missing answer when the window closes without one', async () => {
|
||||
requestWrittenAnswers.mockResolvedValueOnce([null])
|
||||
const result = await askWrittenExercise.execute({
|
||||
subject: 'autre-sujet',
|
||||
kind: 'module',
|
||||
questions: [{ question: 'Q ?', type: 'free_text' }]
|
||||
})
|
||||
expect(result).toMatch(/pas de reponse/)
|
||||
})
|
||||
})
|
||||
@@ -1,182 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-skills-misc-test-'))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tempDir }
|
||||
}))
|
||||
|
||||
const openCoachProgressWindow = vi.fn()
|
||||
vi.mock('../../src/main/coach/progressWindow', () => ({ openCoachProgressWindow }))
|
||||
|
||||
const {
|
||||
setResearchSummary,
|
||||
createModules,
|
||||
setModuleTheory,
|
||||
saveAssessment,
|
||||
unlockNextModule,
|
||||
upsertConceptStatus,
|
||||
getModuleOrderIndex
|
||||
} = await import('../../src/main/coach/coachStore')
|
||||
const { recordSubjectLevel } = await import('../../src/main/skills/coach/recordSubjectLevel')
|
||||
const { trackConceptMastery } = await import('../../src/main/skills/coach/trackConceptMastery')
|
||||
const { completeSubject } = await import('../../src/main/skills/coach/completeSubject')
|
||||
const { openModuleForUser } = await import('../../src/main/skills/coach/openModuleForUser')
|
||||
const { getCoursePlan } = await import('../../src/main/skills/coach/getCoursePlan')
|
||||
|
||||
const VALID_CONTENT = [
|
||||
'Accroche',
|
||||
'Un vendeur doit calculer rapidement combien de tissu acheter pour un mur triangulaire. '.repeat(
|
||||
16
|
||||
),
|
||||
'Developpement theorique',
|
||||
'Idee centrale, analogie, definition formelle, exemple resolu et contre-exemple. '.repeat(35),
|
||||
'Phase guidee',
|
||||
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier.',
|
||||
'Exercices progressifs',
|
||||
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
|
||||
'Exercice de debogage',
|
||||
"Trouve l'erreur dans ce calcul errone et corrige-la.",
|
||||
'Synthese',
|
||||
'Resume final avec question de meta-cognition et test Feynman. '.repeat(15)
|
||||
].join('\n\n')
|
||||
|
||||
describe('record_subject_level', () => {
|
||||
const subject = 'chimie-test'
|
||||
|
||||
it('should refuse when no assessment exists yet for the subject', async () => {
|
||||
await expect(recordSubjectLevel.execute({ subject, level: 'debutant' })).rejects.toThrow(
|
||||
/Aucune evaluation/
|
||||
)
|
||||
})
|
||||
|
||||
it('should record the level once an assessment exists', async () => {
|
||||
saveAssessment(subject, null, 'Q ?', 'free_text', null, 'R', 'initial', false, null, null, null)
|
||||
const result = await recordSubjectLevel.execute({ subject, level: 'debutant' })
|
||||
expect(result).toMatch(/debutant/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('track_concept_mastery', () => {
|
||||
const subject = 'physique-test'
|
||||
const concept = 'Loi d-ohm'
|
||||
|
||||
it('should allow a progress-only status without any assessment', async () => {
|
||||
const result = await trackConceptMastery.execute({ subject, concept, status: 'in_progress' })
|
||||
expect(result).toMatch(/in_progress/)
|
||||
})
|
||||
|
||||
it('should refuse an evaluative status ("acquired") without a prior assessment', async () => {
|
||||
await expect(
|
||||
trackConceptMastery.execute({ subject, concept, status: 'acquired' })
|
||||
).rejects.toThrow(/Aucune evaluation/)
|
||||
})
|
||||
|
||||
it('should accept an evaluative status once an assessment exists for that concept', async () => {
|
||||
saveAssessment(
|
||||
subject,
|
||||
concept,
|
||||
'Q ?',
|
||||
'free_text',
|
||||
null,
|
||||
'R',
|
||||
'module',
|
||||
false,
|
||||
null,
|
||||
null,
|
||||
null
|
||||
)
|
||||
const result = await trackConceptMastery.execute({ subject, concept, status: 'acquired' })
|
||||
expect(result).toMatch(/acquired/)
|
||||
})
|
||||
|
||||
it('should reject an invalid status value', async () => {
|
||||
await expect(
|
||||
trackConceptMastery.execute({ subject, concept, status: 'invalide' })
|
||||
).rejects.toThrow(/status invalide/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('open_module_for_user', () => {
|
||||
const subject = 'histoire-test'
|
||||
|
||||
it('should throw when the module does not exist', async () => {
|
||||
await expect(openModuleForUser.execute({ subject, module: 'Module fantome' })).rejects.toThrow(
|
||||
/introuvable/
|
||||
)
|
||||
})
|
||||
|
||||
it('should refuse to open a locked module', async () => {
|
||||
createModules(subject, [{ name: 'Module 1' }, { name: 'Module 2' }])
|
||||
await expect(openModuleForUser.execute({ subject, module: 'Module 2' })).rejects.toThrow(
|
||||
/verrouille/
|
||||
)
|
||||
})
|
||||
|
||||
it('should refuse to open a module whose content was never written', async () => {
|
||||
await expect(openModuleForUser.execute({ subject, module: 'Module 1' })).rejects.toThrow(
|
||||
/pas encore ecrit/
|
||||
)
|
||||
})
|
||||
|
||||
it('should open an unlocked module with written content', async () => {
|
||||
setModuleTheory(subject, 'Module 1', VALID_CONTENT)
|
||||
openCoachProgressWindow.mockClear()
|
||||
const result = await openModuleForUser.execute({ subject, module: 'Module 1' })
|
||||
expect(result).toMatch(/ouvert/)
|
||||
expect(openCoachProgressWindow).toHaveBeenCalledWith({ subject, module: 'Module 1' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('complete_subject', () => {
|
||||
const subject = 'biologie-test'
|
||||
|
||||
it('should refuse when modules are not all acquired yet', async () => {
|
||||
createModules(subject, [{ name: 'Seul module' }])
|
||||
await expect(completeSubject.execute({ subject })).rejects.toThrow(/pas encore valides/)
|
||||
})
|
||||
|
||||
it('should refuse when all modules are acquired but no final assessment exists', async () => {
|
||||
const orderIndex = getModuleOrderIndex(subject, 'Seul module')
|
||||
upsertConceptStatus(subject, 'Seul module', 'acquired')
|
||||
if (orderIndex !== null) unlockNextModule(subject, orderIndex)
|
||||
await expect(completeSubject.execute({ subject })).rejects.toThrow(/evaluation finale/)
|
||||
})
|
||||
|
||||
it('should mark the subject as mastered once modules are acquired and a final assessment exists', async () => {
|
||||
saveAssessment(
|
||||
subject,
|
||||
null,
|
||||
'Q finale ?',
|
||||
'free_text',
|
||||
null,
|
||||
'R',
|
||||
'final',
|
||||
false,
|
||||
'difficile',
|
||||
null,
|
||||
null
|
||||
)
|
||||
const result = await completeSubject.execute({ subject })
|
||||
expect(result).toMatch(/maitrise/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('get_course_plan', () => {
|
||||
it('should report no existing plan for a brand new subject', async () => {
|
||||
const result = await getCoursePlan.execute({ subject: 'sujet-jamais-vu-xyz' })
|
||||
expect(result).toMatch(/Aucun plan de cours/)
|
||||
})
|
||||
|
||||
it('should summarize research/module state for a subject already in progress', async () => {
|
||||
const subject = 'plan-existant-test'
|
||||
setResearchSummary(subject, JSON.stringify({ sources: [] }))
|
||||
createModules(subject, [{ name: 'Module unique' }])
|
||||
const result = await getCoursePlan.execute({ subject })
|
||||
expect(result).toMatch(/Recherche deja effectuee/)
|
||||
expect(result).toMatch(/Module unique/)
|
||||
})
|
||||
})
|
||||
@@ -1,130 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-skills-test-'))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tempDir }
|
||||
}))
|
||||
|
||||
vi.mock('../../src/main/coach/exerciseWindow', () => ({
|
||||
requestWrittenAnswers: vi.fn(async (items: { question: string }[]) =>
|
||||
items.map(() => 'une reponse')
|
||||
)
|
||||
}))
|
||||
|
||||
const { setResearchSummary } = await import('../../src/main/coach/coachStore')
|
||||
const { generateCoursePlan } = await import('../../src/main/skills/coach/generateCoursePlan')
|
||||
const { writeModuleContent } = await import('../../src/main/skills/coach/writeModuleContent')
|
||||
const { completeModule } = await import('../../src/main/skills/coach/completeModule')
|
||||
const { askWrittenExercise } = await import('../../src/main/skills/coach/askWrittenExercise')
|
||||
|
||||
const VALID_CONTENT = [
|
||||
'Accroche',
|
||||
'Un vendeur doit calculer rapidement combien de tissu acheter pour un mur triangulaire. '.repeat(
|
||||
16
|
||||
),
|
||||
'Developpement theorique',
|
||||
'Idee centrale, analogie, definition formelle, exemple resolu et contre-exemple. '.repeat(35),
|
||||
'Phase guidee',
|
||||
'ETAPE 1 : identifier les donnees. ETAPE 2 : appliquer la formule. ETAPE 3 : verifier.',
|
||||
'Exercices progressifs',
|
||||
'EXERCICE 1 facile. EXERCICE 2 facile. EXERCICE 3 moyen. EXERCICE 4 moyen. EXERCICE 5 difficile. EXERCICE 6 difficile.',
|
||||
'Exercice de debogage',
|
||||
"Trouve l'erreur dans ce calcul errone et corrige-la.",
|
||||
'Synthese',
|
||||
'Resume final avec question de meta-cognition et test Feynman. '.repeat(15)
|
||||
].join('\n\n')
|
||||
|
||||
const SUBJECT = 'trigonometrie-pipeline-test'
|
||||
|
||||
describe('generate_course_plan', () => {
|
||||
it('should refuse when no research exists yet for the subject', async () => {
|
||||
await expect(
|
||||
generateCoursePlan.execute({
|
||||
subject: 'sujet-jamais-recherche',
|
||||
objective: 'Tu seras capable de calculer un sinus dans un triangle rectangle',
|
||||
modules: [{ name: 'Module 1' }]
|
||||
})
|
||||
).rejects.toThrow(/Aucune recherche/)
|
||||
})
|
||||
|
||||
it('should refuse when the objective is missing', async () => {
|
||||
setResearchSummary(SUBJECT, JSON.stringify({ sources: [] }))
|
||||
await expect(
|
||||
generateCoursePlan.execute({ subject: SUBJECT, objective: '', modules: [{ name: 'A' }] })
|
||||
).rejects.toThrow(/objective manquant/)
|
||||
})
|
||||
|
||||
it('should create the course plan once research and objective are present', async () => {
|
||||
const result = await generateCoursePlan.execute({
|
||||
subject: SUBJECT,
|
||||
objective: 'Tu seras capable de calculer un sinus dans un triangle rectangle',
|
||||
modules: [{ name: 'Module A' }, { name: 'Module B' }]
|
||||
})
|
||||
expect(result).toMatch(/Module A/)
|
||||
expect(result).toMatch(/Module B/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('write_module_content', () => {
|
||||
it('should reject content missing required sections', async () => {
|
||||
await expect(
|
||||
writeModuleContent.execute({ subject: SUBJECT, module: 'Module A', content: 'Trop court.' })
|
||||
).rejects.toThrow(/Contenu invalide/)
|
||||
})
|
||||
|
||||
it('should accept well-structured content for the first (unlocked) module', async () => {
|
||||
const result = await writeModuleContent.execute({
|
||||
subject: SUBJECT,
|
||||
module: 'Module A',
|
||||
content: VALID_CONTENT
|
||||
})
|
||||
expect(result).toMatch(/enregistre/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('complete_module', () => {
|
||||
it('should refuse when no assessment exists yet for the module', async () => {
|
||||
await expect(completeModule.execute({ subject: SUBJECT, module: 'Module A' })).rejects.toThrow(
|
||||
/Aucune evaluation/
|
||||
)
|
||||
})
|
||||
|
||||
it('should refuse when only a single difficulty level was used', async () => {
|
||||
await askWrittenExercise.execute({
|
||||
subject: SUBJECT,
|
||||
kind: 'module',
|
||||
questions: [
|
||||
{
|
||||
question: 'Question facile ?',
|
||||
type: 'free_text',
|
||||
concept: 'Module A',
|
||||
difficulty: 'facile'
|
||||
}
|
||||
]
|
||||
})
|
||||
await expect(completeModule.execute({ subject: SUBJECT, module: 'Module A' })).rejects.toThrow(
|
||||
/niveau de difficulte/
|
||||
)
|
||||
})
|
||||
|
||||
it('should validate the module once at least two difficulty levels were used and answers were correct', async () => {
|
||||
await askWrittenExercise.execute({
|
||||
subject: SUBJECT,
|
||||
kind: 'module',
|
||||
questions: [
|
||||
{
|
||||
question: 'Question difficile ?',
|
||||
type: 'free_text',
|
||||
concept: 'Module A',
|
||||
difficulty: 'difficile'
|
||||
}
|
||||
]
|
||||
})
|
||||
const result = await completeModule.execute({ subject: SUBJECT, module: 'Module A' })
|
||||
expect(result).toMatch(/valide/)
|
||||
})
|
||||
})
|
||||
@@ -1,137 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-drawing-test-'))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tempDir }
|
||||
}))
|
||||
|
||||
const openDrawingWindow = vi.fn(async () => {})
|
||||
const revealShape = vi.fn(async () => {})
|
||||
const renderMermaid = vi.fn(async () => {})
|
||||
const playCaption = vi.fn(async () => {})
|
||||
vi.mock('../../src/main/coach/drawingWindow', () => ({
|
||||
openDrawingWindow,
|
||||
revealShape,
|
||||
renderMermaid,
|
||||
playCaption
|
||||
}))
|
||||
|
||||
const synthesizeSpeech = vi.fn(async () => Buffer.from('audio'))
|
||||
vi.mock('../../src/main/ai/elevenlabs', () => ({ synthesizeSpeech }))
|
||||
|
||||
const { getModuleDetail, createModules } = await import('../../src/main/coach/coachStore')
|
||||
const { drawSchema } = await import('../../src/main/skills/coach/drawSchema')
|
||||
const { drawFlowDiagram } = await import('../../src/main/skills/coach/drawFlowDiagram')
|
||||
|
||||
describe('draw_schema', () => {
|
||||
it('should refuse when no valid shape is given', async () => {
|
||||
await expect(drawSchema.execute({ title: 'Test', shapes: [] })).rejects.toThrow(
|
||||
/Aucune forme valide/
|
||||
)
|
||||
})
|
||||
|
||||
it('should refuse when no shape has a caption', async () => {
|
||||
await expect(
|
||||
drawSchema.execute({
|
||||
title: 'Test',
|
||||
shapes: [{ type: 'circle', x: 10, y: 10, radius: 5 }]
|
||||
})
|
||||
).rejects.toThrow(/Aucune caption/)
|
||||
})
|
||||
|
||||
it('should refuse an unknown preset name', async () => {
|
||||
await expect(
|
||||
drawSchema.execute({
|
||||
title: 'Test',
|
||||
shapes: [{ type: 'preset', preset: 'inexistant', caption: 'voila' }]
|
||||
})
|
||||
).rejects.toThrow(/Preset inconnu/)
|
||||
})
|
||||
|
||||
it('should draw a manual shape with a caption, calling the drawing window and speech synthesis', async () => {
|
||||
openDrawingWindow.mockClear()
|
||||
revealShape.mockClear()
|
||||
synthesizeSpeech.mockClear()
|
||||
const result = await drawSchema.execute({
|
||||
title: 'Mon dessin',
|
||||
shapes: [{ type: 'circle', x: 10, y: 10, radius: 5, caption: 'Voici un cercle' }]
|
||||
})
|
||||
expect(result).toMatch(/termine/)
|
||||
expect(openDrawingWindow).toHaveBeenCalledWith('Mon dessin', 700, 500)
|
||||
expect(synthesizeSpeech).toHaveBeenCalledWith('Voici un cercle')
|
||||
expect(revealShape).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should expand a geometry preset into real shapes', async () => {
|
||||
const result = await drawSchema.execute({
|
||||
title: 'Triangle',
|
||||
shapes: [
|
||||
{
|
||||
type: 'preset',
|
||||
preset: 'right_triangle',
|
||||
presetParams: { adjacentCaption: 'Le cote vertical' }
|
||||
}
|
||||
]
|
||||
})
|
||||
expect(result).toMatch(/termine/)
|
||||
})
|
||||
|
||||
it('should persist the drawing to the module when subject and module are both given', async () => {
|
||||
createModules('dessin-subject-test', [{ name: 'Module dessin' }])
|
||||
await drawSchema.execute({
|
||||
title: 'Sauvegarde',
|
||||
subject: 'dessin-subject-test',
|
||||
module: 'Module dessin',
|
||||
shapes: [{ type: 'circle', x: 1, y: 1, radius: 1, caption: 'un cercle' }]
|
||||
})
|
||||
const detail = getModuleDetail('dessin-subject-test', 'Module dessin')
|
||||
expect(detail?.diagrams).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('draw_flow_diagram', () => {
|
||||
it('should refuse missing mermaid code', async () => {
|
||||
await expect(
|
||||
drawFlowDiagram.execute({ title: 'Cycle', mermaid: '', captions: ['une etape'] })
|
||||
).rejects.toThrow(/mermaid manquant/)
|
||||
})
|
||||
|
||||
it('should refuse when no caption is provided', async () => {
|
||||
await expect(
|
||||
drawFlowDiagram.execute({ title: 'Cycle', mermaid: 'graph LR; A --> B', captions: [] })
|
||||
).rejects.toThrow(/Aucune caption/)
|
||||
})
|
||||
|
||||
it('should render the diagram and narrate each caption in sequence', async () => {
|
||||
renderMermaid.mockClear()
|
||||
playCaption.mockClear()
|
||||
const result = await drawFlowDiagram.execute({
|
||||
title: 'Cycle de l-eau',
|
||||
mermaid: 'graph LR; Evaporation --> Condensation',
|
||||
captions: ['Premiere etape', 'Deuxieme etape']
|
||||
})
|
||||
expect(result).toMatch(/affiche/)
|
||||
expect(renderMermaid).toHaveBeenCalledWith(
|
||||
'Cycle de l-eau',
|
||||
'graph LR; Evaporation --> Condensation'
|
||||
)
|
||||
expect(playCaption).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('should persist the diagram to the module when subject and module are both given', async () => {
|
||||
createModules('diagramme-subject-test', [{ name: 'Module diagramme' }])
|
||||
await drawFlowDiagram.execute({
|
||||
title: 'Sauvegarde',
|
||||
subject: 'diagramme-subject-test',
|
||||
module: 'Module diagramme',
|
||||
mermaid: 'graph LR; A --> B',
|
||||
captions: ['une etape']
|
||||
})
|
||||
const detail = getModuleDetail('diagramme-subject-test', 'Module diagramme')
|
||||
expect(detail?.diagrams).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -1,105 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-research-test-'))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tempDir }
|
||||
}))
|
||||
|
||||
const { getResearchSummary } = await import('../../src/main/coach/coachStore')
|
||||
const { researchTopic } = await import('../../src/main/skills/coach/researchTopic')
|
||||
|
||||
function buildSources(count: number, level = 1): { title: string; url: string; level: number }[] {
|
||||
return Array.from({ length: count }, (_, i) => ({
|
||||
title: `Source ${i + 1}`,
|
||||
url: `https://example.edu/source-${i + 1}`,
|
||||
level
|
||||
}))
|
||||
}
|
||||
|
||||
const BASE_ARGS = {
|
||||
subject: 'trigonometrie-recherche-test',
|
||||
subjectDomain: 'math_science',
|
||||
definition: 'La trigonometrie etudie les relations entre angles et longueurs.',
|
||||
usageToday: 'Utilisee en architecture, navigation, physique.',
|
||||
whyUsedToday: 'Permet de calculer des distances inaccessibles directement.',
|
||||
practicalCases: 'Calcul de la hauteur d-un batiment via son ombre.',
|
||||
application: 'Mesurer un angle puis appliquer sinus/cosinus/tangente.',
|
||||
prerequisites: 'Connaitre le theoreme de Pythagore et les triangles rectangles.',
|
||||
keyConcepts: ['sinus', 'cosinus', 'tangente', 'hypotenuse', 'angle'],
|
||||
commonErrors: [
|
||||
'confondre sinus et cosinus',
|
||||
'oublier de convertir en radians',
|
||||
'mauvais triangle de reference'
|
||||
],
|
||||
feynmanExplanation:
|
||||
'Imagine une echelle contre un mur : la trigonometrie dit comment l-angle change la hauteur atteinte.'
|
||||
}
|
||||
|
||||
describe('research_topic', () => {
|
||||
it('should reject an invalid subjectDomain', async () => {
|
||||
await expect(
|
||||
researchTopic.execute({
|
||||
...BASE_ARGS,
|
||||
subjectDomain: 'domaine-inconnu',
|
||||
sources: buildSources(5)
|
||||
})
|
||||
).rejects.toThrow(/subjectDomain invalide/)
|
||||
})
|
||||
|
||||
it('should reject a source with an invalid URL', async () => {
|
||||
await expect(
|
||||
researchTopic.execute({
|
||||
...BASE_ARGS,
|
||||
sources: [{ title: 'Source', url: 'pas-une-url', level: 1 }]
|
||||
})
|
||||
).rejects.toThrow(/URL valide/)
|
||||
})
|
||||
|
||||
it('should reject when fewer sources than the domain minimum are provided', async () => {
|
||||
await expect(researchTopic.execute({ ...BASE_ARGS, sources: buildSources(3) })).rejects.toThrow(
|
||||
/Au moins 5 sources/
|
||||
)
|
||||
})
|
||||
|
||||
it('should reject when every source is level 4 only', async () => {
|
||||
await expect(
|
||||
researchTopic.execute({ ...BASE_ARGS, sources: buildSources(5, 4) })
|
||||
).rejects.toThrow(/niveau 1, 2 ou 3/)
|
||||
})
|
||||
|
||||
it('should reject fewer than 5 key concepts', async () => {
|
||||
await expect(
|
||||
researchTopic.execute({ ...BASE_ARGS, sources: buildSources(5), keyConcepts: ['a', 'b'] })
|
||||
).rejects.toThrow(/keyConcepts/)
|
||||
})
|
||||
|
||||
it('should reject fewer than 3 common errors', async () => {
|
||||
await expect(
|
||||
researchTopic.execute({ ...BASE_ARGS, sources: buildSources(5), commonErrors: ['a'] })
|
||||
).rejects.toThrow(/commonErrors/)
|
||||
})
|
||||
|
||||
it('should require a higher minimum source count for medicine_law_finance', async () => {
|
||||
await expect(
|
||||
researchTopic.execute({
|
||||
...BASE_ARGS,
|
||||
subjectDomain: 'medicine_law_finance',
|
||||
sources: buildSources(5)
|
||||
})
|
||||
).rejects.toThrow(/Au moins 10 sources/)
|
||||
})
|
||||
|
||||
it('should accept a fully valid research payload and persist it', async () => {
|
||||
const result = await researchTopic.execute({ ...BASE_ARGS, sources: buildSources(5) })
|
||||
expect(result).toMatch(/enregistree/)
|
||||
const stored = getResearchSummary(BASE_ARGS.subject)
|
||||
expect(stored).not.toBeNull()
|
||||
const parsed = JSON.parse(stored ?? '{}') as { sources: unknown[]; subjectDomain: string }
|
||||
expect(parsed.sources).toHaveLength(5)
|
||||
expect(parsed.subjectDomain).toBe('math_science')
|
||||
})
|
||||
})
|
||||
@@ -5,14 +5,10 @@ import { join } from 'node:path'
|
||||
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-vision-meeting-test-'))
|
||||
|
||||
const getSources = vi.fn(async () => [{ thumbnail: { toPNG: () => Buffer.from([1, 2, 3]) } }])
|
||||
const requestCameraFrame = vi.fn(async () => 'data:image/png;base64,abc')
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tempDir },
|
||||
desktopCapturer: { getSources },
|
||||
screen: { getPrimaryDisplay: () => ({ size: { width: 1920, height: 1080 } }) }
|
||||
app: { getPath: () => tempDir }
|
||||
}))
|
||||
vi.mock('../../src/main/windowBridge', () => ({ requestCameraFrame, sendToRenderer: vi.fn() }))
|
||||
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer: vi.fn() }))
|
||||
|
||||
// pdf-parse/index.js execute du code de demo au chargement quand `module.parent` est absent (cas du
|
||||
// loader de Vitest), ce qui tente de lire un fichier de test inexistant : on le mocke entierement
|
||||
@@ -23,11 +19,6 @@ vi.mock('mammoth', () => ({
|
||||
default: { extractRawText: vi.fn(async () => ({ value: 'Texte extrait du docx' })) }
|
||||
}))
|
||||
|
||||
const analyzeImage = vi.fn(async (_dataUrl: string, question: string) => `Reponse a: ${question}`)
|
||||
vi.mock('../../src/main/ai/vision', () => ({ analyzeImage }))
|
||||
|
||||
const { analyzeScreen } = await import('../../src/main/skills/vision/analyzeScreen')
|
||||
const { watchCamera } = await import('../../src/main/skills/vision/watchCamera')
|
||||
const { searchWeb } = await import('../../src/main/skills/web/searchWeb')
|
||||
const { getLastMeetingSummarySkill } =
|
||||
await import('../../src/main/skills/meeting/getLastMeetingSummary')
|
||||
@@ -36,36 +27,6 @@ const { extractText } = await import('../../src/main/skills/documents/extractTex
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
getSources.mockResolvedValue([{ thumbnail: { toPNG: () => Buffer.from([1, 2, 3]) } }])
|
||||
requestCameraFrame.mockResolvedValue('data:image/png;base64,abc')
|
||||
analyzeImage.mockImplementation(
|
||||
async (_dataUrl: string, question: string) => `Reponse a: ${question}`
|
||||
)
|
||||
})
|
||||
|
||||
describe('analyze_screen', () => {
|
||||
it('should capture the screen and ask the vision model with a default question', async () => {
|
||||
const result = await analyzeScreen.execute({})
|
||||
expect(result).toMatch(/Decris ce que tu vois a l'ecran/)
|
||||
})
|
||||
|
||||
it('should throw when no screen source is detected', async () => {
|
||||
getSources.mockResolvedValueOnce([])
|
||||
await expect(analyzeScreen.execute({ question: 'test' })).rejects.toThrow(/Aucun ecran/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('watch_camera', () => {
|
||||
it('should request a camera frame and ask the vision model', async () => {
|
||||
const result = await watchCamera.execute({ question: "Qu'est-ce que c'est ?" })
|
||||
expect(result).toMatch(/Qu'est-ce que c'est/)
|
||||
expect(requestCameraFrame).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should use a default question when none is given', async () => {
|
||||
const result = await watchCamera.execute({})
|
||||
expect(result).toMatch(/Decris ce que tu vois/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('search_web', () => {
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { analyzeImage } from '../../src/main/ai/vision'
|
||||
|
||||
describe('analyzeImage()', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
process.env.OPENROUTER_API_KEY = 'test-key'
|
||||
})
|
||||
|
||||
it('should return the model answer when the API call succeeds', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({ choices: [{ message: { content: 'Une tasse de cafe sur un bureau.' } }] })
|
||||
} as Response)
|
||||
|
||||
const result = await analyzeImage('data:image/png;base64,abc', "Qu'est-ce que tu vois ?")
|
||||
expect(result).toBe('Une tasse de cafe sur un bureau.')
|
||||
})
|
||||
|
||||
it('should return a fallback message when the response has no content', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ choices: [{ message: {} }] })
|
||||
} as Response)
|
||||
|
||||
const result = await analyzeImage('data:image/png;base64,abc', 'Question ?')
|
||||
expect(result).toMatch(/n'ai pas reussi/)
|
||||
})
|
||||
|
||||
it('should throw a descriptive error when the API call fails', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: false,
|
||||
status: 429,
|
||||
text: () => Promise.resolve('Rate limited')
|
||||
} as Response)
|
||||
|
||||
await expect(analyzeImage('data:image/png;base64,abc', 'Question ?')).rejects.toThrow(
|
||||
/vision.*429/
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,59 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-visioncapture-test-'))
|
||||
|
||||
const getSources = vi.fn(async () => [{ thumbnail: { toPNG: () => Buffer.from([1, 2, 3]) } }])
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tempDir },
|
||||
desktopCapturer: { getSources },
|
||||
screen: { getPrimaryDisplay: () => ({ size: { width: 100, height: 100 } }) }
|
||||
}))
|
||||
|
||||
class WorkerMock {
|
||||
postMessage = vi.fn()
|
||||
on = vi.fn()
|
||||
}
|
||||
vi.mock('node:worker_threads', () => ({ Worker: WorkerMock }))
|
||||
|
||||
const { startVisionCapture, stopVisionCapture, getRecentCaptures } =
|
||||
await import('../../src/main/coach/visionCapture')
|
||||
|
||||
describe('visionCapture', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
it('should return an empty list of captures before any capture happens', () => {
|
||||
expect(getRecentCaptures(5)).toEqual([])
|
||||
})
|
||||
|
||||
it('should capture a screenshot on every tick once started', async () => {
|
||||
startVisionCapture()
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
expect(getSources).toHaveBeenCalled()
|
||||
stopVisionCapture()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should not start a second interval when already running', async () => {
|
||||
getSources.mockClear()
|
||||
startVisionCapture()
|
||||
startVisionCapture()
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
expect(getSources).toHaveBeenCalledTimes(1)
|
||||
stopVisionCapture()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('should stop capturing once stopped', async () => {
|
||||
getSources.mockClear()
|
||||
startVisionCapture()
|
||||
stopVisionCapture()
|
||||
await vi.advanceTimersByTimeAsync(5000)
|
||||
expect(getSources).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
@@ -1,13 +1,6 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
const ipcMainOn = vi.fn()
|
||||
const ipcMainRemoveListener = vi.fn()
|
||||
vi.mock('electron', () => ({
|
||||
ipcMain: { on: ipcMainOn, removeListener: ipcMainRemoveListener }
|
||||
}))
|
||||
|
||||
const { setMainWindow, sendToRenderer, requestCameraFrame } =
|
||||
await import('../../src/main/windowBridge')
|
||||
const { setMainWindow, sendToRenderer } = await import('../../src/main/windowBridge')
|
||||
|
||||
describe('sendToRenderer()', () => {
|
||||
it('should do nothing when no main window has been set', () => {
|
||||
@@ -21,68 +14,3 @@ describe('sendToRenderer()', () => {
|
||||
expect(send).toHaveBeenCalledWith('some-channel', 'a', 'b')
|
||||
})
|
||||
})
|
||||
|
||||
describe('requestCameraFrame()', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should reject immediately when no main window is available', async () => {
|
||||
setMainWindow(null as never)
|
||||
await expect(requestCameraFrame()).rejects.toThrow(/Fenetre indisponible/)
|
||||
})
|
||||
|
||||
it('should resolve with the data URL once the renderer responds for the matching request', async () => {
|
||||
const send = vi.fn()
|
||||
setMainWindow({ webContents: { send } } as never)
|
||||
|
||||
const promise = requestCameraFrame(1000)
|
||||
const requestId = send.mock.calls[0]?.[1] as string
|
||||
const handler = ipcMainOn.mock.calls.find((c) => c[0] === 'camera-frame-result')?.[1] as (
|
||||
event: unknown,
|
||||
id: string,
|
||||
dataUrl: string | null
|
||||
) => void
|
||||
|
||||
handler({}, requestId, 'data:image/png;base64,abc')
|
||||
await expect(promise).resolves.toBe('data:image/png;base64,abc')
|
||||
})
|
||||
|
||||
it('should reject when the renderer responds with null (camera unavailable)', async () => {
|
||||
const send = vi.fn()
|
||||
setMainWindow({ webContents: { send } } as never)
|
||||
|
||||
const promise = requestCameraFrame(1000)
|
||||
const requestId = send.mock.calls[0]?.[1] as string
|
||||
const handler = ipcMainOn.mock.calls.find((c) => c[0] === 'camera-frame-result')?.[1] as (
|
||||
event: unknown,
|
||||
id: string,
|
||||
dataUrl: string | null
|
||||
) => void
|
||||
|
||||
handler({}, requestId, null)
|
||||
await expect(promise).rejects.toThrow(/Impossible d'acceder a la camera/)
|
||||
})
|
||||
|
||||
it('should ignore a response for a different request id', async () => {
|
||||
const send = vi.fn()
|
||||
setMainWindow({ webContents: { send } } as never)
|
||||
|
||||
const promise = requestCameraFrame(1000)
|
||||
const handler = ipcMainOn.mock.calls.find((c) => c[0] === 'camera-frame-result')?.[1] as (
|
||||
event: unknown,
|
||||
id: string,
|
||||
dataUrl: string | null
|
||||
) => void
|
||||
|
||||
handler({}, 'un-autre-id', 'data:image/png;base64,ignore')
|
||||
const handlerAgain = ipcMainOn.mock.calls.find((c) => c[0] === 'camera-frame-result')?.[1] as (
|
||||
event: unknown,
|
||||
id: string,
|
||||
dataUrl: string | null
|
||||
) => void
|
||||
const requestId = send.mock.calls[0]?.[1] as string
|
||||
handlerAgain({}, requestId, 'data:image/png;base64,bon')
|
||||
await expect(promise).resolves.toBe('data:image/png;base64,bon')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user