File size: 55,199 Bytes
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
8501103
 
d686d47
8501103
d686d47
 
 
 
 
52ba0e1
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
 
 
 
 
 
 
 
d686d47
52ba0e1
d686d47
52ba0e1
d686d47
52ba0e1
 
d686d47
 
 
 
 
 
 
52ba0e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
536e671
52ba0e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
536e671
 
52ba0e1
 
 
 
536e671
52ba0e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
 
 
 
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
d686d47
 
 
 
 
52ba0e1
d686d47
 
 
 
52ba0e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d686d47
 
52ba0e1
 
 
 
 
 
 
 
d686d47
 
 
 
 
 
 
 
52ba0e1
 
 
 
 
 
 
 
 
 
 
 
d686d47
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
 
 
 
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8501103
 
 
 
 
 
 
 
 
 
 
d686d47
 
 
52ba0e1
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
d686d47
 
 
52ba0e1
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
 
 
 
 
 
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
 
 
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
 
 
 
 
 
 
 
 
 
d686d47
52ba0e1
 
d686d47
 
 
 
 
52ba0e1
d686d47
 
52ba0e1
 
d686d47
 
52ba0e1
d686d47
52ba0e1
 
 
 
 
 
 
 
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
 
 
 
d686d47
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
d686d47
 
 
 
52ba0e1
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
8501103
 
 
 
 
 
 
 
 
52ba0e1
 
d686d47
52ba0e1
d686d47
 
52ba0e1
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8501103
 
 
 
d686d47
 
 
 
 
 
 
52ba0e1
 
 
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
 
 
d686d47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52ba0e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d686d47
 
 
52ba0e1
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
// RosDiff web app. Plain JS, no build step: talks to the same API the docs describe.

const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];

// ------------------------------------------------------------------ helpers

/** h("div", {class: "x", onclick: fn}, child, "text") -> element. Text is always set safely. */
function h(tag, attrs = {}, ...children) {
  const el = document.createElement(tag);
  for (const [k, v] of Object.entries(attrs || {})) {
    if (v === null || v === undefined || v === false) continue;
    if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2), v);
    else if (k === "class") el.className = v;
    else if (k === "html") el.innerHTML = v; // only ever used with our own static SVG strings
    else el.setAttribute(k, v === true ? "" : v);
  }
  for (const c of children.flat()) {
    if (c === null || c === undefined || c === false) continue;
    el.append(c instanceof Node ? c : document.createTextNode(String(c)));
  }
  return el;
}

const ICON = {
  check: '<svg viewBox="0 0 24 24"><path d="m5 12.5 4.5 4.5L19 7.5"/></svg>',
  cross: '<svg viewBox="0 0 24 24"><path d="M7 7l10 10M17 7 7 17"/></svg>',
  warn: '<svg viewBox="0 0 24 24"><path d="M12 8v5m0 3.5v.01"/></svg>',
  sim: '<svg viewBox="0 0 24 24"><path d="M12 3 4 7.5v9L12 21l8-4.5v-9L12 3Zm0 0v18M4 7.5l8 4.5 8-4.5"/></svg>',
  code: '<svg viewBox="0 0 24 24"><path d="m8 7-5 5 5 5m8-10 5 5-5 5"/></svg>',
  play: '<svg viewBox="0 0 24 24"><path d="M8 5.5v13l10-6.5-10-6.5Z"/></svg>',
  download: '<svg viewBox="0 0 24 24"><path d="M12 4v11m0 0 4.5-4.5M12 15l-4.5-4.5M5 19h14"/></svg>',
  external: '<svg viewBox="0 0 24 24"><path d="M14 5h5v5M19 5l-8 8M17 14v5H5V7h5"/></svg>',
  copy: '<svg viewBox="0 0 24 24"><path d="M9 9h10v10H9zM5 15V5h10"/></svg>',
  bolt: '<svg viewBox="0 0 24 24"><path d="M13 3 5 13.5h6L10 21l8-10.5h-6L13 3Z"/></svg>',
  wrench: '<svg viewBox="0 0 24 24"><path d="M14.5 6.5a4 4 0 0 0-5.3 5.3L4 17l3 3 5.2-5.2a4 4 0 0 0 5.3-5.3l-2.6 2.6-2.4-.6-.6-2.4 2.6-2.6Z"/></svg>',
};
const icon = (name) => h("span", { html: ICON[name], "aria-hidden": "true", style: "display:inline-flex" });

const ROBOTS = [
  { id: "unitree_g1", label: "G1 humanoid", emoji: "🧍" },
  { id: "unitree_h1", label: "H1 humanoid", emoji: "🧍‍♂️" },
  { id: "unitree_go2", label: "Go2 robot dog", emoji: "🐕" },
  { id: "franka_emika_panda", label: "Panda arm", emoji: "🦾" },
];
const robotLabel = (id) => (ROBOTS.find((r) => r.id === id) || { label: id || "no robot" }).label;

const EXAMPLES = {
  sim: [
    ["unitree_g1", "The robot stands 1.5 m in front of a staircase with 3 steps, each 15 cm high and 30 cm deep."],
    ["unitree_go2", "The dog is on a floor with three low boxes (10 cm tall) spread 1–2 m ahead of it."],
    ["franka_emika_panda", "The arm stands next to a table 0.4 m high with three small coloured cubes on it."],
    ["unitree_h1", "The humanoid faces a doorway 0.9 m wide between two walls, with a 2 kg box just past it."],
  ],
  code: [
    "Stop the robot when the laser scanner sees something closer than 0.5 m, by publishing zero velocity on /cmd_vel.",
    "A service that adds two integers, plus a small client node that calls it once a second.",
    "Read the IMU on /imu and publish a smoothed (low-pass filtered) version on /imu/filtered.",
    "Record the robot's /odom positions and publish them as a nav_msgs/Path on /trail.",
  ],
};

const TERMINAL = new Set(["COMPLETED", "FAILED", "CANCELLED", "TIMED_OUT"]);

class ApiError extends Error {
  constructor(status, detail) {
    super(typeof detail === "string" ? detail : JSON.stringify(detail));
    this.status = status;
    this.detail = detail;
  }
}

function friendly(err) {
  if (!(err instanceof ApiError)) return "Can't reach the RosDiff server. Check your connection and try again.";
  const d = err.detail;
  const msg = typeof d === "string" ? d : d?.message || err.message;
  switch (err.status) {
    case 401: return "Your key isn't recognised. Sign out and sign in again.";
    case 402: return /budget/i.test(msg || "") ? msg : "This month's shared compute credit is used up. Please tell the Orcanion team.";
    case 429: return "Today's limit for this is reached. Try again tomorrow.";
    case 503: return "This part isn't switched on on the server yet.";
    case 507: return "Result storage is full for now. Old results are cleared automatically; try again later.";
    case 502: return "The AI or the cloud GPU had a problem: " + msg;
    case 422:
      if (Array.isArray(d)) return "Please check what you typed: " + d.map((x) => x.msg).join("; ");
      return msg;
    default: return msg || "Something went wrong.";
  }
}

// ------------------------------------------------------------------ API

let savedKey; try { savedKey = localStorage.getItem("rosdiff_key"); } catch {}

const state = {
  key: savedKey || "",
  tester: "",
  robot: localStorage.getItem("rosdiff_robot") || "unitree_g1",
  distro: localStorage.getItem("rosdiff_distro") || "humble",
  lang: localStorage.getItem("rosdiff_lang") || "python",
  busy: { sim: false, code: false },
  rated: {}, // job id -> helpful | not_helpful (this session)
};
function remember(k, v) { try { localStorage.setItem(k, v); } catch { /* private mode */ } }

