import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { gameApi, useGame } from "../store.js";
import { explainDiagnostic } from "../training/diagnostics.js";
import { reviewC, narrateReview } from "../training/review.js";
import "./codeTraining.css";
import { syntaxHintAtNewline, syntaxHintWhileEditing } from "../training/syntaxHint.js";
import { SPEECH_LANGUAGES } from "../game/reachy/voiceProfile.js";
import { askReachyLocally, webGpuAvailable } from "../training/reachyHelp.js";
import { highlightC } from "../training/cSyntaxHighlight.js";
import { diagnosticRanges, parseClangDiagnostics, squiggleHtml } from "../training/liveDiagnostics.js";
import { EDITOR_FONTS, newlineEdit, wordRange, reindentC, tabEdit } from '../training/editorCommands.js';
import { createRaceProtocol } from "../training/raceProtocol.js";
import { createInteractionProtocol } from "../training/interactionProtocol.js";
import { INTERACTIVE_EXERCISES } from "./trainingExercises.jsx";
import { useExam } from '../training/useExam.js';
import { ExamPanel, ExamActions, ExamQuiz } from './ExamPanel.jsx';
import { asOwnEdit } from '../training/editProvenance.js';
import DebugPanel from './DebugPanel.jsx';
const STORAGE = "reachy-code-training-c";
const MICRODUCK_RACE = {
id: "microducks-race",
scene: true,
title: "Microduck's Race",
statement: {
en: <>
Write a C program to organise a race between 2 and 8 Microducks, numbered from 1 to N. Your program controls their target speeds and predicts the outcome, while the 3D simulation determines the actual winner.
1. Set up the race. Ask the user for the number of robots and a race distance between 1 and 5 metres. Check that both values are valid before configuring the race.
2. Start together. Set each runner's estimated distance to zero and choose a random target speed between 0.10 and 0.25 metres per second for each robot. Send all initial speeds to the simulator before giving a common start signal. The code window then minimises so you can watch the race.
3. Run the race. Keep the target speeds for 1 second, then choose new random speeds for every runner. Send each complete set so all runners change speed together. Between updates, let time pass and estimate each robot's progress from its speed and the elapsed time.
4. Predict the finish. Before each interval, estimate how long each robot still needs to reach the line. If one is expected to finish within the next second, shorten the duration used to calculate the estimated distances to the earliest predicted arrival. Still wait a full second with sleep(1), then update the estimated distances, send your predicted winner to the simulator and end your program.
Required simulator messages. Use these exact output formats, including the French keywords and the newline at the end of each message. You may choose your own variable names.
After validating the inputs (count: integer; distance: metres):{'printf("course %d distance %f\\n", count, distance);'}
For each runner, before the start and at every speed update (number: 1 to N; speed: metres per second):{'printf("microduck %d vitesse %f\\n", number, speed);'}
Once all N initial speeds have been sent, give the start signal once:{'printf("1,2,3,partez\\n");'}
At the predicted finish, send the predicted winner's number:{'printf("le vainqueur est microduck %d\\n", number);'}
Configuration and speed messages control the simulator; they are hidden from the terminal. The winner message remains a prediction; the simulation announces the actual winner.
>,
fr: <>
Écrivez un programme en C pour organiser une course entre 2 et 8 Microducks, numérotés de 1 à N. Votre programme commande leurs vitesses cibles et prévoit le résultat, tandis que la simulation 3D détermine le véritable vainqueur.
1. Préparer la course. Demandez à l’utilisateur le nombre de robots et une distance comprise entre 1 et 5 mètres. Vérifiez la validité des deux valeurs avant de configurer la course.
2. Donner un départ commun. Initialisez à zéro la distance estimée de chaque coureur et choisissez pour chacun une vitesse cible aléatoire entre 0,10 et 0,25 mètre par seconde. Transmettez toutes les vitesses initiales au simulateur avant de donner le signal de départ commun. La fenêtre de code se réduit alors pour vous laisser observer la course.
3. Faire progresser la course. Conservez les vitesses cibles pendant 1 seconde, puis tirez de nouvelles vitesses pour tous les coureurs. Transmettez chaque ensemble complet afin que tous changent de vitesse en même temps. Entre deux mises à jour, laissez le temps s’écouler et estimez la progression de chaque robot à partir de sa vitesse et de la durée écoulée.
4. Prévoir l’arrivée. Avant chaque intervalle, estimez le temps encore nécessaire à chaque robot pour atteindre la ligne. Si l’un d’eux doit arriver dans la prochaine seconde, raccourcissez la durée utilisée pour calculer les distances estimées jusqu’à la première arrivée prévue. Attendez tout de même une seconde entière avec sleep(1), puis mettez à jour les distances estimées, transmettez votre vainqueur prévu au simulateur et terminez votre programme.
Messages requis par le simulateur. Respectez exactement ces formats de sortie, y compris les mots-clés français et le retour à la ligne à la fin de chaque message. Vous pouvez choisir vos propres noms de variables.
Après validation des saisies (count : entier ; distance : mètres) :{'printf("course %d distance %f\\n", count, distance);'}
Pour chaque coureur, avant le départ et à chaque changement de vitesse (number : de 1 à N ; speed : mètres par seconde) :{'printf("microduck %d vitesse %f\\n", number, speed);'}
Une fois les N vitesses initiales transmises, donnez une seule fois le signal de départ :{'printf("1,2,3,partez\\n");'}
Au moment de l’arrivée prévue, transmettez le numéro du vainqueur prévu :{'printf("le vainqueur est microduck %d\\n", number);'}
Les messages de configuration et de vitesse pilotent le simulateur et sont masqués dans le terminal. Le message de victoire reste une prévision ; la simulation annonce le véritable gagnant.
>,
},
};
export default function CodeTraining({ onClose }) {
const [editorFont, setEditorFont] = useState(() => { try { const saved = localStorage.getItem('training-editor-font'); return EDITOR_FONTS[saved] ? saved : 'consolas'; } catch { return 'consolas'; } });
const [editorSize, setEditorSize] = useState(() => { try { const saved = Number(localStorage.getItem('training-editor-size')); return [12, 14, 16, 18, 20].includes(saved) ? saved : 14; } catch { return 14; } });
const [source, setSource] = useState(() => { try { return localStorage.getItem(STORAGE) ?? ""; } catch { return ""; } });
const [status, setStatus] = useState("Write, compile, then run your C program.");
const [phase, setPhase] = useState("idle");
const [debugMode, setDebugMode] = useState(false);
const debugAction = useRef(null);
const [debugPoint, setDebugPoint] = useState(null);
const [debugLines, setDebugLines] = useState([]);
const [watch, setWatch] = useState([]);
const [breakpoints, setBreakpoints] = useState([]);
const breakpointsRef = useRef([]);
const [editorScroll, setEditorScroll] = useState(0);
const [examToolsOpen, setExamToolsOpen] = useState(true);
const [compiledSource, setCompiledSource] = useState(null);
const [terminal, setTerminal] = useState("");
const [diagnostics, setDiagnostics] = useState("");
const [explanation, setExplanation] = useState("");
const [examHelpOpen, setExamHelpOpen] = useState(false);
const [input, setInput] = useState("");
const [compact, setCompact] = useState(false);
const [exerciseOpen, setExerciseOpen] = useState(false);
const [exercise, setExercise] = useState(null);
const [raceMinimized, setRaceMinimized] = useState(false);
const [raceLaunched, setRaceLaunched] = useState(false);
const [board, setBoard] = useState(null);
const exerciseRef = useRef(null);
const bootDone = useGame(s => s.bootDone);
const [show3d, setShow3d] = useState(true);
const [helpOpen, setHelpOpen] = useState(false);
const [helpQuestion, setHelpQuestion] = useState("");
const [helpAnswer, setHelpAnswer] = useState("");
const [helpStatus, setHelpStatus] = useState("");
const [helpBusy, setHelpBusy] = useState(false);
const [selectedWord, setSelectedWord] = useState("");
const [pendingFile, setPendingFile] = useState(null);
const [syntaxHint, setSyntaxHint] = useState(null);
const lastQuack = useRef(-Infinity);
const liveHintKey = useRef("");
const sourceField = useRef(null);
const exerciseOutput = useRef(null);
const [analysis, setAnalysis] = useState(null);
const language = useGame((s) => s.speechLanguage);
const personality = useGame((s) => s.speechPersonality);
const provider = useGame((s) => s.speechProvider);
const voice = useGame((s) => s.speech);
const supported = !!WebAssembly.Suspending && !!WebAssembly.promising;
const dialog = useRef(null), output = useRef(null), inputField = useRef(null), gutter = useRef(null), highlighter = useRef(null), squiggles = useRef(null), fileInput = useRef(null);
const lintWorker = useRef(null);
const [lintDiagnostics, setLintDiagnostics] = useState([]);
const [hoveredDiagnostic, setHoveredDiagnostic] = useState(null);
const session = useRef(null);
const exam = useExam({ source, language, replaceSource: value => {
stop(); setSource(value); setExercise(null); setExerciseOpen(false); setCompact(false);
setHelpOpen(false); setAnalysis(null); setDiagnostics(''); setExplanation(''); setTerminal('');
setPendingFile(null); setSyntaxHint(null); setSelectedWord('');
} });
const busy = ["compiling", "analyzing", "feedback", "running", "input", "paused"].includes(phase);
// Feedback speech is independent from the text area: learners can correct
// the source while Reachy is explaining the previous compilation.
const editorLocked = ["compiling", "analyzing", "running", "input", "paused"].includes(phase) || exam.working || (exam.active && !exam.selected);
const docked = !exam.active && !debugMode && (compact || (!exercise && ["running", "input"].includes(phase)));
const exerciseRunning = raceMinimized;
const isBoard = exercise?.id === 'tic-tac-toe';
const exerciseInput = !!exercise && exercise.id !== 'microducks-race' && raceMinimized;
debugAction.current = resumeDebug;
useEffect(() => { setExamToolsOpen(!exam.selected); }, [exam.selected?.id, exam.active]);
useEffect(() => {
if (!debugMode) return;
const key = event => {
const command = event.key === 'F5' ? 'continue' : event.key === 'F10' ? 'over' : event.key === 'F11' ? event.shiftKey ? 'out' : 'into' : null;
if (command) { event.preventDefault(); if (event.type === 'keydown' && !event.repeat) debugAction.current?.(command); }
};
window.addEventListener('keydown', key, true);
window.addEventListener('keyup', key, true);
return () => { window.removeEventListener('keydown', key, true); window.removeEventListener('keyup', key, true); };
}, [debugMode]);
useEffect(() => { setRaceLaunched(false); }, [exercise]);
useEffect(() => {
exerciseRef.current = exercise;
if (exam.active) return;
useGame.setState({ trainingExercise: !!exercise?.scene });
gameApi.setTrainingStageVisible?.(!exercise?.scene);
}, [exercise, bootDone, exam.active]);
useEffect(() => {
dialog.current.show();
document.body.classList.add("code-training-active");
useGame.setState({ codeTrainingOpen: true });
gameApi.enterCodeTraining?.();
return () => { document.body.classList.remove("code-training-active", "training-3d-off", "exam-active"); dispose(); gameApi.stopTrainingRace?.(); gameApi.leaveCodeTraining?.(); useGame.setState({ codeTrainingOpen: false, examActive: false }); };
}, []);
useEffect(() => {
document.body.classList.toggle("training-3d-off", exam.active || !show3d);
document.body.classList.toggle('exam-active', exam.active);
useGame.setState({ examActive: exam.active });
}, [show3d, exam.active]);
useEffect(() => {
try { localStorage.setItem('training-editor-font', editorFont); localStorage.setItem('training-editor-size', String(editorSize)); } catch { /* optional preference storage */ }
}, [editorFont, editorSize]);
const highlighted = useMemo(() => highlightC(source, selectedWord), [source, selectedWord]);
const lintRanges = useMemo(() => diagnosticRanges(source, lintDiagnostics), [source, lintDiagnostics]);
const squiggled = useMemo(() => squiggleHtml(source, lintRanges), [source, lintRanges]);
// Like an IDE, re-check the source with Clang shortly after typing stops.
useEffect(() => {
if (!supported || !source.trim()) { setLintDiagnostics([]); return; }
const timer = setTimeout(() => {
if (!lintWorker.current) {
lintWorker.current = new Worker(new URL("../training/lint.worker.js", import.meta.url), { type: "module" });
lintWorker.current.onmessage = ({ data }) => { if (!data.error) setLintDiagnostics(parseClangDiagnostics(data.diagnostics)); };
}
lintWorker.current.postMessage({ source, baseUrl: new URL(import.meta.env.BASE_URL, location.href).href });
}, 600);
return () => clearTimeout(timer);
}, [source, supported]);
useEffect(() => () => lintWorker.current?.terminate(), []);
useEffect(() => setHoveredDiagnostic(null), [lintRanges]);
useEffect(() => { if (!exam.active) try { localStorage.setItem(STORAGE, source); } catch { /* storage may be disabled */ } }, [source, exam.active]);
useEffect(() => {
for (const field of [output.current, exerciseOutput.current]) if (field) field.scrollTop = field.scrollHeight;
}, [terminal, raceMinimized]);
useEffect(() => { if (phase === "input") inputField.current?.focus(); }, [phase, raceMinimized]);
useEffect(() => {
if (editorLocked || exam.active) return;
const field = sourceField.current;
if (!field || document.activeElement !== field) return;
const hint = syntaxHintWhileEditing(source, field.selectionStart);
const key = hint ? `${hint.line}:${hint.message}` : "";
if (hint) {
setSyntaxHint(hint);
if (key !== liveHintKey.current) { lastQuack.current = performance.now(); gameApi.quack?.(); }
} else if (liveHintKey.current) setSyntaxHint(null);
liveHintKey.current = key;
}, [source, editorLocked]);
function dispose() {
const current = session.current;
session.current = null;
if (!current) return;
cancelInspections(current);
clearTimeout(current.timer);
current.voice.abort();
current.worker.terminate();
}
function stop(message = "Stopped. Compile again to start a fresh program.") {
setDebugPoint(null); setDebugMode(false); setDebugLines([]);
setRaceLaunched(false);
setBoard(null);
if (!exam.active) gameApi.stopTrainingRace?.(); setRaceMinimized(false);
dispose(); setPhase("idle"); setCompiledSource(null); setStatus(message);
}
function arm(current, milliseconds = 15000) {
clearTimeout(current.timer);
current.timer = setTimeout(() => {
if (session.current === current) stop("Time limit reached. Check for an infinite loop, or try compiling again.");
}, milliseconds);
}
const append = (text) => setTerminal((value) => (value + text).slice(-40000));
async function speak(current, flush = false) {
if (current.assessment || current.debug) { current.speech = ''; return; }
while (session.current === current && current.speech.length) {
const newline = current.speech.indexOf("\n");
if (!flush && newline < 0 && current.speech.length < 240) break;
const length = newline >= 0 ? Math.min(newline + 1, 240) : Math.min(current.speech.length, 240);
const text = current.speech.slice(0, length);
current.speech = current.speech.slice(length);
if (text.trim()) await gameApi.reachySay?.(text, { signal: current.voice.signal, language: current.language, personality: current.personality, provider: current.provider });
}
}
async function narrate(current, text) {
if (current.assessment) return;
// A speech-service failure must not destroy the compiler session or hide
// the diagnostics. Keep the last explanation available for a retry.
current.lastNarration = text;
try { await gameApi.reachySay?.(text, { signal: current.voice.signal, language: current.language, personality: current.personality, provider: current.provider, trainingFeedback: true }); }
catch (error) {
if (session.current === current && error.name !== "AbortError") append(`Voice: ${error.message}\n`);
}
}
function compile(operation = "compile", autoRun = false, debug = false) {
if (exam.active && operation === "analyze") return;
if (operation === "compile") { setCompiledSource(null); setTerminal(""); }
setAnalysis(null); setDiagnostics(""); setExplanation(""); setExamHelpOpen(false); setPhase(operation === "analyze" ? "analyzing" : "compiling");
setDebugMode(debug); setDebugPoint(null); setDebugLines([]);
const command = { type: operation, source, debug, breakpoints: breakpointsRef.current, baseUrl: new URL(import.meta.env.BASE_URL, location.href).href };
if (session.current) {
session.current.exercise = exerciseRef.current;
session.current.source = source;
session.current.language = language; session.current.personality = personality; session.current.provider = provider;
session.current.autoRun = autoRun;
session.current.debug = debug;
session.current.assessment = exam.active;
arm(session.current, 180000);
session.current.worker.postMessage(command);
return;
}
const worker = new Worker(new URL("../training/compiler.worker.js", import.meta.url), { type: "module" });
const current = { worker, voice: new AbortController(), speech: "", source, language, personality, provider, autoRun, debug, exercise: exerciseRef.current, assessment: exam.active };
session.current = current;
arm(current, 180000);
worker.onerror = (event) => { if (session.current === current) stop(`Compiler unavailable: ${event.message}`); };
worker.onmessage = async ({ data }) => {
if (session.current !== current) return;
try {
if (data.type === 'debug-inspected') {
const pending = current.inspections?.get(data.requestId);
current.inspections?.delete(data.requestId);
if (pending) data.error ? pending.reject(new Error(data.error)) : pending.resolve(data.page);
return;
}
if (data.type === "status") { setStatus(data.text); return; }
clearTimeout(current.timer);
if (data.type === 'debug-paused') {
setDebugPoint(data); setPhase('paused'); setRaceMinimized(false);
setStatus(`${current.language === 'fr' ? 'Pause avant' : 'Paused before'} ${data.function} : ${data.line}`);
requestAnimationFrame(() => {
const field = sourceField.current;
if (!field) return;
const height = parseFloat(getComputedStyle(field).lineHeight);
const top = (data.line - 1) * height;
if (top < field.scrollTop || top > field.scrollTop + field.clientHeight - height * 2) field.scrollTop = Math.max(0, top - field.clientHeight / 3);
gutter.current.scrollTop = highlighter.current.scrollTop = squiggles.current.scrollTop = field.scrollTop; setEditorScroll(field.scrollTop);
});
} else if (data.type === "analyzed") {
setDiagnostics(data.diagnostics);
const paragraphs = narrateReview(reviewC(current.source, data.diagnostics), current.personality, current.language);
setAnalysis({ source: current.source, text: paragraphs.join("\n\n") });
setPhase("feedback"); setStatus("Reachy analyse les pistes d'amélioration…");
await narrate(current, paragraphs.join(" "));
if (session.current !== current) return;
setPhase("idle"); setStatus("Analyse terminée. Les conseils restent disponibles ci-dessous.");
} else if (data.type === "compiled") {
setDebugLines(data.debugLines || []);
if (!data.ok) setDebugMode(false);
setDiagnostics(data.diagnostics);
setPhase("feedback");
setStatus(current.assessment ? (data.ok ? 'Compilation successful.' : 'Compilation failed.') : (data.ok ? "Compilation successful! Microduck is celebrating." : "Compilation failed. Microduck reacts, then Reachy explains."));
const reactions = await Promise.allSettled(current.exercise || current.assessment || current.debug ? [] : [
gameApi.playMicroduckEmotion?.(data.ok ? "excited" : "mock", current.voice.signal),
gameApi.playReachyEmotion?.(data.ok ? "proud1" : "reprimand1", current.voice.signal),
]);
if (session.current !== current) return;
// Emotion recordings can include a forward Microduck motion. Restore
// the Code Training staging once both reactions have completed.
if (!current.assessment) gameApi.enterCodeTraining?.();
for (const reaction of reactions) if (reaction.status === "rejected") append(`Robot: ${reaction.reason?.message || reaction.reason}\n`);
if (!data.ok && !current.assessment) {
const explanation = explainDiagnostic(data.diagnostics, current.source);
setExplanation(explanation);
await narrate(current, explanation);
}
if (session.current !== current) return;
setCompiledSource(data.ok ? current.source : null);
if (data.ok && current.autoRun) {
current.autoRun = false;
run(current, true);
} else {
setStatus(data.ok ? "Compilation successful. Ready to run." : "Fix the errors, then compile again.");
setPhase("idle");
}
} else if (data.type === "output") {
if (current.exercise && data.fd === 1) await current.protocol.write(data.text);
else {
append(data.text);
if (data.fd === 1) { current.speech += data.text; await speak(current); }
}
if (session.current !== current) return;
worker.postMessage({ type: "reply" }); arm(current);
} else if (data.type === "input") {
await current.protocol?.flush();
if (current.exercise?.id === 'microducks-race' || !current.exercise) setRaceMinimized(false);
await speak(current, true);
if (session.current !== current) return;
setPhase("input"); setStatus("Waiting for terminal input…");
} else if (data.type === "flush") {
await current.protocol?.flush();
await speak(current, true);
if (session.current !== current) return;
worker.postMessage({ type: "reply" }); arm(current);
} else if (data.type === "exited") {
setDebugPoint(null); setDebugMode(false);
await current.protocol?.flush();
if (current.exercise && gameApi.endTrainingRun?.() === false) {
setRaceLaunched(false);
setRaceMinimized(false); append('\n[Course terminée sans message de victoire]\n');
}
append(`\n[Program exited with code ${data.code}]\n`);
setPhase("idle"); setStatus(`Program finished (exit ${data.code}).`);
} else if (data.type === "error") {
await speak(current, true);
if (session.current !== current) return;
append(`\n${data.text}\n`); stop(data.text);
}
} catch (error) { if (session.current === current) stop(error.message || String(error)); }
};
worker.postMessage(command);
}
function toggleBreakpoint(line) {
const next = breakpointsRef.current.includes(line) ? breakpointsRef.current.filter(item => item !== line) : [...breakpointsRef.current, line];
breakpointsRef.current = next; setBreakpoints(next);
session.current?.worker.postMessage({ type: 'breakpoints', lines: next });
}
function resumeDebug(command) {
if (phase !== 'paused' || !session.current) return;
cancelInspections(session.current);
setPhase('running'); setDebugPoint(null); setStatus('Debug: running');
arm(session.current);
session.current.worker.postMessage({ type: 'reply', value: command });
}
function cancelInspections(current) {
current.inspections?.forEach(pending => pending.reject(new Error('Pause ended.')));
current.inspections?.clear();
}
const inspectArray = useCallback((arrayId, start) => {
const current = session.current;
if (!current || phase !== 'paused' || !debugPoint) return Promise.reject(new Error('Pause ended.'));
current.inspections ??= new Map();
const requestId = current.inspectionId = (current.inspectionId || 0) + 1;
return new Promise((resolve, reject) => {
current.inspections.set(requestId, { resolve, reject });
current.worker.postMessage({ type: 'debug-inspect', requestId, pauseId: debugPoint.pauseId, arrayId, start });
});
}, [phase, debugPoint]);
function run(current = session.current, skipSourceCheck = false) {
if (!current || (!skipSourceCheck && compiledSource !== source)) return;
setRaceLaunched(false);
current.exercise = exerciseRef.current;
current.protocol = current.exercise?.id === 'microducks-race' ? createRaceProtocol({
configure: (count, distance) => {
if (!gameApi.startTrainingRace) throw new Error("La simulation n'est pas encore prête.");
gameApi.startTrainingRace({ count, distance, onFinish: number => {
if (session.current === current) append(`le vainqueur est microduck ${number}\n`);
} });
},
speed: (number, speed) => gameApi.setTrainingRaceSpeed?.(number, speed),
go: () => { gameApi.goTrainingRace?.(); setShow3d(true); setRaceMinimized(true); setRaceLaunched(true); setExerciseOpen(false); },
winner: number => { gameApi.finishTrainingRace?.(number); return false; },
output: append,
}) : current.exercise ? createInteractionProtocol({
mode: current.exercise.id,
start: () => {
if (current.boardStarted) throw new Error('Start Tic Tac Toe only once per run.');
if (!gameApi.startTrainingBoard) throw new Error('The simulation is not ready yet.');
gameApi.startTrainingBoard({ onChange: state => { if (session.current === current) setBoard(state); } });
current.boardStarted = true;
setShow3d(true); setRaceMinimized(true); setRaceLaunched(true); setExerciseOpen(false);
},
move: (team, cell) => gameApi.playTrainingBoard(team, cell),
finish: winner => gameApi.finishTrainingBoard(winner),
robot: async (name, emotion) => {
current.voice.signal.throwIfAborted();
if (name === 'microduck') await gameApi.playMicroduckEmotion?.(emotion === 'sad' ? 'sadness' : emotion, current.voice.signal);
else await gameApi.playReachyEmotion?.(emotion, current.voice.signal);
if (session.current === current) gameApi.enterCodeTraining?.();
},
output: async text => {
if (session.current !== current) return;
append(text);
if (current.exercise.id !== 'tic-tac-toe') { current.speech += text; await speak(current, true); }
},
}) : null;
current.boardStarted = false; setBoard(null);
current.speech = ""; setTerminal(""); setInput(""); setRaceMinimized(false); setCompact(false); if (!current.assessment) gameApi.stopTrainingRace?.(); setPhase("running"); setStatus("Running");
if (current.exercise && !current.exercise.scene) {
setRaceMinimized(true); setRaceLaunched(true); setShow3d(true); setExerciseOpen(false);
}
arm(current); current.worker.postMessage({ type: "run" });
}
function saveSource() {
const url = URL.createObjectURL(new Blob([source], { type: "text/x-c;charset=utf-8" }));
const link = document.createElement("a");
link.href = url; link.download = "main.c";
document.body.append(link); link.click(); link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
function openRaceCode() {
setCompact(false); setRaceMinimized(false);
requestAnimationFrame(() => { if (dialog.current) dialog.current.scrollTop = 0; });
}
function submitInput(eof = false) {
const current = session.current;
if (!current || phase !== "input") return;
append(eof ? "[End of input]\n" : `${input}\n`);
current.worker.postMessage({ type: "reply", value: eof ? null : `${input}\n` });
setInput(""); setPhase("running"); setStatus("Running — Reachy reads stdout."); arm(current);
}
function chooseSourceFile() { fileInput.current?.click(); }
// The textarea covers the squiggle layer, so hit-test its marks by position.
function hoverSquiggle(x, y) {
const layer = squiggles.current;
if (!layer) return;
const editor = layer.getBoundingClientRect();
for (const mark of layer.querySelectorAll('[data-diagnostic]')) {
const box = [...mark.getClientRects()].find(rect => x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom + 4);
if (!box) continue;
const range = lintRanges[mark.dataset.diagnostic];
const below = box.bottom - editor.top + 4;
if (hoveredDiagnostic?.range !== range) setHoveredDiagnostic({ range, severity: range.severity, message: range.message, left: Math.max(0, box.left - editor.left), top: below + 60 > editor.height ? box.top - editor.top - 4 : below, above: below + 60 > editor.height });
return;
}
if (hoveredDiagnostic) setHoveredDiagnostic(null);
}
function selectEditorWord(field = sourceField.current) {
if (!field) return;
const word = field.value.slice(field.selectionStart, field.selectionEnd);
setSelectedWord(word.length <= 80 && /^[A-Za-z_]\w*$/.test(word) ? word : "");
}
function editSource(field, edit) {
field.setSelectionRange(edit.start, edit.end);
// Chromium keeps these edits in the native undo stack; retain a fallback.
if (!asOwnEdit(() => document.execCommand('insertText', false, edit.text))) field.setRangeText(edit.text, edit.start, edit.end, 'end');
setSource(field.value); setSelectedWord('');
requestAnimationFrame(() => {
field.setSelectionRange(edit.selectionStart ?? edit.caret, edit.caret);
if (gutter.current) gutter.current.scrollTop = field.scrollTop;
for (const layer of [highlighter.current, squiggles.current]) if (layer) { layer.scrollTop = field.scrollTop; layer.scrollLeft = field.scrollLeft; }
});
}
async function loadPendingFile() {
if (!pendingFile) return;
try {
const nextSource = await pendingFile.text();
setSource(nextSource); setCompiledSource(null); setTerminal(""); setDiagnostics(""); setExplanation(""); setStatus(`${pendingFile.name} loaded. Compile it to run.`);
} catch (error) { setStatus(`Unable to open the file: ${error.message || error}`); }
finally { setPendingFile(null); }
}
async function askReachy() {
const question = helpQuestion.trim();
if (!question) return;
if (!webGpuAvailable()) {
const localAdvice = diagnostics ? explainDiagnostic(diagnostics, source) : "WebGPU n’est pas disponible ici. Reachy peut toujours expliquer les diagnostics du compilateur, mais l’assistant local demande un Chrome ou Edge récent avec WebGPU.";
setHelpAnswer(localAdvice); return;
}
setHelpBusy(true); setHelpAnswer("");
try {
const answer = await askReachyLocally({ question, source, diagnostics, language, onProgress: setHelpStatus });
setHelpAnswer(answer);
gameApi.reachySay?.(answer, { language, personality, provider: "browser", trainingFeedback: true }).catch(() => {});
} catch (error) {
setHelpAnswer(`L’assistant local n’a pas pu démarrer : ${error.message || error}`);
} finally {
setHelpBusy(false); setHelpStatus("");
}
}
const diagnosticTone = /(?:fatal )?error:/.test(diagnostics) ? "has-errors" : "has-warnings";
return createPortal(<>
{!exam.active && !exercise?.scene && <>
{isBoard ? terminal.trim().split('\n').slice(-2).join('\n') : terminal}