-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1320 lines (1235 loc) · 48.2 KB
/
Copy pathapp.js
File metadata and controls
1320 lines (1235 loc) · 48.2 KB
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function () {
"use strict";
/* ============================================================== */
/* Small utilities */
/* ============================================================== */
const $ = (id) => document.getElementById(id);
function escapeHtml(text) {
return String(text)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
/* ============================================================== */
/* Tutor text rendering */
/* ============================================================== */
//
// The tutor (Ollama or Claude) sometimes ignores the "plain text" rule and
// emits Markdown + LaTeX. Rather than rely on prompt discipline, we clean
// it up here:
// 1. HTML-escape first, so any literal <, >, & from the model stays text.
// 2. Strip LaTeX delimiters and rewrite the common commands into plain
// text (e.g. \(F\) -> F, \frac{dF}{dt} -> dF/dt, \alpha -> α).
// 3. Render a tiny safe subset of Markdown (bold, italic, inline code,
// bullet/numbered lists, paragraph breaks). NO arbitrary HTML.
const GREEK = {
alpha: "α", beta: "β", gamma: "γ", delta: "δ", epsilon: "ε",
zeta: "ζ", eta: "η", theta: "θ", iota: "ι", kappa: "κ",
lambda: "λ", mu: "μ", nu: "ν", xi: "ξ", pi: "π", rho: "ρ",
sigma: "σ", tau: "τ", upsilon: "υ", phi: "φ", chi: "χ",
psi: "ψ", omega: "ω",
Alpha: "Α", Beta: "Β", Gamma: "Γ", Delta: "Δ", Epsilon: "Ε",
Theta: "Θ", Lambda: "Λ", Mu: "Μ", Pi: "Π", Sigma: "Σ",
Phi: "Φ", Psi: "Ψ", Omega: "Ω",
infty: "∞", partial: "∂", nabla: "∇", sum: "Σ", prod: "Π",
int: "∫", cdot: "·", times: "×", div: "÷", pm: "±", mp: "∓",
leq: "≤", geq: "≥", neq: "≠", approx: "≈", equiv: "≡",
rightarrow: "→", leftarrow: "←", Rightarrow: "⇒", Leftarrow: "⇐",
to: "→", sin: "sin", cos: "cos", tan: "tan", log: "log",
ln: "ln", exp: "exp",
};
function stripLatex(s) {
// Block math: \[ ... \] -> on its own line, plain.
s = s.replace(/\\\[([\s\S]*?)\\\]/g, "\n$1\n");
// Display $$ ... $$ -> on its own line.
s = s.replace(/\$\$([\s\S]*?)\$\$/g, "\n$1\n");
// Inline math: \(...\) and $...$ (avoid currency by requiring no space).
s = s.replace(/\\\(([\s\S]*?)\\\)/g, "$1");
s = s.replace(/(?<!\$)\$([^\s$][^$\n]*?[^\s$])\$(?!\$)/g, "$1");
s = s.replace(/(?<!\$)\$([^\s$])\$(?!\$)/g, "$1");
// \frac{a}{b} -> a/b (parenthesize compound numerator/denominator).
s = s.replace(/\\frac\s*\{([^{}]+)\}\s*\{([^{}]+)\}/g, (_, a, b) => {
const parenA = /[+\-]/.test(a) ? `(${a})` : a;
const parenB = /[+\-]/.test(b) ? `(${b})` : b;
return `${parenA}/${parenB}`;
});
// \sqrt{a} -> sqrt(a)
s = s.replace(/\\sqrt\s*\{([^{}]+)\}/g, "sqrt($1)");
// \text{a} -> a
s = s.replace(/\\text\s*\{([^{}]*)\}/g, "$1");
// Subscripts / superscripts: x_{n} -> x_n, x^{2} -> x^2
s = s.replace(/_\{([^{}]+)\}/g, "_$1");
s = s.replace(/\^\{([^{}]+)\}/g, "^$1");
// Greek + common symbols / function names.
s = s.replace(/\\([A-Za-z]+)/g, (_, name) =>
Object.prototype.hasOwnProperty.call(GREEK, name) ? GREEK[name] : name
);
// Stray "left"/"right" sizing markers — leave the inner brackets.
s = s.replace(/\b(left|right)\b/g, "");
// Tidy spaces.
return s.replace(/[ \t]+/g, " ").replace(/ ?\n ?/g, "\n");
}
function renderTutorMarkdown(raw) {
// 1. Escape first — everything we insert after this is either literal
// escaped text or our own whitelisted tags.
let s = escapeHtml(raw);
// 2. Strip LaTeX -> plain text.
s = stripLatex(s);
// 3. Markdown: code, bold, italics, headers.
s = s.replace(/`([^`\n]+?)`/g, "<code>$1</code>");
s = s.replace(/\*\*([^*\n][^*]*?)\*\*/g, "<strong>$1</strong>");
s = s.replace(/(?<![*\w])\*([^*\n]+?)\*(?!\w)/g, "<em>$1</em>");
s = s.replace(/^#{1,6}\s+(.+)$/gm, "<strong>$1</strong>");
// 4. Lists, line by line. Group consecutive same-type items, even when
// separated by blank lines (tutors love "1. ...\n\n2. ...").
const lines = s.split("\n");
const out = [];
let listType = null;
let buf = [];
const flush = () => {
if (!listType) return;
out.push(
`<${listType}>` +
buf.map((i) => `<li>${i}</li>`).join("") +
`</${listType}>`
);
listType = null;
buf = [];
};
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const ol = line.match(/^\s*\d+\.\s+(.+)$/);
const ul = line.match(/^\s*[-•]\s+(.+)$/);
if (ol) {
if (listType !== "ol") flush();
listType = "ol";
buf.push(ol[1]);
} else if (ul) {
if (listType !== "ul") flush();
listType = "ul";
buf.push(ul[1]);
} else if (line.trim() === "" && listType) {
// Blank line between items — look ahead. If the next non-blank line
// continues the same list type, swallow this blank. Otherwise close.
let j = i + 1;
while (j < lines.length && lines[j].trim() === "") j++;
const next = lines[j] || "";
const continuesOl = /^\s*\d+\.\s+/.test(next);
const continuesUl = /^\s*[-•]\s+/.test(next);
if ((listType === "ol" && continuesOl) || (listType === "ul" && continuesUl)) {
continue; // stay inside the list
}
flush();
out.push(line);
} else {
flush();
out.push(line);
}
}
flush();
s = out.join("\n");
// 5. Paragraph breaks: collapse runs of blank lines, then \n -> <br>.
s = s.replace(/\n{3,}/g, "\n\n");
s = s.replace(/\n/g, "<br>");
// Strip <br> noise adjacent to list tags.
s = s.replace(/(<br>)+(<\/?(?:ol|ul|li)>)/g, "$2");
s = s.replace(/(<\/(?:ol|ul)>)(<br>)+/g, "$1");
return s;
}
/* Optional shared access code for published deployments. The server
* answers 401 + code_required until the right X-Access-Code header is
* sent; we ask once and remember it in localStorage. */
const ACCESS_CODE_KEY = "visuallm-access-code";
function getAccessCode() {
try {
return localStorage.getItem(ACCESS_CODE_KEY) || "";
} catch (e) {
return "";
}
}
function apiHeaders() {
const headers = { "Content-Type": "application/json" };
const code = getAccessCode();
if (code) headers["X-Access-Code"] = code;
return headers;
}
function promptForAccessCode() {
const entered = window.prompt(
"This VisualLM server requires an access code to generate animations:"
);
if (!entered || !entered.trim()) return false;
try {
localStorage.setItem(ACCESS_CODE_KEY, entered.trim());
} catch (e) {
/* private mode — the code just won't persist */
}
return true;
}
async function postJSON(path, body, opts) {
// Fetch with one retry by default: localhost fetches occasionally fail
// with the browser-generic `TypeError: Failed to fetch` for transient
// reasons (server thread mid-restart, socket race, etc.). Re-trying once
// turns most of those into a single visible blip instead of a hard fail.
//
// Callers MUST opt out (`{retry: false}`) for non-idempotent endpoints:
// if a request gets through to the server and only the *response* drops,
// the retry would re-process the side effect (e.g. duplicate uploads).
const maxAttempts = opts && opts.retry === false ? 1 : 2;
let res;
let lastFetchError = null;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
res = await fetch(path, {
method: "POST",
headers: apiHeaders(),
body: JSON.stringify(body),
});
lastFetchError = null;
break;
} catch (err) {
lastFetchError = err;
if (attempt < maxAttempts - 1) {
await new Promise((r) => setTimeout(r, 250));
}
}
}
if (lastFetchError) {
throw new Error(
"Couldn't reach the server. Is the Python server (`python3 main.py`) still running?"
);
}
const data = await res.json().catch(() => ({}));
if (!res.ok) {
// Locked deployment: ask for the access code once and retry the same
// call. A wrong code lands back here and asks again.
if (res.status === 401 && data && data.code_required) {
if (promptForAccessCode()) return postJSON(path, body, opts);
}
const message = data && data.error ? data.error : `Request failed (${res.status}).`;
throw new Error(message);
}
return data;
}
/* ============================================================== */
/* Sandbox runner: a Web Worker + OffscreenCanvas that runs the */
/* AI-generated animation code in isolation. */
/* ============================================================== */
class SandboxRunner {
constructor(frame) {
this.frame = frame;
this.worker = null;
this.ready = false;
this.readyWaiters = [];
this.pending = null; // { resolve, reject, settled, watchdog }
this.speed = 1;
this.paused = false;
this.onCrash = null; // called for runtime errors after a scene is live
this._resizeRaf = 0;
this._spawn();
// Debounce via rAF: a window-drag fires resize ~60×/s, and each
// _resize() sets canvas.width which CLEARS the bitmap. Without coalescing,
// the canvas flickers black for the entire drag. One resize message per
// animation frame is enough for any visible UI change.
window.addEventListener("resize", () => {
if (this._resizeRaf) return;
this._resizeRaf = requestAnimationFrame(() => {
this._resizeRaf = 0;
this._resize();
});
});
this._wireOrbit();
}
/* Drag-to-orbit + scroll-to-zoom + double-click-to-reset for 3D scenes.
* Listeners live on the persistent frame (the canvas inside is recreated
* on every worker respawn); the worker applies the deltas to every cam3d. */
_wireOrbit() {
const frame = this.frame;
let dragging = false;
let lastX = 0;
let lastY = 0;
frame.addEventListener("pointerdown", (e) => {
if (e.button !== 0) return;
dragging = true;
lastX = e.clientX;
lastY = e.clientY;
if (frame.setPointerCapture) {
try {
frame.setPointerCapture(e.pointerId);
} catch (err) {
/* capture is best-effort */
}
}
});
frame.addEventListener("pointermove", (e) => {
if (!dragging || !this.worker) return;
const dx = e.clientX - lastX;
const dy = e.clientY - lastY;
lastX = e.clientX;
lastY = e.clientY;
this.worker.postMessage({
type: "orbit",
dyaw: dx * 0.008,
dpitch: dy * 0.008,
});
});
const endDrag = () => {
dragging = false;
};
frame.addEventListener("pointerup", endDrag);
frame.addEventListener("pointercancel", endDrag);
frame.addEventListener("pointerleave", endDrag);
frame.addEventListener(
"wheel",
(e) => {
if (!this.worker) return;
e.preventDefault();
this.worker.postMessage({
type: "orbit",
dzoom: Math.exp(-e.deltaY * 0.0012),
});
},
{ passive: false }
);
frame.addEventListener("dblclick", () => {
if (this.worker) this.worker.postMessage({ type: "orbit-reset" });
});
}
_newCanvas() {
const old = this.frame.querySelector("canvas");
if (old) old.remove();
const canvas = document.createElement("canvas");
canvas.id = "visualizerCanvas";
canvas.setAttribute("aria-label", "STEM visualization canvas");
this.frame.insertBefore(canvas, this.frame.firstChild);
return canvas;
}
_dims() {
const rect = this.frame.getBoundingClientRect();
return {
width: Math.max(320, Math.round(rect.width)),
height: Math.max(240, Math.round(rect.height)),
dpr: Math.min(2, window.devicePixelRatio || 1),
};
}
_spawn() {
this.ready = false;
if (this.worker) {
try {
this.worker.terminate();
} catch (e) {
/* ignore */
}
}
const canvas = this._newCanvas();
const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker("./sandbox-worker.js?v=16");
this.worker = worker;
worker.onmessage = (e) => this._onMessage(e.data || {});
const d = this._dims();
worker.postMessage(
{ type: "init", canvas: offscreen, width: d.width, height: d.height, dpr: d.dpr },
[offscreen]
);
}
_whenReady() {
if (this.ready) return Promise.resolve();
return new Promise((resolve) => this.readyWaiters.push(resolve));
}
_onMessage(m) {
switch (m.type) {
case "ready":
this.ready = true;
this.readyWaiters.splice(0).forEach((fn) => fn());
break;
case "heartbeat":
if (this.pending && !this.pending.settled) this._settle(true);
break;
case "compile-error":
case "runtime-error": {
// Carry the sandbox-extracted offending line (m.where) on the Error so
// the repair request can forward it to the model.
if (this.pending && !this.pending.settled) {
const e = new Error(m.message || "Animation failed.");
e.where = m.where || "";
this._settle(false, e);
} else if (this.onCrash) {
const e = new Error(m.message || "Animation crashed.");
e.where = m.where || "";
this.onCrash(e);
}
break;
}
default:
break;
}
}
_settle(ok, err) {
const p = this.pending;
if (!p || p.settled) return;
p.settled = true;
clearTimeout(p.watchdog);
this.pending = null;
if (ok) p.resolve();
else p.reject(err);
}
/* Load code and resolve once it renders a frame; reject on error/hang. */
async run(code) {
await this._whenReady();
if (this.pending && !this.pending.settled) this._settle(false, new Error("superseded"));
return new Promise((resolve, reject) => {
const pending = { resolve, reject, settled: false, watchdog: null };
this.pending = pending;
pending.watchdog = setTimeout(() => {
// No heartbeat and no error -> the scene is likely stuck in a loop.
this._spawn(); // kill the frozen worker and start a fresh one
this._settle(false, new Error("The animation hung (possible infinite loop)."));
}, 3000);
this.worker.postMessage({ type: "run", code, resetTime: true });
if (this.paused) this.worker.postMessage({ type: "pause" });
this.worker.postMessage({ type: "speed", value: this.speed });
});
}
pause() {
this.paused = true;
if (this.worker) this.worker.postMessage({ type: "pause" });
}
resume() {
this.paused = false;
if (this.worker) this.worker.postMessage({ type: "resume" });
}
setSpeed(value) {
this.speed = value;
if (this.worker) this.worker.postMessage({ type: "speed", value });
}
_resize() {
if (!this.worker || !this.ready) return;
const d = this._dims();
this.worker.postMessage({
type: "resize",
width: d.width,
height: d.height,
dpr: d.dpr,
});
}
}
/* ============================================================== */
/* App state + DOM references */
/* ============================================================== */
const state = {
mode: "auto",
scene: null,
busy: false,
chat: [],
chatBusy: false,
health: null,
};
const el = {
prompt: $("promptInput"),
visualize: $("visualizeButton"),
random: $("randomButton"),
playPause: $("playPauseButton"),
speed: $("speedSlider"),
speedValue: $("speedValue"),
topic: $("detectedTopic"),
dimension: $("detectedDimension"),
equation: $("detectedEquation"),
summary: $("sceneSummary"),
tag: $("sceneTag"),
confidence: $("sceneConfidence"),
explanation: $("explanationList"),
frame: document.querySelector(".canvas-frame"),
chatMessages: $("chatMessages"),
chatForm: $("chatForm"),
chatInput: $("chatInput"),
sendChat: $("sendChatButton"),
chatSuggestions: $("chatSuggestions"),
statusBadge: $("ollamaStatusBadge"),
modelLabel: $("ollamaModelLabel"),
orbitHint: $("orbitHint"),
};
const runner = new SandboxRunner(el.frame);
// Crashes AFTER a scene has started (post-heartbeat runtime errors) used
// to just print the error and leave a frozen canvas. Now we auto-trigger
// the repair flow with the crashed scene's code + the error message, the
// same way runSceneWithRepair handles errors during initial load.
runner.onCrash = async (err) => {
if (!state.scene || state.busy) {
setConfidence("Animation error: " + err.message, "warn");
return;
}
setBusyVisual(true, "Repairing…");
setConfidence(
"Animation crashed: " + err.message + ". Asking the model to fix it…",
"pending",
);
try {
const repaired = await postJSON("/api/repair", {
prompt: state.scene.prompt,
code: state.scene.code,
error: err.message,
where: err.where || "",
});
await runSceneWithRepair(repaired, state.scene.prompt);
} catch (repairErr) {
setConfidence("Could not auto-repair: " + repairErr.message, "warn");
} finally {
setBusyVisual(false);
}
};
/* ============================================================== */
/* Panel rendering */
/* ============================================================== */
function setConfidence(text, tone) {
el.confidence.textContent = text;
el.confidence.dataset.tone = tone || "";
}
function updatePanels(scene) {
el.topic.textContent = scene.title;
el.dimension.textContent = scene.dimension;
el.equation.textContent = scene.equation || "No single equation — concept scene";
el.summary.textContent = scene.summary;
el.tag.textContent = scene.tag;
// 3D scenes are orbitable — surface that, since nothing else hints at it.
if (el.orbitHint) el.orbitHint.hidden = scene.dimension !== "3D";
el.explanation.innerHTML = "";
(scene.bullets || []).forEach((b) => {
const li = document.createElement("li");
li.textContent = b;
el.explanation.appendChild(li);
});
renderSuggestions(scene);
}
function setBusyVisual(isBusy, label) {
// Track focus so keyboard users aren't stranded when the button they
// pressed gets disabled (focus jumps to <body>). We restore after re-enable.
const focusedWasControl =
isBusy && (document.activeElement === el.visualize ||
document.activeElement === el.random);
if (focusedWasControl) setBusyVisual._restoreFocus = document.activeElement;
state.busy = isBusy;
el.visualize.disabled = isBusy;
el.random.disabled = isBusy;
// Chips trigger visualize() too, but visualize() early-returns when busy.
// Without disabling, clicking a chip mid-generation silently overwrites
// the prompt textarea while the in-flight scene is still loading.
document.querySelectorAll(".chip").forEach((c) => {
c.disabled = isBusy;
});
el.visualize.textContent = isBusy ? label || "Generating…" : "Visualize";
// Tell screen readers the visualization region is loading / settled.
if (el.frame) el.frame.setAttribute("aria-busy", isBusy ? "true" : "false");
if (!isBusy && setBusyVisual._restoreFocus) {
// Only restore focus if it's still on body (user hasn't moved on).
if (document.activeElement === document.body) {
setBusyVisual._restoreFocus.focus();
}
setBusyVisual._restoreFocus = null;
}
}
/* ============================================================== */
/* Visualization flow: generate -> run -> repair loop */
/* ============================================================== */
// Each repair is a full, slow LLM round-trip. With the sandbox now tolerant of
// invented helpers and transient bad frames (see sandbox-worker.js), genuinely
// unfixable scenes are rarer — so cap repairs at 2 and show the fallback
// sooner instead of burning a third slow call that usually fails the same way.
const MAX_REPAIRS = 2;
// Guaranteed-renderable placeholder for when generation + all repairs fail.
// Without it the canvas sits dead-black under the error message.
const CLIENT_FALLBACK_CODE = [
'H.background();',
'H.text("Couldn\'t render this prompt", 28, 40, { color: H.colors.ink, size: 20, weight: 700 });',
'H.text("The model\'s code kept failing. Rephrase the prompt or try again.", 28, 64, { color: H.colors.sub, size: 13 });',
'const cx = H.W / 2, cy = H.H / 2 + 20;',
'const r = 60 + 16 * Math.sin(t * 1.5);',
'H.circle(cx, cy, r, { stroke: H.colors.accent, width: 3 });',
'H.circle(cx, cy, r * 0.6, { stroke: H.colors.accent2, width: 2 });',
'H.circle(cx, cy, 6, { fill: H.colors.ink });',
].join("\n");
const ENGINE_NAMES = {
claude: "Claude",
openai: "ChatGPT",
gemini: "Gemini",
ollama: "local model",
library: "curated library",
fallback: "fallback",
};
function engineName(engine) {
return ENGINE_NAMES[engine] || "the model";
}
// A live elapsed-seconds ticker so a slow local-model generation reads as
// "working" rather than "frozen". Updates the status line in place.
let _elapsedTimer = null;
function startElapsed(baseLabel) {
stopElapsed();
const t0 = Date.now();
const tick = () => {
const s = Math.round((Date.now() - t0) / 1000);
setConfidence(`${baseLabel} (${s}s)`, "pending");
};
tick();
_elapsedTimer = setInterval(tick, 1000);
}
function stopElapsed() {
if (_elapsedTimer) {
clearInterval(_elapsedTimer);
_elapsedTimer = null;
}
}
async function visualize(prompt) {
if (state.busy) return;
const clean = (prompt || "").trim();
if (!clean) return;
setBusyVisual(true, "Thinking…");
el.topic.textContent = "Generating…";
// Elapsed ticker — local generation can take 10-60s; a live counter makes
// the wait legible instead of looking hung. (Curated/cached hits return so
// fast the ticker never visibly advances.)
startElapsed("The AI is writing a custom animation for your prompt…");
// A new scene always starts playing. Without this, pausing one scene
// left every FUTURE scene frozen on its first frame — which reads as
// "the animation doesn't move" rather than "I paused it earlier".
if (runner.paused) {
runner.resume();
el.playPause.textContent = "Pause";
}
try {
const scene = await postJSON("/api/visualize", {
prompt: clean,
preferred_mode: state.mode,
});
stopElapsed();
await runSceneWithRepair(scene, clean);
} catch (err) {
stopElapsed();
setConfidence("Could not generate: " + err.message, "warn");
el.topic.textContent = "Generation failed";
el.summary.textContent = err.message;
// Re-check which backend is alive — the failure often means the badge
// is now stale (Ollama died, Claude key expired, server restarted, etc.).
refreshStatus();
} finally {
stopElapsed();
setBusyVisual(false);
}
}
// Show the guaranteed-renderable placeholder under a warning. Used whenever
// the repair loop gives up — budget exhausted, or non-convergence detected
// (repeated identical error, or the model returned the code unchanged).
async function showClientFallback(scene, message) {
if (scene) {
state.scene = scene;
updatePanels(scene);
}
setConfidence(message, "warn");
try {
await runner.run(CLIENT_FALLBACK_CODE);
} catch (fallbackErr) {
/* placeholder is hand-written and can't realistically fail */
}
}
async function runSceneWithRepair(scene, prompt) {
let current = scene;
let prevError = null;
for (let attempt = 0; attempt <= MAX_REPAIRS; attempt++) {
const engineLabel = engineName(current.engine);
try {
if (!current.code || !current.code.trim()) {
throw new Error("No animation code was produced.");
}
setConfidence(
attempt === 0
? `Running ${current.dimension} scene from ${engineLabel}…`
: `Repair ${attempt}/${MAX_REPAIRS}: trying the fixed code…`,
"pending"
);
await runner.run(current.code);
state.scene = current;
updatePanels(current);
if (current.is_fallback) {
// Server gave us a guaranteed-renderable placeholder because the real
// generator produced blank code three times. Surface it clearly —
// otherwise the user sees the breathing-circle placeholder and
// a confidence message that claims it was "generated by local model".
setConfidence(
"Fallback scene — the model didn't draw anything. " +
(current.summary || "Try rephrasing or enable Claude."),
"warn",
);
} else if (current.quality_warnings && current.quality_warnings.length) {
const issues = current.quality_warnings
.map((w) => (w === "static" ? "may not animate" : "may lack labels"))
.join(", ");
setConfidence(
`${current.dimension} • generated by ${engineLabel} — heads-up: ${issues}. ` +
"Regenerate or rephrase for a better scene.",
"warn",
);
} else if (current.from_library) {
// Instant, hand-verified scene from the curated STEM corpus.
setConfidence(
`${current.dimension} • curated STEM scene (instant, verified)` +
(current.fallback_reason ? " — " + current.fallback_reason : ""),
"ok",
);
} else if (current.recovered_after_retry) {
const n = current.recovered_after_retry;
setConfidence(
`${current.dimension} • generated by ${engineLabel}` +
(current.model ? " (" + current.model + ")" : "") +
` — recovered after ${n} retr${n === 1 ? "y" : "ies"}`,
"ok",
);
} else {
setConfidence(
`${current.dimension} • generated by ${engineLabel}` +
(current.model ? " (" + current.model + ")" : "") +
(current.cached ? " — instant (cached)" : ""),
"ok"
);
}
seedTutorForScene(current);
return;
} catch (err) {
// Non-convergence guard: if this error follows a repair and matches the
// PREVIOUS attempt's error, the repairs aren't making progress — bail
// now instead of grinding through the rest of the (slow) repair budget.
const stuck = attempt > 0 && err.message === prevError;
prevError = err.message;
if (attempt >= MAX_REPAIRS || stuck) {
await showClientFallback(
current,
(stuck
? `The fix kept hitting the same error ("${err.message}") — stopping early. `
: `Couldn't fix it after ${MAX_REPAIRS} tries. Last error: ${err.message}. `) +
"Try a different prompt, or set ANTHROPIC_API_KEY for the stronger Claude generator."
);
return;
}
setConfidence(
`Animation error: "${err.message}". Asking ${engineLabel} for a fix…`,
"pending"
);
const triedCode = current.code;
try {
current = await postJSON("/api/repair", {
prompt,
code: current.code,
error: err.message,
where: err.where || "",
});
} catch (repairErr) {
setConfidence("Repair failed: " + repairErr.message, "warn");
return;
}
// Unchanged-code guard: the model returned the same code it was given,
// so re-running it would fail identically — stop rather than spend
// another slow round on a guaranteed repeat.
if (current.code && triedCode && current.code.trim() === triedCode.trim()) {
await showClientFallback(
current,
"The model returned the same code unchanged — stopping early. " +
"Try rephrasing the prompt."
);
return;
}
}
}
}
/* ============================================================== */
/* Tutor chat */
/* ============================================================== */
function renderChat() {
// Differential render: append new messages and refresh changed ones in
// place. A full innerHTML rebuild looks like "removed all + added all"
// to the aria-live="polite" region, which makes screen readers
// re-announce the entire conversation on every send.
const list = el.chatMessages;
// Shrunk (e.g., seedTutorForScene replaced everything) — wipe and start over.
if (list.children.length > state.chat.length) {
list.replaceChildren();
}
for (let i = 0; i < state.chat.length; i++) {
const msg = state.chat[i];
const key = `${msg.role}|${msg.pending ? "1" : "0"}|${msg.content}`;
let div = list.children[i];
if (!div) {
div = document.createElement("div");
list.appendChild(div);
} else if (div.dataset.key === key) {
continue; // unchanged — leave the DOM (and the screen reader) alone
}
div.dataset.key = key;
div.className = "chat-message " + msg.role + (msg.pending ? " pending" : "");
// Pending bubbles are visual placeholders; hide from the AT tree so
// screen readers don't announce "Thinking…" and then re-announce when
// the real answer replaces it. The container's aria-busy below carries
// the loading state.
if (msg.pending) div.setAttribute("aria-hidden", "true");
else div.removeAttribute("aria-hidden");
const who = document.createElement("span");
who.className = "chat-role";
who.textContent = msg.role === "user" ? "You" : "Tutor";
const body = document.createElement("p");
body.className = "chat-body";
body.innerHTML = renderTutorMarkdown(msg.content);
div.replaceChildren(who, body);
}
// Tell SRs the chat region is awaiting a response when any bubble is pending.
list.setAttribute(
"aria-busy",
state.chat.some((m) => m.pending) ? "true" : "false",
);
list.scrollTop = list.scrollHeight;
}
// Bumped every time the chat is wiped (seedTutorForScene). sendChat captures
// this at start; if it changes before the response lands, an unrelated reset
// happened (e.g. a new scene loaded) and we must NOT pop/push into the new
// chat — that ate the seed and orphaned the user's question.
let chatSessionId = 0;
function seedTutorForScene(scene) {
chatSessionId++;
state.chat = [
{
role: "assistant",
content:
`This is "${scene.title}". ${scene.summary} ` +
"Ask me anything about what you're seeing, the math behind it, or for a practice problem.",
},
];
renderChat();
}
function renderSuggestions(scene) {
el.chatSuggestions.innerHTML = "";
(scene.student_prompts || []).slice(0, 4).forEach((prompt) => {
const btn = document.createElement("button");
btn.className = "suggestion-chip";
btn.type = "button";
btn.textContent = prompt;
btn.addEventListener("click", () => {
el.chatInput.value = prompt;
el.chatInput.focus();
});
el.chatSuggestions.appendChild(btn);
});
}
async function sendChat(question) {
const clean = (question || "").trim();
if (!clean || state.chatBusy) return;
state.chatBusy = true;
el.sendChat.disabled = true;
state.chat.push({ role: "user", content: clean });
state.chat.push({ role: "assistant", content: "Thinking…", pending: true });
renderChat();
const history = state.chat
.filter((m) => !m.pending)
.map((m) => ({ role: m.role, content: m.content }))
.slice(-6);
const session = chatSessionId;
try {
const data = await postJSON("/api/chat", {
question: clean,
visualization: state.scene || {},
history: history.slice(0, -1),
});
if (session !== chatSessionId) return; // chat was reset; discard response
state.chat.pop();
state.chat.push({ role: "assistant", content: data.answer });
} catch (err) {
if (session !== chatSessionId) return;
state.chat.pop();
state.chat.push({ role: "assistant", content: "Tutor unavailable: " + err.message });
// Same reasoning as visualize(): the failure usually means the badge
// is now stale.
refreshStatus();
} finally {
state.chatBusy = false;
el.sendChat.disabled = false;
renderChat();
}
}
/* ============================================================== */
/* Status */
/* ============================================================== */
async function refreshStatus() {
try {
const health = await fetch("/api/health").then((r) => r.json());
state.health = health;
const gen = health.generator;
if (gen === "claude") {
el.statusBadge.textContent = "Claude online";
el.statusBadge.className = "status-pill ok";
el.modelLabel.textContent = "Generator: " + (health.claude.model || "claude");
} else if (gen === "openai") {
el.statusBadge.textContent = "ChatGPT online";
el.statusBadge.className = "status-pill ok";
el.modelLabel.textContent = "Generator: " + (health.openai.model || "openai");
} else if (gen === "gemini") {
el.statusBadge.textContent = "Gemini online";
el.statusBadge.className = "status-pill ok";
el.modelLabel.textContent = "Generator: " + (health.gemini.model || "gemini");
} else if (gen === "ollama") {
el.statusBadge.textContent = "Local model";
el.statusBadge.className = "status-pill ok";
el.modelLabel.textContent = "Generator: " + (health.ollama.selected_model || "ollama");
} else {
el.statusBadge.textContent = "No generator";
el.statusBadge.className = "status-pill error";
el.modelLabel.textContent =
"Set ANTHROPIC_API_KEY / OPENAI_API_KEY / GEMINI_API_KEY or start Ollama";
}
} catch (err) {
el.statusBadge.textContent = "Server offline";
el.statusBadge.className = "status-pill error";
el.modelLabel.textContent = "Could not reach the VisualLM server.";
}
}
/* ============================================================== */
/* Tabs (left panel) */
/* ============================================================== */
function activateTab(name, focusActive) {
const tabs = Array.from(document.querySelectorAll(".tab"));
let activated = null;
tabs.forEach((t) => {
const active = t.dataset.tab === name;
t.classList.toggle("active", active);
t.setAttribute("aria-selected", active ? "true" : "false");
// ARIA tablist: only the active tab is in the Tab order.
t.tabIndex = active ? 0 : -1;
if (active) activated = t;
});
document.querySelectorAll(".tab-panel").forEach((p) => {
const active = p.dataset.panel === name;
p.classList.toggle("active", active);
if (active) p.removeAttribute("hidden");
else p.setAttribute("hidden", "");
});
if (focusActive && activated) activated.focus();
}
(function wireTabs() {
const tabs = Array.from(document.querySelectorAll(".tab"));
// Initialize tabindex so only the currently-active tab is tabbable.
tabs.forEach((t) => {
t.tabIndex = t.classList.contains("active") ? 0 : -1;
});
tabs.forEach((tab, i) => {
tab.addEventListener("click", () => activateTab(tab.dataset.tab));
tab.addEventListener("keydown", (e) => {
let nextIndex = null;
if (e.key === "ArrowLeft" || e.key === "ArrowUp") nextIndex = i - 1;
else if (e.key === "ArrowRight" || e.key === "ArrowDown") nextIndex = i + 1;
else if (e.key === "Home") nextIndex = 0;
else if (e.key === "End") nextIndex = tabs.length - 1;
if (nextIndex === null) return;
e.preventDefault();
const target = tabs[((nextIndex % tabs.length) + tabs.length) % tabs.length];
activateTab(target.dataset.tab, true);
});
});
})();
/* ============================================================== */
/* Resources */
/* ============================================================== */
const resourceEl = {
drop: $("dropZone"),
file: $("resourceFileInput"),
list: $("resourceList"),
empty: $("resourceEmpty"),
count: $("resourceCount"),
};