async function api(path, { method = "GET", body, raw = false } = {}) {
  let res;
  try {
    res = await fetch(path, {
      method,
      headers: { "X-API-Key": state.key, ...(body ? { "content-type": "application/json" } : {}) },
      body: body ? JSON.stringify(body) : undefined,
    });
  } catch {
    throw new Error("network");
  }
  if (!res.ok) {
    let detail = res.statusText;
    try { detail = (await res.json()).detail ?? detail; } catch { /* not json */ }
    if (res.status === 401 && !path.startsWith("/me/history")) signOut(true);
    throw new ApiError(res.status, detail);
  }
  return raw ? res : res.json();
}

function toast(text) {
  const t = $("#toast");
  t.textContent = text;
  t.hidden = false;
  clearTimeout(toast.timer);
  toast.timer = setTimeout(() => (t.hidden = true), 3200);
}

function download(name, blob) {
  const a = h("a", { href: URL.createObjectURL(blob), download: name });
  document.body.append(a);
  a.click();
  a.remove();
  setTimeout(() => URL.revokeObjectURL(a.href), 2000);
}

// ------------------------------------------------------------------ syntax highlighting (small, safe)

const KW = {
  python: "def class import from return if elif else for while in not and or is None True False self with as try except finally raise lambda pass yield super",
  cpp: "include class struct public private protected return if else for while auto const void int double float bool true false nullptr namespace using std new delete override virtual static template typename this",
  cmake: "cmake_minimum_required project find_package add_executable ament_target_dependencies install ament_package if endif set target_link_libraries ament_lint_auto_find_test_dependencies DESTINATION TARGETS DIRECTORY REQUIRED",
};
function langFor(path) {
  if (/\.py$/.test(path)) return "python";
  if (/\.(cpp|hpp|cc|h)$/.test(path)) return "cpp";
  if (/CMakeLists\.txt$|\.cmake$/.test(path)) return "cmake";
  if (/\.(xml|urdf|xacro|launch)$/.test(path)) return "xml";
  if (/\.ya?ml$|\.cfg$/.test(path)) return "yaml";
  return "text";
}
function tokenize(code, lang) {
  let re;
  if (lang === "xml") re = /(<!--[\s\S]*?-->)|("[^"]*"|'[^']*')|(<\/?[\w:.-]+|\/?>)()/g;
  else if (lang === "text") return [{ cls: "", text: code }];
  else {
    const comment = lang === "cpp" ? String.raw`//.*$|/\*[\s\S]*?\*/` : String.raw`#.*$`;
    const kw = KW[lang] ? String.raw`\b(?:${KW[lang].split(" ").join("|")})\b` : "(?!x)x";
    re = new RegExp(String.raw`(${comment})|("""[\s\S]*?"""|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*')|(${kw})|(\b\d+(?:\.\d+)?\b)`, "gm");
  }
  const out = [];
  let last = 0;
  for (const m of code.matchAll(re)) {
    if (m.index > last) out.push({ cls: "", text: code.slice(last, m.index) });
    const cls = m[1] ? "hl-c" : m[2] ? "hl-s" : m[3] ? (lang === "xml" ? "hl-t" : "hl-k") : "hl-n";
    out.push({ cls, text: m[0] });
    last = m.index + m[0].length;
    if (m[0].length === 0) re.lastIndex++;
  }
  if (last < code.length) out.push({ cls: "", text: code.slice(last) });
  return out;
}
function codeBlock(code, lang) {
  const pre = h("pre", { class: "code" });
  let line = h("span", { class: "ln" });
  for (const tok of tokenize(code.replace(/\n$/, ""), lang)) {
    const parts = tok.text.split("\n");
    parts.forEach((part, i) => {
      if (i > 0) {
        pre.append(line);
        line = h("span", { class: "ln" });
      }
      if (part) line.append(tok.cls ? h("span", { class: tok.cls }, part) : document.createTextNode(part));
    });
  }
  pre.append(line);
  return h("div", { class: "code-scroll" }, pre);
}

// ------------------------------------------------------------------ cards

function statusIcon(kind) {
  if (kind === "busy") return h("span", { class: "status-icon busy" }, h("span", { class: "spinner" }));
  return h("span", { class: `status-icon ${kind}`, html: kind === "ok" ? ICON.check : kind === "bad" ? ICON.cross : ICON.warn });
}

function workingCard(steps) {
  const text = h("span", { class: "shimmer" }, steps[0]);
  const card = h("div", { class: "card" }, h("div", { class: "card-head" }, statusIcon("busy"), h("div", { class: "working" }, text)));
  let i = 0;
  card._timer = setInterval(() => { i = (i + 1) % steps.length; text.textContent = steps[i]; }, 5000);
  card.stop = () => clearInterval(card._timer);
  return card;
}

// 👍 / 👎 on a scene, a package or a job, with an optional note. Stored with what RosDiff did for it.
function feedbackBar(type, id, current) {
  const cur = current === "works" || current === "helpful" ? "helpful" : current ? "not_helpful" : null;
  const wrap = h("div", { class: "feedback", role: "group", "aria-label": "Was this helpful?" });
  const opts = [["helpful", "👍", "Helpful"], ["not_helpful", "👎", "Not helpful"]];
  for (const [rating, emoji, label] of opts) {
    const b = h("button", { class: "fb" + (cur === rating ? " chosen" : ""), type: "button", title: label, "aria-pressed": String(cur === rating) },
      h("span", { "aria-hidden": "true" }, emoji), h("span", { class: "fb-label" }, label));
    b.addEventListener("click", async () => {
      const note = await askNote(rating);
      try {
        await api("/feedback", { method: "POST", body: { target_type: type, target_id: id, rating, note } });
        $$(".fb", wrap).forEach((x) => { x.classList.toggle("chosen", x === b); x.setAttribute("aria-pressed", String(x === b)); });
        if (type === "job") state.rated[id] = rating;
        toast(note ? "Thanks, we read every note!" : "Thanks for the feedback!");
      } catch (e) { toast(friendly(e)); }
    });
    wrap.append(b);
  }
  return wrap;
}

function askNote(rating) {
  const d = $("#fb-dialog");
  const ta = $("#fb-note");
  ta.value = "";
  $("#fb-title").textContent = rating === "helpful" ? "Glad it helped! Anything we could do better?" : "Tell us what went wrong or how we can improve";
  return new Promise((resolve) => {
    d.addEventListener("close", () => resolve(d.returnValue === "send" ? ta.value.trim() : ""), { once: true });
    d.returnValue = "";
    d.showModal();
    ta.focus();
  });
}
$("#fb-form").addEventListener("submit", (e) => { e.preventDefault(); $("#fb-dialog").close("send"); });
$("#fb-skip").addEventListener("click", () => $("#fb-dialog").close("skip"));

// ------------------------------------------------------------------ routing, simulators, cost

const TIER_TEXT = { low: "Fast", mid: "Standard", high: "High reasoning", free: "Free debugger" };
const SIMS = [
  { id: "mujoco", label: "MuJoCo", what: "One run with video and a 3D replay", verb: "Run in MuJoCo", on: true },
  { id: "mujoco_warp", label: "MuJoCo Warp", what: "64 randomized copies at once on the GPU: how often does it work?", verb: "Stress test in MuJoCo Warp", on: true },
  { id: "isaac_sim", label: "Isaac Sim", what: "Runs in MuJoCo, then a photoreal RTX render of the same motion", verb: "Run + render in Isaac Sim", on: true },
  { id: "gazebo", label: "Gazebo", what: "Not available in RosDiff yet", on: false },
  { id: "webots", label: "Webots", what: "Not available in RosDiff yet", on: false },
  { id: "pybullet", label: "PyBullet", what: "Not available in RosDiff yet", on: false },
];
const simInfo = (id) => SIMS.find((x) => x.id === id) || SIMS[0];

