File size: 51,623 Bytes
b09157d
022cb3a
16215cb
022cb3a
d6a8383
022cb3a
3713433
eb24e49
f5375f2
 
b7125e0
b09157d
 
 
 
 
db2d194
 
b09157d
022cb3a
 
b09157d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
022cb3a
 
b09157d
 
 
022cb3a
 
b09157d
 
 
 
 
 
 
 
 
022cb3a
 
 
73bd3c5
2eac511
022cb3a
 
b09157d
 
 
 
 
 
 
f5375f2
 
 
 
 
 
 
 
d6a8383
 
3713433
 
b09157d
16215cb
eb24e49
f5375f2
 
eb24e49
022cb3a
b7125e0
 
 
 
022cb3a
b09157d
 
 
 
 
 
f5375f2
 
b09157d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
022cb3a
 
16215cb
f5375f2
16215cb
d6a8383
b09157d
022cb3a
f5375f2
b09157d
 
 
 
3713433
b09157d
 
 
b7125e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b09157d
 
 
 
 
 
 
3713433
 
 
 
 
 
 
 
 
f5375f2
022cb3a
 
 
 
 
b09157d
022cb3a
 
 
 
 
b09157d
 
 
 
022cb3a
 
 
 
 
 
 
 
 
 
b09157d
022cb3a
 
 
 
 
 
f5375f2
022cb3a
 
d6a8383
b09157d
d6a8383
 
 
f5375f2
d6a8383
 
 
 
b09157d
 
16215cb
2eac511
b09157d
 
022cb3a
b09157d
022cb3a
f5375f2
 
b09157d
 
022cb3a
 
 
 
 
b09157d
022cb3a
 
 
 
 
 
b09157d
 
 
 
 
 
022cb3a
 
b09157d
 
 
 
 
 
 
 
 
b7125e0
b09157d
 
16215cb
f5375f2
16215cb
 
d6a8383
16215cb
 
 
b09157d
 
022cb3a
 
b09157d
 
 
 
d6a8383
022cb3a
efd10d1
 
b09157d
d6a8383
b09157d
479059c
73bd3c5
d6a8383
022cb3a
 
 
f5375f2
 
 
 
 
 
 
022cb3a
b09157d
 
 
 
 
022cb3a
 
 
b09157d
 
022cb3a
 
 
 
b09157d
022cb3a
 
 
 
b09157d
 
 
 
 
 
022cb3a
 
 
 
 
 
 
 
 
 
 
b09157d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5375f2
 
b09157d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
022cb3a
 
16215cb
 
 
 
 
 
 
b09157d
 
 
 
022cb3a
 
 
 
 
 
 
f5375f2
b7125e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5375f2
 
 
b09157d
 
 
 
 
db2d194
b09157d
 
 
 
b7125e0
b09157d
f5375f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db2d194
022cb3a
b09157d
022cb3a
eb24e49
b09157d
f5375f2
b09157d
 
 
022cb3a
 
 
 
b09157d
 
 
16215cb
b09157d
16215cb
b09157d
 
f5375f2
b09157d
022cb3a
 
 
eb24e49
d6a8383
f5375f2
 
 
2eac511
db2d194
b09157d
 
 
 
 
022cb3a
b09157d
 
b7125e0
b09157d
f5375f2
b7125e0
 
d6a8383
b09157d
 
 
 
 
 
 
 
 
 
d6a8383
3713433
d6a8383
f5375f2
022cb3a
 
b09157d
022cb3a
b09157d
 
 
 
b7125e0
f5375f2
022cb3a
d6a8383
b09157d
022cb3a
2eac511
73bd3c5
b09157d
022cb3a
b09157d
022cb3a
 
 
 
b09157d
022cb3a
b09157d
 