// "AI Routing: automatic · Standard tier · Why?" — information only; nobody has to pick a model.
// The sharper brief the generator actually worked from (made for free by OpenCode Zen).
function enhancedBlock(e) {
  if (!e?.used || !e.text) return null;
  return h("details", { class: "enhanced" }, h("summary", {}, "✨ Enhanced prompt"),
    h("div", { class: "why" }, e.text, h("div", { class: "muted small", style: "margin-top:6px" }, "Written for free with OpenCode Zen; it doesn't use your budget.")));
}

function routingLine(r, cost) {
  if (!r) return null;
  const tiers = r.tiers_used?.length ? r.tiers_used : [r.tier];
  const paidTiers = tiers.filter((t) => t in TIER_TEXT && t !== "free");
  const final = paidTiers.length ? paidTiers[paidTiers.length - 1] : r.tier;
  const models = [...new Set((r.models || []).filter(Boolean))];
  const why = h("span", { class: "why" },
    h("div", {}, `Reason: ${r.reason}${r.complexity ? ` (rated ${r.complexity})` : ""}.`),
    h("div", {}, `Capability tier: ${TIER_TEXT[r.tier] || r.tier}` + (r.escalated ? ` → raised to ${TIER_TEXT[final]} to fix a failed check` : "")),
    r.free_debug ? h("div", {}, "A fix was tried with a free DeepSeek model first (OpenCode Zen, not charged).") : null,
    r.simulator ? h("div", {}, `Simulator: ${simInfo(r.simulator).label}, ${r.simulator_reason}.`) : null,
    models.length ? h("div", { class: "muted small" }, `Model${models.length > 1 ? "s" : ""}: ${models.join(", ")}`) : null,
    cost ? h("div", {}, `This task used ${rupees(cost.inr)} (estimated ${rupees(cost.estimate_inr[0])}–${rupees(cost.estimate_inr[1])}). You have ${rupees(cost.budget.remaining)} of ${rupees(cost.budget.allocation)} left.`) : null);
  return h("div", { class: "routing" },
    h("span", { class: "auto" }, "AI Routing: automatic"),
    h("span", {}, `${TIER_TEXT[final] || final} tier`),
    cost ? h("span", {}, `· used ${rupees(cost.inr)}`) : null,
    h("details", {}, h("summary", {}, "Why?"), why));
}

// "Estimated usage: ₹8–₹12. Your remaining budget: ₹42 / ₹125. [Run]" — only for tasks above the threshold.
function confirmCard(detail, run, cancel) {
  const [lo, hi] = detail.estimate_inr || [0, 0];
  const b = detail.budget || {};
  const go = h("button", { class: "btn btn-primary btn-sm", type: "button" }, icon("play"), "Run");
  const no = h("button", { class: "btn btn-sm btn-ghost", type: "button" }, "Cancel");
  const card = h("div", { class: "card" },
    h("div", { class: "card-head" }, statusIcon("warn"),
      h("div", {}, h("div", { class: "title" }, "Estimated usage"), h("div", { class: "sub" }, "This is a bigger task, so RosDiff checks with you first."))),
    h("div", { class: "card-body confirm" },
      h("div", {}, "This task is expected to consume approximately"),
      h("div", { class: "big" }, `${rupees(lo)} – ${rupees(hi)}`),
      h("div", { class: "muted small" }, `Your remaining budget: ${rupees(b.remaining ?? 0)} / ${rupees(b.allocation ?? 0)}. Only what it actually uses is charged.`)),
    h("div", { class: "card-actions" }, go, no));
  go.addEventListener("click", () => { go.disabled = no.disabled = true; run(); });
  no.addEventListener("click", () => { go.disabled = no.disabled = true; cancel(); });
  return card;
}

document.addEventListener("click", (e) => {
  $$(".sim-menu").forEach((m) => {
    if (m.hidden || m.contains(e.target) || m._owner.contains(e.target)) return;
    m.hidden = true;
    m._owner.setAttribute("aria-expanded", "false");
  });
});

function errorCard(message) {
  return h("div", { class: "card" }, h("div", { class: "card-head" }, statusIcon("bad"), h("div", {}, h("div", { class: "title" }, "That didn't work"), h("div", { class: "sub" }, message))));
}

function userMessage(text, meta) {
  return h("div", { class: "msg-user" }, text, meta ? h("span", { class: "meta" }, meta) : null);
}

// --- simulation

function sceneCard(gen) {
  const ok = gen.valid;
  const val = gen.validation || {};
  const stats = val.stats || {};
  const head = h("div", { class: "card-head" }, statusIcon(ok ? "ok" : "bad"),
    h("div", {},
      h("div", { class: "title" }, ok ? "Scene ready" : "Couldn't build a working scene"),
      h("div", { class: "sub" }, ok ? `Loads and simulates in MuJoCo · ${robotLabel(gen.robot)}` : "MuJoCo rejected every attempt")));
  const body = h("div", { class: "card-body" });
  const route = routingLine(gen.routing, gen.cost);
  if (route) body.append(route);
  const brief = enhancedBlock(gen.enhanced_prompt);
  if (brief) body.append(brief);
  if (ok) {
    body.append(h("div", { class: "facts" },
      h("span", { class: "pill" }, `${stats.nbody ?? "?"} bodies`),
      h("span", { class: "pill" }, `${stats.ngeom ?? "?"} shapes`),
      (val.warnings || []).length ? h("span", { class: "pill warn" }, `${val.warnings.length} warning(s)`) : h("span", { class: "pill ok" }, "no warnings")));
  } else {
    body.append(h("div", { class: "error-box" }, val.error || gen.error || "Unknown problem"));
  }
  if (gen.mjcf) {
    body.append(h("details", { class: "xml" }, h("summary", {}, "Show the scene file (MJCF XML)"),
      h("div", { class: "code-view" }, codeBlock(gen.mjcf, "xml"))));
  }
  const actions = h("div", { class: "card-actions" });
  const runs = h("div", { class: "runs" });
  if (ok) actions.append(...simPicker(gen, runs));
  if (gen.mjcf) {
    const dl = h("button", { class: "btn btn-sm", type: "button" }, icon("download"), "Download");
    dl.addEventListener("click", () => download(`scene_${gen.id}.xml`, new Blob([gen.mjcf], { type: "application/xml" })));
    actions.append(dl);
  }
  actions.append(h("span", { class: "spacer" }), feedbackBar("generation", gen.id, gen.rating));
  const wrap = h("div", { style: "display:flex;flex-direction:column;gap:14px" }, h("div", { class: "card" }, head, body, actions), runs);
  return wrap;
}

// The simulator RosDiff chose, as the main button, plus "Use another simulator".
function simPicker(gen, runs) {
  const auto = gen.routing?.simulator || "mujoco";
  let chosen = auto;
  const run = h("button", { class: "btn btn-primary btn-sm", type: "button" }, icon("play"), h("span", {}, simInfo(chosen).verb));
  run.addEventListener("click", () => startRun(gen, runs, run, chosen));
  const menu = h("div", { class: "sim-menu", role: "menu", hidden: true },
    h("div", { class: "muted small", style: "padding:6px 10px 4px" }, `RosDiff picked ${simInfo(auto).label} for this scene.`));
  const other = h("button", { class: "btn btn-sm btn-ghost", type: "button", "aria-haspopup": "menu", "aria-expanded": "false" }, "Use another simulator");
  const paint = () => $$(".sim-opt", menu).forEach((o) => o.classList.toggle("chosen", o.dataset.sim === chosen));
  for (const sim of SIMS) {
    const opt = h("button", { class: "sim-opt", type: "button", role: "menuitemradio", "data-sim": sim.id, disabled: !sim.on },
      h("b", {}, sim.label + (sim.id === auto ? " · recommended" : "")), h("span", {}, sim.what));
    opt.addEventListener("click", () => {
      chosen = sim.id;
      run.lastChild.textContent = sim.verb;
      paint();
      menu.hidden = true;
      other.setAttribute("aria-expanded", "false");
    });
    menu.append(opt);
  }
  paint();
  other.addEventListener("click", () => { menu.hidden = !menu.hidden; other.setAttribute("aria-expanded", String(!menu.hidden)); });
  menu._owner = other;
  return [run, other, menu]; // the menu opens as a full-width row of the card's action bar
}

async function startRun(gen, container, button, sim = "mujoco") {
  button.disabled = true;
  try {
    if (sim === "mujoco_warp") {
      const job = await api("/simulate/sweep", { method: "POST", body: { generation_id: gen.id, n_worlds: 64 } });
      container.append(jobCard({ id: job.id, kind: "sweep", status: job.status, report_url: job.report_url }));
    } else {
      const job = await api("/simulate/run", { method: "POST", body: { generation_id: gen.id, duration_s: 10, controller: "hold" } });
      const then = sim === "isaac_sim" ? (j) => startIsaac(j.id, container) : null;
      container.append(jobCard({ id: job.run_id, kind: "sim", status: job.status, report_url: job.report_url }, then));
    }
    scrollDown("sim");
  } catch (e) {
    container.append(errorCard(friendly(e)));
  } finally {
    setTimeout(() => (button.disabled = false), 1500);
  }
}

async function startIsaac(runId, container, button) {
  if (button) button.disabled = true;
  try {
    const job = await api(`/simulate/run/${runId}/isaac`, { method: "POST" });
    container.append(jobCard({ id: job.id, kind: "isaac", status: job.status, report_url: job.report_url }));
    scrollDown("sim");
  } catch (e) {
    container.append(errorCard(friendly(e)));
    if (button) button.disabled = false;
  }
}

// --- code

function packageCard(gen) {
  const ok = gen.valid;
  const val = gen.validation || {};
  const files = gen.files || {};
  const names = Object.keys(files);
  const head = h("div", { class: "card-head" }, statusIcon(ok ? "ok" : names.length ? "warn" : "bad"),
    h("div", {},
      h("div", { class: "title" }, ok ? "Package ready" : names.length ? "Package written, with problems" : "Couldn't write the package"),
      h("div", { class: "sub" }, `${names.length} file(s) · ROS 2 ${gen.distro || ""} · ${gen.language === "cpp" ? "C++" : "Python"}`)));
  const body = h("div", { class: "card-body" });
  const route = routingLine(gen.routing, gen.cost);
  if (route) body.append(route);
  const brief = enhancedBlock(gen.enhanced_prompt);
  if (brief) body.append(brief);
  const errors = val.errors || [];
  if (errors.length) body.append(h("div", { class: "error-box" }, errors.slice(0, 6).join("\n")));
  if ((val.warnings || []).length) body.append(h("p", { class: "note" }, `${val.warnings.length} note(s): ${val.warnings.slice(0, 2).join("; ")}`));
  if (names.length) {
    const tabs = h("div", { class: "tabs", role: "tablist" });
    const view = h("div");
    const show = (name) => {
      $$(".tab", tabs).forEach((t) => { const on = t.dataset.name === name; t.classList.toggle("active", on); t.setAttribute("aria-selected", String(on)); });
      view.replaceChildren(codeBlock(files[name], langFor(name)));
      view.dataset.current = name;
    };
    const order = names.slice().sort((a, b) => score(a) - score(b) || a.localeCompare(b));
    for (const name of order) {
      tabs.append(h("button", { class: "tab", type: "button", role: "tab", "data-name": name, title: name, onclick: () => show(name) }, name.split("/").slice(-1)[0]));
    }
    body.append(h("div", { class: "code-view" }, tabs, view));
    show(order[0]);
    body._view = view;
  }
  const actions = h("div", { class: "card-actions" });
  const checks = h("div", { class: "runs" });
  if (names.length) {
    const check = h("button", { class: "btn btn-primary btn-sm", type: "button" }, icon("wrench"), "Build & run");
    check.addEventListener("click", () => startCheck(gen, checks, check));
    const zip = h("button", { class: "btn btn-sm", type: "button" }, icon("download"), "Download .zip");
    zip.addEventListener("click", async () => {
      try { download(`rosdiff-${gen.id}.zip`, await (await api(`/code/${gen.id}/zip`, { raw: true })).blob()); }
      catch (e) { toast(friendly(e)); }
    });
    const copy = h("button", { class: "btn btn-sm btn-ghost", type: "button", title: "Copy the open file" }, icon("copy"), "Copy");
    copy.addEventListener("click", async () => {
      const name = body._view?.dataset.current;
      try {
        if (navigator.clipboard) {
          await navigator.clipboard.writeText(files[name]);
        } else {
          const ta = document.createElement("textarea");
          ta.value = files[name]; ta.style.position = "fixed"; ta.style.left = "-9999px";
          document.body.appendChild(ta); ta.select(); document.execCommand("copy");
          document.body.removeChild(ta);
        }
        toast("Copied!");
      } catch { toast("Couldn't copy"); }
    });
    actions.append(check, zip, copy);
  }
  actions.append(h("span", { class: "spacer" }), feedbackBar("generation", gen.id, gen.rating));
  return h("div", { style: "display:flex;flex-direction:column;gap:14px" }, h("div", { class: "card" }, head, body, actions), checks);
}
function score(path) {
  if (/launch/.test(path)) return 1;
  if (/\.(py|cpp)$/.test(path) && !/(setup|__init__)\.py$/.test(path)) return 0;
  if (/package\.xml$/.test(path)) return 2;
  return 3;
}

async function startCheck(gen, container, button) {
  button.disabled = true;
  try {
    const job = await api("/code/check", { method: "POST", body: { generation_id: gen.id } });
    container.append(jobCard({ id: job.id, kind: "ros_check", status: job.status, report_url: job.report_url }));
    scrollDown("code");
  } catch (e) {
    container.append(errorCard(friendly(e)));
  } finally {
    setTimeout(() => (button.disabled = false), 1500);
  }
}

// --- background jobs (runs, checks, stress tests) with live status

const JOB_TEXT = {
  sim: { wait: "Waiting for a cloud GPU… (the first run can take a minute or two)", run: "Simulating and recording the video…", title: "Simulation" },
  sweep: { wait: "Starting the stress test…", run: "Running many variations at once on the GPU…", title: "Stress test" },
  ros_check: { wait: "Starting a ROS 2 machine…", run: "Building, testing and running your package for 10 s…", title: "Build & run" },
  review: { wait: "Waiting for the video reviewer…", run: "Watching the video…", title: "AI review" },
  isaac: { wait: "Starting Isaac Sim…", run: "Rendering with Isaac Sim…", title: "Isaac Sim render" },
  export: { wait: "Starting the export…", run: "Building the dataset…", title: "Dataset export" },
};