db2d194
b09157d
2eac511
b09157d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
022cb3a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
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.<br /><br />
      <strong>1. Set up the race.</strong> 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.<br /><br />
      <strong>2. Start together.</strong> 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.<br /><br />
      <strong>3. Run the race.</strong> 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.<br /><br />
      <strong>4. Predict the finish.</strong> 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.<br /><br />
      <strong>Required simulator messages.</strong> 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.<br />
      After validating the inputs (count: integer; distance: metres):<br /><code>{'printf("course %d distance %f\\n", count, distance);'}</code><br />
      For each runner, before the start and at every speed update (number: 1 to N; speed: metres per second):<br /><code>{'printf("microduck %d vitesse %f\\n", number, speed);'}</code><br />
      Once all N initial speeds have been sent, give the start signal once:<br /><code>{'printf("1,2,3,partez\\n");'}</code><br />
      At the predicted finish, send the predicted winner's number:<br /><code>{'printf("le vainqueur est microduck %d\\n", number);'}</code><br />
      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.<br /><br />
      <strong>1. Préparer la course.</strong> 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.<br /><br />
      <strong>2. Donner un départ commun.</strong> 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.<br /><br />
      <strong>3. Faire progresser la course.</strong> 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.<br /><br />
      <strong>4. Prévoir l’arrivée.</strong> 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.<br /><br />
      <strong>Messages requis par le simulateur.</strong> 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.<br />
      Après validation des saisies (count : entier ; distance : mètres) :<br /><code>{'printf("course %d distance %f\\n", count, distance);'}</code><br />
      Pour chaque coureur, avant le départ et à chaque changement de vitesse (number : de 1 à N ; speed : mètres par seconde) :<br /><code>{'printf("microduck %d vitesse %f\\n", number, speed);'}</code><br />
      Une fois les N vitesses initiales transmises, donnez une seule fois le signal de départ :<br /><code>{'printf("1,2,3,partez\\n");'}</code><br />
      Au moment de l’arrivée prévue, transmettez le numéro du vainqueur prévu :<br /><code>{'printf("le vainqueur est microduck %d\\n", number);'}</code><br />
      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(<><dialog ref={dialog} className={`code-training${debugMode ? ' is-debugging' : ''}${exam.active ? ' is-exam' : ''}${exam.active && exam.quizPending ? ' is-quiz' : ''}${exam.active && !examToolsOpen ? ' exam-wide' : ''}${docked ? " is-docked" : ""}${exerciseRunning ? " exercise-running" : ""}`} style={{ '--editor-font': EDITOR_FONTS[editorFont].family, '--editor-size': `${editorSize}px` }} aria-labelledby="code-training-title" onCancel={(event) => { event.preventDefault(); onClose(); }}>
    <header className="code-training-header">
      <div><strong id="code-training-title">{exam.active ? exam.t('ÉVALUATION', 'ASSESSMENT') : 'CODE TRAINING'}</strong><span>{exam.active ? exam.t('Éditeur C · simulation 3D en pause', 'C editor · 3D simulation paused') : 'Learn with Microduck & Reachy Mini'}</span></div>
      <label>Language <select aria-label="Programming language" defaultValue="c"><option value="c">C (C17)</option></select></label>
      <label>Voice <select aria-label="Analysis language" value={language} disabled={busy} onChange={(e) => useGame.setState({ speechLanguage: e.target.value })}>{Object.entries(SPEECH_LANGUAGES).map(([code, item]) => <option key={code} value={code}>{item.label}</option>)}</select></label>
      {!exam.active && <><label>Style <select aria-label="Reachy personality" value={personality} disabled={busy} onChange={(e) => useGame.setState({ speechPersonality: e.target.value })}><option value="sympa">Warm</option><option value="blagueur">Playful</option><option value="cassant">Blunt</option></select></label>
      <label>Engine <select aria-label="Reachy voice engine" value={provider} disabled={busy} onChange={(e) => useGame.setState({ speechProvider: e.target.value })}><option value="browser">Local · instant</option><option value="qwen">Qwen · online</option></select></label>
      <label className="three-toggle"><input type="checkbox" checked={show3d} onChange={(e) => setShow3d(e.target.checked)} /> 3D</label></>}
      {!exam.active && <button type="button" className="help-toggle" aria-label="Ask Reachy for help" aria-expanded={helpOpen} onClick={() => setHelpOpen((value) => !value)}>?</button>}
      {!exam.active && <button type="button" className="code-close" aria-label={compact ? "Expand editor" : "Compact editor"} disabled={["feedback", "running", "input"].includes(phase)} onClick={() => setCompact(!compact)}>{compact ? "+" : "−"}</button>}
      <button type="button" className="code-close" aria-label="Close code training" onClick={onClose}>×</button>
    </header>
    <div className="code-training-toolbar">
      <span className="code-filename">main.c</span>
      <label className="editor-setting">{exam.t('Police', 'Font')} <select aria-label="Editor font" value={editorFont} onChange={e => setEditorFont(e.target.value)}>{Object.entries(EDITOR_FONTS).map(([id, font]) => <option key={id} value={id}>{font.label}</option>)}</select></label>
      <label className="editor-setting">{exam.t('Taille', 'Size')} <select aria-label="Editor font size" value={editorSize} onChange={e => setEditorSize(Number(e.target.value))}>{[12, 14, 16, 18, 20].map(size => <option key={size} value={size}>{size}</option>)}</select></label>
      {exercise && raceLaunched && <button type="button" onClick={() => setRaceMinimized(true)}>{isBoard ? (language === 'fr' ? 'Voir le plateau' : 'View board') : (exercise.id === 'microducks-race' ? 'Voir la course' : (language === 'fr' ? 'Voir la simulation' : 'View simulation'))}</button>}
      <button type="button" onClick={() => compile()} disabled={busy || !source.trim() || !supported}>Compile</button>
      <button type="button" onClick={() => compile("analyze")} disabled={exam.active || busy || !source.trim() || !supported}>Analyse</button>
      <button type="button" onClick={saveSource}>Enregistrer .c</button>
      {!exam.active && <button type="button" onClick={chooseSourceFile} disabled={busy}>Charger .c</button>}
      {exam.active && <ExamActions exam={exam} source={source} busy={busy} />}
      <button type="button" className="compile-run" aria-label="Compile and run" title="Compile and run" onClick={() => compile("compile", true)} disabled={busy || !source.trim() || !supported}>→</button>
      <button type="button" className="compile-run debug-run" aria-label="Compile and debug" title={exam.t('Compiler et déboguer', 'Compile and debug')} onClick={() => compile('compile', true, true)} disabled={busy || editorLocked || !source.trim() || !supported}><span aria-hidden="true">➜<svg viewBox="0 0 24 24"><path d="M9 5 7 2m8 3 2-3M4 9h4m8 0h4M3 14h5m8 0h5M5 20l4-4m6 0 4 4M8 10a4 4 0 0 1 8 0v5a4 4 0 0 1-8 0zM9 6h6M12 10v9" /></svg></span></button>
      <button onClick={() => stop()} disabled={!busy}>Stop</button>
    </div>
    {!supported && <p role="alert" className="code-notice">Interactive C requires a recent Chrome or Edge browser. You can still write and save your code here.</p>}
    {voice.status && <p className="code-notice" role="status">{voice.status}</p>}
    {voice.error && <p className="code-notice" role="alert">{voice.error}{session.current?.lastNarration && <button type="button" disabled={busy || voice.busy} onClick={async () => { const current = session.current; if (!current) return; setPhase("feedback"); await narrate(current, current.lastNarration); if (session.current === current) setPhase("idle"); }}>Retry voice</button>}</p>}
    <input ref={fileInput} className="file-picker" type="file" accept=".c,text/x-c,text/plain" aria-label="Open a C file" onChange={(event) => setPendingFile(event.target.files?.[0] || null)} />
    {pendingFile && <section className="load-confirm" role="dialog" aria-label="Save before opening file"><strong>Ouvrir « {pendingFile.name} » ?</strong><p>Le code actuel sera remplacé. Souhaites-tu d’abord l’enregistrer ?</p><button type="button" onClick={() => { saveSource(); loadPendingFile(); }}>Sauvegarder puis ouvrir</button><button type="button" onClick={loadPendingFile}>Ouvrir sans sauvegarder</button><button type="button" onClick={() => setPendingFile(null)}>Annuler</button></section>}
    {helpOpen && <section className="reachy-help" aria-label="Reachy code help"><button type="button" className="feedback-close" aria-label="Close Reachy help" onClick={() => setHelpOpen(false)}>×</button><strong>Ask Reachy · local WebGPU</strong><p>Aucune clé ni API : le modèle se télécharge une fois sur cet appareil, puis reste dans le navigateur.</p><textarea aria-label="Question for Reachy" value={helpQuestion} disabled={helpBusy} onChange={(e) => setHelpQuestion(e.target.value)} placeholder="Pourquoi mon programme ne compile pas ?" /><button type="button" disabled={helpBusy || !helpQuestion.trim()} onClick={askReachy}>{helpBusy ? "Preparing…" : "Ask"}</button>{helpStatus && <p className="help-status" role="status">{helpStatus}</p>}{helpAnswer && <pre>{helpAnswer}</pre>}</section>}
    {exam.active && <section className="exam-statement" aria-label={exam.t('Énoncé', 'Assignment')}><strong>{exam.selected?.title[language === 'fr' ? 'fr' : 'en'] || exam.t('Choisissez un exercice après avoir saisi le code d’accès.', 'Enter the access code, then choose an exercise.')}</strong></section>}
    {exam.active && exam.quizPending && <ExamQuiz exam={exam} />}
    {exam.active && !examToolsOpen && <>
      {exam.notice && <p className="code-notice" role="status">{exam.notice}</p>}
      {exam.storageError && <p className="code-notice" role="alert">{exam.t('Stockage indisponible : téléchargez votre fichier .c avant de fermer cette page.', 'Storage unavailable: download your .c file before closing this page.')}</p>}
      {exam.activity.syncError && <p className="code-notice" role="alert">{exam.t('Journal non synchronisé. Une nouvelle tentative sera faite au retour de la connexion.', 'Activity log not synced. It will be retried when the connection returns.')}</p>}
    </>}
    <div className="code-source">
      <div ref={gutter} className="debug-gutter" aria-label="Breakpoints">{source.split('\n').map((_, i) => <button key={i} type="button" className={`${breakpoints.includes(i + 1) ? 'has-breakpoint ' : ''}${debugPoint?.line === i + 1 ? 'current-line ' : ''}${debugLines.includes(i + 1) ? 'executable-line' : ''}`} aria-label={`Breakpoint line ${i + 1}`} aria-pressed={breakpoints.includes(i + 1)} title={`${exam.t('Point d’arrêt', 'Breakpoint')} ${i + 1}${debugLines.length && !debugLines.includes(i + 1) ? exam.t(' — pas d’instruction exécutable', ' — no executable statement') : ''}`} onClick={() => toggleBreakpoint(i + 1)}><span>{debugPoint?.line === i + 1 ? '➜' : breakpoints.includes(i + 1) ? '●' : '·'}</span>{i + 1}</button>)}</div>
      <div className="code-editor"><pre ref={highlighter} className="code-highlight" aria-hidden="true" dangerouslySetInnerHTML={{ __html: highlighted }} />
      <pre ref={squiggles} className="code-highlight code-squiggles" aria-hidden="true" dangerouslySetInnerHTML={{ __html: squiggled }} />
      {debugPoint && <div className="debug-line-highlight" aria-hidden="true" style={{ top: 12 + (debugPoint.line - 1) * editorSize * 1.5 - editorScroll, height: editorSize * 1.5 }} />}
      <textarea ref={sourceField} aria-label="C source code" autoFocus spellCheck="false" autoCapitalize="off" autoCorrect="off" value={source} readOnly={editorLocked}
        onScroll={(e) => { gutter.current.scrollTop = e.currentTarget.scrollTop; for (const layer of [highlighter.current, squiggles.current]) { layer.scrollTop = e.currentTarget.scrollTop; layer.scrollLeft = e.currentTarget.scrollLeft; } setEditorScroll(e.currentTarget.scrollTop); setHoveredDiagnostic(null); }}
        onMouseMove={(e) => hoverSquiggle(e.clientX, e.clientY)} onMouseLeave={() => setHoveredDiagnostic(null)}
        onChange={(e) => { setSource(e.target.value); if (e.nativeEvent.inputType !== "insertLineBreak") setSyntaxHint(null); }} onKeyDown={(e) => {
          if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f' && !editorLocked) {
            e.preventDefault();
            const field = e.currentTarget, text = reindentC(field.value);
            editSource(field, { start: 0, end: field.value.length, text, caret: Math.min(field.selectionStart, text.length) });
          }
          if (e.key === "Enter" && !editorLocked && !e.nativeEvent.isComposing) {
            e.preventDefault();
            const field = e.currentTarget;
            const hint = !exam.active && field.selectionStart === field.selectionEnd ? syntaxHintAtNewline(field.value, field.selectionStart) : null;
            editSource(field, newlineEdit(field.value, field.selectionStart, field.selectionEnd));
            setSyntaxHint(hint);
            if (hint && performance.now() - lastQuack.current > 300) { lastQuack.current = performance.now(); gameApi.quack?.(); }
          }
          if (e.key === "Tab" && !editorLocked) {
            e.preventDefault();
            const field = e.currentTarget, start = field.selectionStart, end = field.selectionEnd;
            editSource(field, tabEdit(field.value, start, end, e.shiftKey));
          }
        }} onSelect={(e) => selectEditorWord(e.currentTarget)} onDoubleClick={(e) => {
          const field = e.currentTarget, range = wordRange(field.value, field.selectionStart);
          if (range) { field.setSelectionRange(range.start, range.end); selectEditorWord(field); }
        }} />
      {hoveredDiagnostic && <div className={`squiggle-tooltip is-${hoveredDiagnostic.severity}`} role="tooltip" style={{ left: hoveredDiagnostic.left, top: hoveredDiagnostic.top, transform: hoveredDiagnostic.above ? 'translateY(-100%)' : undefined }}>{hoveredDiagnostic.message}</div>}
      </div>
    </div>
    {syntaxHint && <p className="code-notice" aria-label="Syntax hint">Line {syntaxHint.line}: {syntaxHint.message}</p>}
    {debugMode && <DebugPanel point={debugPoint} paused={phase === 'paused'} resume={resumeDebug} language={language} watch={watch} setWatch={setWatch} inspectArray={inspectArray} />}
    <p className="code-status" role="status">{status}{!busy && compiledSource && compiledSource !== source ? " Source changed: compile again." : ""}</p>
    {(diagnostics || explanation) && <section className={`code-feedback ${diagnosticTone}`}><button type="button" className="feedback-close" aria-label="Dismiss compiler message" disabled={busy} onClick={() => { setDiagnostics(""); setExplanation(""); setStatus(""); }}>×</button><details className="code-diagnostics" open><summary>Compiler diagnostics</summary><pre>{diagnostics}{explanation ? `\n\nReachy: ${explanation}` : ""}</pre></details>{exam.active && diagnosticTone === "has-errors" && <div className="exam-help"><button type="button" aria-expanded={examHelpOpen} onClick={() => setExamHelpOpen((value) => !value)}>Aide</button>{examHelpOpen && <p role="note">{explainDiagnostic(diagnostics, source, "fr")}</p>}</div>}</section>}
    {analysis && <section className="code-feedback"><button type="button" className="feedback-close" aria-label="Dismiss analysis" disabled={busy} onClick={() => { setAnalysis(null); setDiagnostics(""); setStatus(""); }}>×</button><details className="code-analysis" open><summary>Analyse de Reachy{analysis.source !== source ? " — code modifié, relancer l'analyse" : ""}</summary><pre>{analysis.text}</pre></details></section>}
    <div className="code-terminal-heading">TERMINAL <span>{exam.active ? 'stdout · stdin → scanf' : 'stdout → Reachy Mini · stdin → scanf'}</span></div>
    <pre ref={output} className="code-terminal" aria-label="Program terminal" tabIndex={0}>{terminal || "Program output will appear here."}</pre>
    {!exerciseInput && <form className="code-input" onSubmit={(e) => { e.preventDefault(); submitInput(); }}>
      <span aria-hidden="true">❯</span>
      <input ref={inputField} aria-label="Terminal input" value={input} maxLength={4096} disabled={phase !== "input"} placeholder={phase === "input" ? "Type a value, then press Enter…" : "Available when your program reads input"} onChange={(e) => setInput(e.target.value)} />
      <button disabled={phase !== "input"}>Send</button>
      <button type="button" disabled={phase !== "input"} onClick={() => submitInput(true)} title="Send end of input">EOF</button>
    </form>}
    <footer>Your code is saved on this device. Closing stops the program.</footer>
  </dialog>
  <aside className={`exercise-panel${exerciseOpen ? " is-open" : ""}${exam.active && !examToolsOpen ? ' exam-tools-collapsed' : ''}`} aria-label="Exercises">
    {exam.active && !exam.quizPending && <button type="button" className="exercise-panel-button exam-tools-toggle" aria-expanded={examToolsOpen} onClick={() => setExamToolsOpen(value => !value)}>{examToolsOpen ? exam.t('Agrandir le code', 'Expand code') : exam.t('Sujets et évaluation', 'Assignments and assessment')}</button>}
    <button type="button" className="exercise-panel-button" disabled={exam.working} onClick={() => { if (exam.active) exam.leave(); setExerciseOpen((value) => !value); }}>Exercices</button>
    {import.meta.env.VITE_EXAM_ENABLED !== 'false' && <button type="button" className="exercise-panel-button exam-toggle" aria-pressed={exam.active} disabled={exam.working} onClick={() => { if (exam.active) exam.leave(); else { useGame.setState({ speechLanguage: 'fr' }); exam.enter(); } }}>Evaluation</button>}
    {exam.active && <ExamPanel exam={exam} language={language} />}
    {exerciseOpen && <div className="exercise-panel-content">
      {!exercise ? <><strong>{language === 'fr' ? 'Liste des exercices' : 'Exercises'}</strong>{[MICRODUCK_RACE, ...INTERACTIVE_EXERCISES].map(item => <button key={item.id} type="button" className="exercise-item" disabled={busy} onClick={() => { setSource(""); setCompiledSource(null); setTerminal(""); setDiagnostics(""); setExercise(item); setCompact(false); }}>{item.title}</button>)}</> : <><button type="button" className="exercise-back" disabled={busy} onClick={() => { setExercise(null); setBoard(null); setRaceMinimized(false); gameApi.stopTrainingRace?.(); gameApi.enterCodeTraining?.(); }}>← Liste des exercices</button><h2>{exercise.title}</h2><p>{exercise.statement[language] ?? exercise.statement.en}</p></>}
    </div>}
  </aside>
  {!exam.active && !exercise?.scene && <><div className="training-duck-slot" aria-label="Microduck" /><div className="training-reachy-slot" aria-label="Reachy Mini" /></>}
  {exerciseInput && <section className={`board-input-panel${isBoard ? "" : " workshop-terminal"}`} aria-label={isBoard ? "Tic Tac Toe controls" : "Exercise terminal"}>
    {isBoard ? <div className="board-turn" role="status"><span className={`team-dot team-${board?.winner || board?.turn || 1}`} />{board?.moving ? (language === 'fr' ? 'Microduck rejoint sa case…' : 'Microduck is walking to its cell…') : board?.finished ? (board.winner ? `${language === 'fr' ? 'Victoire' : 'Winner'} · ${board.winner === 1 ? (language === 'fr' ? 'Blancs' : 'White') : (language === 'fr' ? 'Violets' : 'Purple')}` : (language === 'fr' ? 'Match nul' : 'Draw')) : `${language === 'fr' ? 'À vous' : 'Your turn'} · ${board?.turn === 2 ? (language === 'fr' ? 'Violets' : 'Purple') : (language === 'fr' ? 'Blancs' : 'White')} · 1–9`}</div> : <div className="board-turn">{exercise.title}</div>}
    <pre ref={exerciseOutput} className="board-prompt" aria-label="Game prompt">{isBoard ? terminal.trim().split('\n').slice(-2).join('\n') : terminal}</pre>
    <form className="code-input" onSubmit={e => { e.preventDefault(); submitInput(); }}>
      <input ref={inputField} aria-label="Terminal input" autoComplete="off" value={input} maxLength={4096} disabled={phase !== 'input'} placeholder={isBoard ? (language === 'fr' ? 'Case de 1 à 9, puis Entrée' : 'Cell 1 to 9, then Enter') : (language === 'fr' ? 'Valeur, puis Entrée' : 'Value, then Enter')} onChange={e => setInput(e.target.value)} />
      <button disabled={phase !== 'input'}>{isBoard ? (language === 'fr' ? 'Jouer' : 'Play') : (language === 'fr' ? 'Envoyer' : 'Send')}</button>
      <button type="button" disabled={phase !== 'input'} onClick={() => submitInput(true)}>EOF</button>
    </form>
    <div className="board-actions"><button onClick={openRaceCode}>{language === 'fr' ? 'Ouvrir le code / terminal' : 'Open code / terminal'}</button><button onClick={() => stop()}>{language === 'fr' ? 'Arrêter' : 'Stop'}</button></div>
  </section>}
  {raceMinimized && exercise?.id === 'microducks-race' && <div className="race-controls"><strong>Microduck’s Race</strong><button onClick={openRaceCode}>Ouvrir le code / terminal</button><button onClick={() => stop()}>Arrêter</button></div>}
  </>, document.body);
}