function jobCard(job, onComplete) {
  const card = h("div", { class: "card" });
  card.dataset.job = job.id;
  const render = (j) => {
    if (j.status === "COMPLETED" && onComplete) { const f = onComplete; onComplete = null; f(j); }
    const text = JOB_TEXT[j.kind] || JOB_TEXT.sim;
    card.replaceChildren();
    if (!TERMINAL.has(j.status)) {
      card.append(h("div", { class: "card-head" }, statusIcon("busy"),
        h("div", {}, h("div", { class: "title" }, text.title), h("div", { class: "working" },
          h("span", { class: "shimmer" }, j.status === "IN_PROGRESS" ? text.run : text.wait)))));
      return;
    }
    if (j.status !== "COMPLETED") {
      card.append(h("div", { class: "card-head" }, statusIcon("bad"),
        h("div", {}, h("div", { class: "title" }, `${text.title} failed`), h("div", { class: "sub" }, j.error ? String(j.error).split("\n")[0].slice(0, 220) : j.status.replace("_", " ").toLowerCase()))),
        reportActions(j));
      return;
    }
    if (j.kind === "sim") card.append(...simResult(j));
    else if (j.kind === "ros_check") card.append(...checkResult(j));
    else if (j.kind === "sweep") card.append(...sweepResult(j));
    else {
      const body = h("div", { class: "card-body" });
      if (j.media?.isaac_video) body.append(h("video", { controls: true, autoplay: true, muted: true, loop: true, playsinline: true, preload: "metadata", src: j.media.isaac_video }));
      card.append(h("div", { class: "card-head" }, statusIcon("ok"), h("div", {}, h("div", { class: "title" }, text.title), h("div", { class: "sub" }, j.summary?.headline || "Done"))),
        ...(body.childNodes.length ? [body] : []), reportActions(j));
    }
  };
  render(job);
  poll(job.id, render);
  return card;
}

async function poll(id, render) {
  let delay = 3000;
  for (;;) {
    await new Promise((r) => setTimeout(r, delay));
    if (!document.querySelector(`[data-job="${id}"]`)) return; // card was cleared
    try {
      const j = await api(`/jobs/${id}`);
      render(j);
      if (TERMINAL.has(j.status)) { refreshBudget(); return; }
    } catch { /* keep trying quietly */ }
    delay = Math.min(delay + 1000, 8000);
  }
}

function reportActions(j, ...extra) {
  const bar = h("div", { class: "card-actions" }, ...extra);
  if (j.report_url) bar.append(h("a", { class: "btn btn-sm", href: j.report_url, target: "_blank", rel: "noopener" }, icon("external"), "Full report"));
  if (TERMINAL.has(j.status)) bar.append(h("span", { class: "spacer" }), feedbackBar("job", j.id, state.rated[j.id]));
  return bar;
}

function simResult(j) {
  const s = j.summary || {};
  const media = j.media || {};
  const fell = s.fell;
  const head = h("div", { class: "card-head" }, statusIcon(fell ? "warn" : "ok"),
    h("div", {}, h("div", { class: "title" }, fell ? `The robot fell at ${s.fell_at} s` : "Simulation finished"),
      h("div", { class: "sub" }, `${s.simulated_seconds ?? "?"} s simulated${s.realtime_factor ? ` · ${s.realtime_factor}× real time` : ""}`)));
  const body = h("div", { class: "card-body" });
  if (media.video || media.video_webm) {
    const v = h("video", { controls: true, autoplay: true, muted: true, loop: true, playsinline: true, preload: "metadata" });
    if (media.video_webm) v.append(h("source", { src: media.video_webm, type: "video/webm" }));
    if (media.video) v.append(h("source", { src: media.video, type: "video/mp4" }));
    body.append(v);
  } else if (s.render_error) {
    body.append(h("p", { class: "note" }, "No video this time: " + s.render_error));
  }
  const facts = h("div", { class: "facts", style: "margin-top:10px" });
  if (fell === false) facts.append(h("span", { class: "pill ok" }, "Stayed up"));
  if (fell === true) facts.append(h("span", { class: "pill bad" }, "Fell over"));
  if (s.unstable_at != null) facts.append(h("span", { class: "pill bad" }, `Unstable at ${s.unstable_at} s`));
  if (s.max_contacts != null) facts.append(h("span", { class: "pill" }, `${s.max_contacts} contacts max`));
  body.append(facts);
  const stress = h("button", { class: "btn btn-sm", type: "button", title: "Run 64 slightly different versions (friction, weights, a push) and count how often it falls" }, icon("bolt"), "Stress test");
  const extra = h("div", { class: "runs" });
  stress.addEventListener("click", async () => {
    stress.disabled = true;
    try {
      const job = await api("/simulate/sweep", { method: "POST", body: { run_id: j.id, n_worlds: 64 } });
      extra.append(jobCard({ id: job.id, kind: "sweep", status: job.status, report_url: job.report_url }));
    } catch (e) { extra.append(errorCard(friendly(e))); stress.disabled = false; }
  });
  const isaac = h("button", { class: "btn btn-sm", type: "button", title: "Render this exact run photorealistically with NVIDIA Isaac Sim" }, icon("play"), "Isaac Sim render");
  isaac.addEventListener("click", () => startIsaac(j.id, extra, isaac));
  return [head, body, reportActions(j, stress, isaac), extra];
}

function checkResult(j) {
  const r = j.summary || {};
  const b = r.build || {};
  const la = r.launch;
  const te = r.test;
  const good = r.passed;
  const head = h("div", { class: "card-head" }, statusIcon(good ? "ok" : b.ok ? "warn" : "bad"),
    h("div", {}, h("div", { class: "title" }, good ? "Builds and runs" : b.ok ? "Builds, but didn't run cleanly" : "Doesn't build"),
      h("div", { class: "sub" }, r.headline || "")));
  const body = h("div", { class: "card-body" });
  const facts = h("div", { class: "facts" },
    h("span", { class: "pill " + (b.ok ? "ok" : "bad") }, b.ok ? "✓ Build" : "✗ Build"),
    la ? h("span", { class: "pill " + (la.ok ? "ok" : "bad") }, la.ok ? "✓ Runs" : "✗ Runs") : null,
    te && te.ran ? h("span", { class: "pill " + (te.ok ? "ok" : "warn") }, `Tests ${te.tests - te.failures - te.errors}/${te.tests}`) : null,
    r.lint ? h("span", { class: "pill" + (r.lint.total ? " warn" : " ok") }, r.lint.total ? `${r.lint.total} style note(s)` : "Style clean") : null);
  body.append(facts);
  const errs = [...(b.errors || []), ...((la && la.errors) || [])];
  if (errs.length) body.append(h("div", { class: "error-box" }, errs.slice(0, 6).join("\n")));
  const missing = [...(b.missing_dependencies || []), ...((la && la.missing_dependencies) || [])];
  if (missing.length) body.append(h("p", { class: "note" }, "Missing: " + [...new Set(missing)].join(", ")));
  if (la && la.crashed?.length) body.append(h("p", { class: "note" }, "Crashed: " + la.crashed.join(", ")));
  if (la && (la.nodes?.length || la.topics?.length)) {
    body.append(h("p", { class: "note", style: "margin:10px 0 4px" }, "While it ran:"),
      h("div", { class: "facts" }, ...(la.nodes || []).map((n) => h("span", { class: "pill" }, "● " + n)),
        ...(la.topics || []).slice(0, 12).map((t) => h("span", { class: "pill" }, t.split(" ")[0]))));
  }
  return [head, body, reportActions(j)];
}

function sweepResult(j) {
  const s = j.summary || {};
  const rate = s.fall_rate;
  const head = h("div", { class: "card-head" }, statusIcon(rate == null ? "ok" : rate < 0.2 ? "ok" : rate < 0.6 ? "warn" : "bad"),
    h("div", {}, h("div", { class: "title" }, "Stress test"), h("div", { class: "sub" }, s.headline || "")));
  const body = h("div", { class: "card-body" }, h("p", { class: "note" },
    rate == null ? "" : `Out of ${s.worlds} slightly different versions (friction, object weights and a push), the robot fell in ${s.fell}.`));
  return [head, body, reportActions(j)];
}

// ------------------------------------------------------------------ threads

function thread(pane) { return $(`#thread-${pane}`); }
function scrollDown(pane) { const t = thread(pane); requestAnimationFrame(() => (t.scrollTop = t.scrollHeight)); }

function showEmpty(pane) {
  const t = thread(pane);
  const examples = h("div", { class: "examples" });
  if (pane === "sim") {
    for (const [robot, text] of EXAMPLES.sim) {
      examples.append(h("button", { class: "example", type: "button", onclick: () => { setRobot(robot); fillComposer("sim", text); } },
        h("span", {}, ROBOTS.find((r) => r.id === robot).emoji), text));
    }
  } else {
    for (const text of EXAMPLES.code) {
      examples.append(h("button", { class: "example", type: "button", onclick: () => fillComposer("code", text) }, h("span", {}, "›"), text));
    }
  }
  t.replaceChildren(h("div", { class: "empty" },
    h("h3", {}, pane === "sim" ? "What world should the robot be in?" : "What should your ROS 2 node do?"),
    h("p", { class: "muted small" }, pane === "sim" ? "Pick a robot below, then describe the scene in plain words. Or start from an example:" : "Choose the ROS 2 version and language below, then describe it. Or start from an example:"),
    examples));
}

function clearPane(pane) {
  thread(pane).replaceChildren();
  showEmpty(pane);
  $$(".h-item.active").forEach((x) => x.classList.remove("active"));
}

function fillComposer(pane, text) {
  const input = $(`#input-${pane}`);
  input.value = text;
  autosize(input);
  input.focus();
}

function autosize(el) { el.style.height = "auto"; el.style.height = Math.min(el.scrollHeight, 200) + "px"; }

async function submit(pane) {
  if (state.busy[pane]) return;
  const input = $(`#input-${pane}`);
  const text = input.value.trim();
  if (text.length < 10) { toast("Please describe it in a bit more detail (at least 10 characters)."); input.focus(); return; }
  const t = thread(pane);
  if (t.querySelector(".empty")) t.replaceChildren();
  const meta = pane === "sim" ? robotLabel(state.robot) : `ROS 2 ${cap(state.distro)} · ${state.lang === "cpp" ? "C++" : "Python"}`;
  t.append(userMessage(text, meta));
  input.value = "";
  autosize(input);
  const body = pane === "sim"
    ? { description: text, robot: state.robot }
    : { request: text, distro: state.distro, language: state.lang };
  await generate(pane, body);
}

async function generate(pane, body) {
  state.busy[pane] = true;
  $(`#composer-${pane} .send`).disabled = true;
  const t = thread(pane);
  const steps = pane === "sim"
    ? ["Sharpening your description…", "Choosing the right AI for this scene…", "Reading the MuJoCo documentation…", "Writing the scene…", "Testing it in MuJoCo…", "Fixing anything MuJoCo complained about…", "Almost there…"]
    : ["Sharpening your request…", "Choosing the right AI for this package…", "Looking up the ROS 2 messages it needs…", "Writing the package…", "Checking every message type exists…", "Almost there…"];
  const working = workingCard(steps);
  t.append(working);
  scrollDown(pane);
  try {
    if (pane === "sim") {
      const r = await api("/simulate/generate", { method: "POST", body });
      working.replaceWith(sceneCard({ ...r, rating: null }));
    } else {
      const r = await api("/code/generate", { method: "POST", body });
      working.replaceWith(packageCard({ ...r, distro: body.distro, language: body.language, rating: null }));
    }
    loadHistory();
    refreshBudget();
  } catch (e) {
    if (e instanceof ApiError && e.status === 409 && e.detail?.needs_confirmation) {
      const card = confirmCard(e.detail,
        () => { card.remove(); generate(pane, { ...body, confirm_cost: true }); },
        () => card.replaceWith(h("p", { class: "note" }, "Cancelled. Nothing was charged.")));
      working.replaceWith(card);
    } else {
      working.replaceWith(errorCard(friendly(e)));
    }
  } finally {
    working.stop();
    state.busy[pane] = false;
    $(`#composer-${pane} .send`).disabled = false;
    scrollDown(pane);
  }
}
const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);

// ------------------------------------------------------------------ history

function groupLabel(iso) {
  const d = new Date(iso.endsWith("Z") || iso.includes("+") ? iso : iso + "Z");
  const today = new Date();
  const days = Math.floor((new Date(today.toDateString()) - new Date(d.toDateString())) / 86400000);
  return days <= 0 ? "Today" : days === 1 ? "Yesterday" : days < 7 ? "This week" : "Earlier";
}
function timeLabel(iso) {
  const d = new Date(iso.endsWith("Z") || iso.includes("+") ? iso : iso + "Z");
  return d.toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
}

async function loadHistory() {
  const box = $("#history");
  try {
    const { items } = await api("/me/history");
    box.replaceChildren();
    if (!items.length) { box.append(h("div", { class: "history-empty" }, "Nothing yet. What you make shows up here.")); return; }
    let group = "";
    for (const it of items) {
      const g = groupLabel(it.created_at);
      if (g !== group) { box.append(h("div", { class: "history-group" }, g)); group = g; }
      const kind = it.kind === "code" ? "code" : "sim";
      const meta = kind === "sim" ? robotLabel(it.robot) : `${cap(it.distro || "")} · ${it.language === "cpp" ? "C++" : "Python"}`;
      const item = h("button", { class: "h-item", type: "button", role: "listitem", "data-id": it.id, title: timeLabel(it.created_at) },
        h("span", { class: `h-icon ${kind}`, html: ICON[kind] }),
        h("span", { class: "h-text" }, h("span", { class: "h-title" }, it.title || "(untitled)"),
          h("span", { class: "h-meta" }, h("span", { class: "dot " + (it.valid ? "ok" : it.valid === false ? "bad" : "") }), meta)));
      item.addEventListener("click", () => openGeneration(it.id, kind, item));
      box.append(item);
    }
  } catch (e) {
    if (!(e instanceof ApiError && e.status === 401)) box.replaceChildren(h("div", { class: "history-empty" }, friendly(e)));
  }
}

// Older generations were made before routing existed; they simply show no routing line.
const savedRouting = (g) => (g.request?.routing ? { ...g.request.routing, models: [g.model] } : null);
const savedBrief = (g) => g.request?.enhanced || null;

async function openGeneration(id, kind, item) {
  closeSidebar();
  switchPane(kind);
  $$(".h-item").forEach((x) => x.classList.toggle("active", x === item));
  const t = thread(kind);
  t.replaceChildren(workingCard(["Opening…"]));
  try {
    const g = await api(`/generations/${id}`);
    const req = g.request || {};
    const content = [];
    if (g.kind === "code") {
      content.push(userMessage(req.request || "", `ROS 2 ${cap(req.distro || "")} · ${req.language === "cpp" ? "C++" : "Python"}`));
      const card = packageCard({ id: g.id, valid: g.valid, validation: g.validation, files: g.output || {}, distro: req.distro, language: req.language, rating: g.rating, routing: savedRouting(g), enhanced_prompt: savedBrief(g) });
      content.push(card);
      for (const j of g.jobs) card.querySelector(".runs").append(jobCard(j));
    } else {
      content.push(userMessage(req.description || "", robotLabel(req.robot)));
      const card = sceneCard({ id: g.id, valid: g.valid, validation: g.validation, mjcf: g.output, robot: req.robot, error: g.error, rating: g.rating, routing: savedRouting(g), enhanced_prompt: savedBrief(g) });
      content.push(card);
      for (const j of g.jobs) card.querySelector(".runs").append(jobCard(j));
    }
    t.replaceChildren(...content);
  } catch (e) {
    t.replaceChildren(errorCard(friendly(e)));
  }
}

// ------------------------------------------------------------------ budget

async function refreshBudget() {
  try {
    const u = await api("/me/usage");
    const { ai } = u;
    if (u.is_owner) {
      $("#budget-label").textContent = "Owner";
      $("#budget-fill").style.width = "0%";
      $("#budget").title = "You are the owner. No budget limits apply.";
      $("#budget").classList.remove("high", "full");
      return;
    }
    const pct = Math.min(100, (100 * ai.used) / (ai.allocation || 1));
    $("#budget-label").textContent = `${rupees(ai.remaining)} left`;
    $("#budget-fill").style.width = pct + "%";
    const el = $("#budget");
    el.classList.toggle("high", pct >= 70 && pct < 100);
    el.classList.toggle("full", pct >= 100);
    el.title = `Your AI budget: ${rupees(ai.used)} of ${rupees(ai.allocation)} used. Click for details.`;
  } catch { /* not important */ }
}

// ------------------------------------------------------------------ layout bits

function setRobot(id) {
  state.robot = id;
  remember("rosdiff_robot", id);
  $$("#robot-chips .chip").forEach((c) => { const on = c.dataset.robot === id; c.classList.toggle("active", on); c.setAttribute("aria-checked", String(on)); });
}

function setupComposer() {
  const chips = $("#robot-chips");
  for (const r of ROBOTS) {
    chips.append(h("button", { class: "chip", type: "button", role: "radio", "data-robot": r.id, onclick: () => setRobot(r.id) }, h("span", { class: "emoji", "aria-hidden": "true" }, r.emoji), r.label));
  }
  setRobot(state.robot);
  for (const [attr, key, stateKey] of [["distro", "rosdiff_distro", "distro"], ["lang", "rosdiff_lang", "lang"]]) {
    const btns = $$(`[data-${attr}]`);
    const set = (v) => {
      state[stateKey] = v;
      remember(key, v);
      btns.forEach((b) => { const on = b.dataset[attr] === v; b.classList.toggle("active", on); b.setAttribute("aria-checked", String(on)); });
    };
    btns.forEach((b) => b.addEventListener("click", () => set(b.dataset[attr])));
    set(state[stateKey]);
  }
  for (const pane of ["sim", "code"]) {
    const input = $(`#input-${pane}`);
    input.addEventListener("input", () => autosize(input));
    input.addEventListener("keydown", (e) => {
      if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); submit(pane); }
    });
    $(`#composer-${pane}`).addEventListener("submit", (e) => { e.preventDefault(); submit(pane); });
  }
  $$("[data-clear]").forEach((b) => b.addEventListener("click", () => clearPane(b.dataset.clear)));
}

function switchPane(pane) {
  $$(".pane").forEach((p) => p.classList.toggle("active", p.id === `pane-${pane}`));
  $$(".mtab").forEach((b) => b.classList.toggle("active", b.dataset.pane === pane));
}
function openSidebar() { $("#sidebar").classList.add("open"); $("#scrim").hidden = false; $("#menu-btn").setAttribute("aria-expanded", "true"); }
function closeSidebar() { $("#sidebar").classList.remove("open"); $("#scrim").hidden = true; $("#menu-btn").setAttribute("aria-expanded", "false"); }

function setupChrome() {
  $$(".mtab").forEach((b) => b.addEventListener("click", () => {
    switchPane(b.dataset.pane);
    if (window.innerWidth <= 860) closeSidebar();
  }));
  $("#menu-btn").addEventListener("click", () => ($("#sidebar").classList.contains("open") ? closeSidebar() : openSidebar()));
  $("#scrim").addEventListener("click", closeSidebar);
  $("#refresh-history").addEventListener("click", loadHistory);
  const menu = $("#user-menu");
  $("#user-btn").addEventListener("click", (e) => { e.stopPropagation(); menu.hidden = !menu.hidden; $("#user-btn").setAttribute("aria-expanded", String(!menu.hidden)); });
  document.addEventListener("click", () => { menu.hidden = true; $("#user-btn").setAttribute("aria-expanded", "false"); });
  $("#logout-btn").addEventListener("click", () => signOut(false));
  $("#help-btn").addEventListener("click", () => openTour());
  $("#usage-btn").addEventListener("click", openUsage);
  $("#budget").addEventListener("click", openUsage);
}

// ------------------------------------------------------------------ sign in / out

function signOut(expired) {
  state.key = "";
  try { localStorage.removeItem("rosdiff_key"); } catch { /* ignore */ }
  $("#app").hidden = true;
  $("#login").hidden = false;
  if (expired) { const e = $("#login-error"); e.textContent = "Please sign in again."; e.hidden = false; }
  $("#key-input").focus();
}

async function enter() {
  const { tester } = await api("/me/history?limit=1");
  state.tester = tester;
  $("#user-name").textContent = tester;
  $("#avatar").textContent = tester.slice(0, 1);
  $("#login").hidden = true;
  $("#app").hidden = false;
  showEmpty("sim");
  showEmpty("code");
  loadHistory();
  refreshBudget();
  setInterval(refreshBudget, 60000);
  let toured = false;
  try { toured = localStorage.getItem("rosdiff_seen_tour") === "1"; } catch { /* ignore */ }
  if (!toured) { remember("rosdiff_seen_tour", "1"); openTour(); }
}

function setupLogin() {
  $("#login-form").addEventListener("submit", async (e) => {
    e.preventDefault();
    const err = $("#login-error");
    err.hidden = true;
    state.key = $("#key-input").value.trim();
    try {
      await enter();
      remember("rosdiff_key", state.key);
    } catch (ex) {
      err.textContent = ex instanceof ApiError && ex.status === 401 ? "That key isn't recognised. Check it and try again." : friendly(ex);
      err.hidden = false;
    }
  });
}

// ------------------------------------------------------------------ startup animation

function splash() {
  const el = $("#splash");
  let seen = false;
  try { seen = localStorage.getItem("rosdiff_seen_splash") === "1"; } catch { /* ignore */ }
  const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
  if (seen) el.classList.add("quick");
  const hold = reduced ? 400 : seen ? 800 : 2300;
  return new Promise((resolve) => {
    const finish = () => {
      if (el.classList.contains("done")) return;
      el.classList.add("done");
      remember("rosdiff_seen_splash", "1");
      setTimeout(() => { el.remove(); resolve(); }, 450);
    };
    setTimeout(finish, hold);
    el.addEventListener("click", finish);
    addEventListener("keydown", finish, { once: true });
  });
}

// ------------------------------------------------------------------ beginner tour

const TOUR = [
  ["Describe what you want to build.", "Type it in plain words, like you'd tell a teammate: a world for your robot on the left, a ROS 2 node on the right."],
  ["RosDiff understands your project.", "First it sharpens your words into a precise brief (for free). Then it reads the relevant MuJoCo and ROS 2 documentation, the robot's real model and every message definition before it writes anything."],
  ["RosDiff picks the right AI for the job.", "Small tasks go to a fast, low-cost model; hard ones to a stronger reasoning model. You never have to choose one."],
  ["RosDiff picks the simulator.", null],
  ["RosDiff sets up the tools.", "Robot models, ROS 2 (Humble or Jazzy), Nav2, MoveIt 2, ros2_control and the build tools are ready in the cloud. Nothing to install."],
  ["RosDiff writes and modifies the code.", "You get a complete package: nodes, launch files, package.xml and build files, checked against the real message types."],
  ["RosDiff runs it and tests it.", "“Run in MuJoCo” shows your robot in that world on a cloud GPU. “Build & run” compiles your package and starts it for 10 seconds."],
  ["RosDiff learns from failures.", "If a draft fails its checks, RosDiff reads the errors and fixes them, moving up to a stronger AI model when it needs to."],
  ["RosDiff manages the cost.", "Each tester has a small AI budget (see the top bar). Bigger tasks show an estimate first. Cloud GPU time has its own equal share per tester; see “My usage”."],
  ["You can override tools any time.", "Want a different simulator? Use “Use another simulator” on any scene. And tell us 👍 or 👎 on every result: that's what this test is for."],
];

function tourSlide(i) {
  const [title, text] = TOUR[i];
  const slide = h("div", {}, h("div", { class: "step" }, `Step ${i + 1}`), h("h3", {}, title));
  if (text) slide.append(h("p", {}, text));
  if (i === 3) {
    slide.append(
      h("p", {}, "RosDiff looks at your robot, the physics, the sensors and what you want to test, then chooses the simulator. For example:"),
      h("div", { class: "tour-demo" },
        h("div", { class: "you" }, "“Build and test a mobile robot with a LiDAR driving between obstacles.”"),
        h("div", { class: "line" }, h("span", { class: "routing" }, h("span", { class: "auto" }, "Auto")), h("span", {}, h("b", {}, "MuJoCo"), " — contact-rich rigid-body physics with the real robot model and its range sensors.")),
        h("div", { class: "line muted small" }, "Ask “how often does it crash?” and it switches to MuJoCo Warp (many variations at once); ask for photoreal camera images and Isaac Sim renders it.")),
      h("p", { class: "small", style: "margin-top:10px" }, "RosDiff automatically selects the simulation environment from your project, robot, physics, sensors and testing needs."),
    );
    const tryIt = h("button", { class: "btn btn-sm", type: "button" }, "Try this example");
    tryIt.addEventListener("click", () => {
      $("#tour").close();
      setRobot("unitree_go2");
      switchPane("sim");
      fillComposer("sim", "The Go2 robot dog with a LiDAR drives between four box obstacles 1 to 3 m ahead of it; test that it doesn't hit them.");
    });
    slide.append(tryIt);
  }
  return slide;
}

function openTour(start = 0) {
  const dlg = $("#tour");
  let i = start;
  const dots = $("#tour-dots");
  dots.replaceChildren(...TOUR.map(() => h("span")));
  const show = () => {
    $("#tour-slide").replaceChildren(tourSlide(i));
    $("#tour-count").textContent = `${i + 1} / ${TOUR.length}`;
    $$("span", dots).forEach((d, k) => d.classList.toggle("on", k === i));
    $("#tour-back").style.visibility = i === 0 ? "hidden" : "visible";
    $("#tour-next").textContent = i === TOUR.length - 1 ? "Start building" : "Next";
  };
  $("#tour-next").onclick = () => { if (i < TOUR.length - 1) { i++; show(); } else dlg.close(); };
  $("#tour-back").onclick = () => { if (i > 0) { i--; show(); } };
  $("#tour-close").onclick = () => dlg.close();
  show();
  dlg.showModal();
}

// ------------------------------------------------------------------ usage

const rupees = (x) => "₹" + (Math.round(x * 100) / 100).toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });

async function openUsage() {
  const body = $("#usage-body");
  body.replaceChildren(h("p", { class: "muted" }, "Loading…"));
  $("#usage").showModal();
  try {
    const u = await api("/me/usage");
    const a = u.ai;
    const pct = Math.min(100, (100 * a.used) / (a.allocation || 1));
    const labels = { coding: "Coding", simulation_ai: "Simulation AI", debugging: "Debugging (automatic fixes)", testing: "Testing" };
    const rows = Object.entries(a.by_category).map(([k, v]) => h("tr", {}, h("td", {}, labels[k] || k), h("td", {}, rupees(v))));
    const parts = [
      h("div", { class: "muted small" }, "AI budget"),
      h("div", { class: "usage-big" }, `${rupees(a.remaining)} left`),
      h("div", { class: "muted small" }, `${rupees(a.used)} of ${rupees(a.allocation)} used`),
      h("div", { class: "meter" }, h("span", { style: `width:${pct}%` })),
      h("table", { class: "usage-table" }, h("tbody", {}, ...rows)),
      h("p", { class: "muted small" }, `Free calls (prompt enhancement on OpenCode Zen, OpenRouter-exempt models) are not counted: ${a.exempt_calls} so far. ` +
        `Team pool: ${rupees(a.pool.used)} of ${rupees(a.pool.total)} used.`),
    ];
    const c = u.compute;
    if (c.share) {
      const gpct = Math.min(100, (100 * c.used) / c.share);
      parts.push(h("div", { class: "muted small", style: "margin-top:14px" }, "Cloud GPU (simulations, stress tests, renders, build checks)"),
        h("div", { class: "usage-big" }, `$${c.remaining.toFixed(2)} left`),
        h("div", { class: "muted small" }, `$${c.used.toFixed(2)} of your $${c.share.toFixed(2)} this month (the $${c.team_limit} credit split equally between ${c.testers} testers). ` +
          "A job only starts if its longest possible run still fits."),
        h("div", { class: "meter" }, h("span", { style: `width:${gpct}%` })));
    }
    if (u.admin && u.team) {
      parts.push(h("div", { class: "muted small", style: "margin-top:10px" }, "Team (admin view)"),
        h("table", { class: "usage-table" },
          h("thead", {}, h("tr", {}, h("th", {}, "Tester"), h("th", {}, "AI used"), h("th", {}, "AI left"), h("th", {}, "GPU used"))),
          h("tbody", {}, ...u.team.map((m) => h("tr", {}, h("td", {}, m.tester), h("td", {}, rupees(m.used)), h("td", {}, rupees(m.remaining)), h("td", {}, `$${(m.gpu || 0).toFixed(2)}`))),
            h("tr", {}, h("td", {}, h("b", {}, "Total")), h("td", {}, h("b", {}, rupees(a.pool.used))), h("td", {}, h("b", {}, rupees(a.pool.remaining))),
              h("td", {}, h("b", {}, `$${(c.team_used || 0).toFixed(2)}`))))));
    }
    body.replaceChildren(...parts);
  } catch (e) {
    body.replaceChildren(h("p", { class: "error-text" }, friendly(e)));
  }
}

setupLogin();
setupChrome();
setupComposer();
splash().then(() => {
  if (state.key) {
    enter().catch(() => signOut(false));
  } else {
    $("#login").hidden = false;
    $("#key-input").focus();
  }
});