File size: 48,840 Bytes
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c91152
8ff66cf
7c91152
d72771b
8ff66cf
 
d72771b
 
 
675b16f
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40798b3
 
95a7e69
40798b3
 
 
d72771b
 
 
 
 
 
95a7e69
d72771b
 
40798b3
7c91152
 
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675b16f
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
 
 
 
d72771b
 
8ff66cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
 
 
 
d72771b
 
 
 
8ff66cf
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
d72771b
8ff66cf
 
 
d72771b
 
 
8ff66cf
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
 
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
 
 
d72771b
 
 
8ff66cf
 
 
 
 
 
 
 
 
d72771b
8ff66cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c91152
 
 
 
 
 
8ff66cf
7c91152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
 
 
 
7c91152
 
 
 
 
 
 
 
8ff66cf
 
 
 
 
7c91152
8ff66cf
 
 
7c91152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935600d
 
 
 
 
 
7c91152
 
 
 
 
8ff66cf
7c91152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
7c91152
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c91152
 
d72771b
7c91152
d72771b
7c91152
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c91152
d72771b
 
7c91152
d72771b
 
 
 
 
 
 
8ff66cf
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c91152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
675b16f
d72771b
675b16f
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c91152
d72771b
7c91152
 
 
 
 
 
 
 
d72771b
675b16f
d72771b
675b16f
7c91152
 
 
 
 
d72771b
 
 
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
// XLeRobot Sim: MuJoCo-GS-Web's XLeRobot (and any uploaded robot) in its scenes or the kitchen, with
// keyboard teleop, skills, a learned policy and an LLM agent; and a Unitree G1 that walks with a learned
// policy. window.xlerobotSim exposes it all.
import "./style.css";
import { SceneView } from "./render/view.js";
import { fetchRobot, json, mujocoModule, onnxRuntime, progress, readRobotFolder, download, text } from "./core/assets.js";
import { writeScene } from "./core/compose.js";
import { Sim } from "./core/sim.js";
import { TELEOP_KEYS, XLeRobot, XLeRobotTeleop } from "./robots/xlerobot.js";
import { G1_KEYS, G1Robot, G1Teleop } from "./robots/g1.js";
import { GenericRobot } from "./robots/generic.js";
import { SkillRunner, comfortable, homeArm, objectInfo, holding } from "./robots/skills.js";
import { PolicyRunner } from "./policy/runner.js";
import { Episode, Household } from "./tasks/household.js";
import { solve } from "./tasks/solver.js";
import { createTools } from "./agent/tools.js";
import { BRIDGE_SPECS, TOOL_GUIDE, TOOL_SPECS } from "./agent/specs.js";
import { Agent, CLAUDE_DEFAULT, CLAUDE_MODELS } from "./agent/agent.js";
import { Bridge, bridgeRequested } from "./agent/bridge.js";
import { DEFAULT_MODEL, HF_ROUTER, routerModels } from "./agent/llm.js";
import { GEMINI_AGENT_DEFAULT } from "./agent/gemini.js";
import { GEMINI_MODEL } from "./agent/perception.js";
import { currentLogin, signIn, signInRequested, signOut } from "./agent/oauth.js";

const BASE = import.meta.env.BASE_URL;
// What the page opens on, unless its URL says otherwise: the kitchen, in Lit (its photographic room).
const DEFAULT_ENV = "kitchen";
const $ = (id) => document.getElementById(id);
const store = {
  get: (k, d = null) => {
    try {
      return localStorage.getItem(`xlerobot-sim.${k}`) ?? d;
    } catch {
      return d;
    }
  },
  set: (k, v) => {
    try {
      localStorage.setItem(`xlerobot-sim.${k}`, v);
    } catch {
      // storage blocked: settings last for this visit
    }
  },
};

const app = {
  mujoco: null,
  envs: [],
  robots: [],
  robotData: {}, // id -> fetched robot (xml, meshes, meta)
  envId: null,
  robotId: null,
  sim: null,
  robot: null,
  teleop: null,
  skills: new SkillRunner(),
  settled: null,
  view: null,
  policy: null,
  policyLoading: null,
  walking: {}, // robot id -> promise of its locomotion policy session (ONNX Runtime)
  pictures: {}, // camera -> the last picture it took for a tool, with the camera's pose then (locate)
  activity: null, // what is loading, shown on the view when no skill runs
  household: null, // the scene's household tasks, if it has them (src/tasks/)
  episode: null, // the task instance being done
};

function setLoading(message, fraction) {
  $("loading").hidden = false;
  $("loading").classList.remove("failed");
  if (message) $("loading-text").textContent = message;
  if (fraction !== undefined) $("loading-bar").style.width = `${Math.round(fraction * 100)}%`;
}

function showError(error) {
  console.error(error);
  $("loading").hidden = false;
  $("loading-text").textContent = `Could not load: ${error.message}`;
  $("loading").classList.add("failed");
}

// ---------------------------------------------------------------------------------------------
// Scenes

/**
 * The environment's XML, and the files next to it to include: its decor (a modelled stand-in for its
 * splat) and its objects ("objects" naming a file), if it has them.
 */
async function envSource(env) {
  const dir = env.xml.slice(0, env.xml.lastIndexOf("/") + 1);
  const extra = [env.decor, env.objects?.endsWith(".xml") ? env.objects : null].filter(Boolean);
  const [xml, ...files] = await Promise.all([text(`${BASE}environments/${env.xml}`), ...extra.map((f) => download(`${BASE}environments/${dir}${f}`))]);
  return { xml, files: extra.map((f, k) => [f, files[k]]), includes: extra };
}

/** Compose `envId` with the robot `robotId`, compile, settle and show it. */
async function loadScene(envId, robotId) {
  const env = app.envs.find((e) => e.id === envId) ?? app.envs[0];
  const robotData = app.robotData[robotId];
  app.skills.cancel("scene changed");
  app.pictures = {};
  setLoading(`Building ${env.name} with ${robotData.meta.name}…`);
  await new Promise((r) => requestAnimationFrame(r));
  const withObjects = env.objects === "robot" && robotData.objectsXml;
  const path = writeScene(app.mujoco, "/scene", await envSource(env), { ...robotData, objectsXml: withObjects ? robotData.objectsXml : null }, { modelName: `${env.id}_${robotId}` });
  let model;
  try {
    model = app.mujoco.MjModel.from_xml_path(path);
  } catch (error) {
    throw new Error(`MuJoCo could not compile the scene: ${error.message ?? error}`);
  }
  // A walking robot's policy loads with the scene (once): it has to run from the first step.
  const walking = robotData.meta.controller === "g1" ? await walkingPolicy(robotData) : null;
  app.sim?.dispose();
  const sim = new Sim(app.mujoco, model, { controlHz: 50 });
  const { controller } = robotData.meta;
  const robot = controller === "xlerobot" ? new XLeRobot(sim, robotData.meta) : controller === "g1" ? new G1Robot(sim, robotData.meta, robotData.policyConfig) : new GenericRobot(sim, robotData.meta);
  app.sim = sim;
  app.robot = robot;
  app.envId = env.id;
  app.robotId = robotId;
  app.teleop = robot instanceof XLeRobot ? new XLeRobotTeleop(robot) : robot instanceof G1Robot ? new G1Teleop(robot) : null;
  // XLeRobot's arms start in their resting pose: rising to it from the model's zero pose, they would
  // sweep objects off a counter beside the robot.
  sim.reset(() => {
    robot.home();
    if (robot instanceof XLeRobot) robot.snapJoints();
  });
  // Objects settle where the scene drops them; a walking robot stands on its joint servos meanwhile.
  sim.run(robot instanceof G1Robot ? 0.3 : 1.0, () => robot.update());
  if (walking) robot.setPolicy(walking.ort, walking.session);
  sim.steps = 0;
  app.settled = sim.snapshot();
  // Household tasks (the kitchen's): BDDL problems over the scene's objects and fixtures.
  app.household = null;
  app.episode = null;
  if (env.tasks && robot instanceof XLeRobot) {
    try {
      app.household = await loadHousehold(env, sim, robot);
    } catch (error) {
      console.warn(`could not load the tasks of ${env.name}`, error);
    }
  }
  app.view.splatBase = `${BASE}environments/`;
  // How the robot's rgba values are meant (robot.json "colorSpace"), for its objects too when it brought them.
  const colorSpace = robotData.meta.colorSpace ?? "srgb";
  // Lit's models (dressing.json: furniture, appliances, objects): where they go comes first, as the scenery
  // they stand in for is drawn apart; the models themselves load while the scene already runs.
  const envDir = `${BASE}environments/${env.xml.slice(0, env.xml.lastIndexOf("/") + 1)}`;
  let dressing = env.dressing ? await json(`${envDir}${env.dressing}`).catch((error) => console.warn(`no furniture models for ${env.name}: ${error.message}`)) : null;
  // A photographic room (tools/home) has the furniture and the appliances in it: only the objects' models remain.
  if (dressing && env.home) dressing = { ...dressing, items: [], parts: [] };
  app.view.setScene(sim, {
    robotRoots: robot.roots ?? (robot.root >= 0 ? [robot.root] : []),
    env,
    cameras: robotData.meta.cameras ?? {},
    robot,
    colorSpaces: { robot: colorSpace, object: withObjects ? colorSpace : "srgb" },
    dressing: dressing ?? null,
  });
  app.view.frameRobot(robot.pose(), robot instanceof G1Robot ? { distance: 3.0, height: 1.9 } : env.id === "kitchen" ? { distance: 2.4, height: 1.8 } : {});
  // The environment's photographic room or baked light for Lit (tools/home, tools/bake_light.mjs), loaded while
  // the scene already runs (app.looksLoading: until they are there, for a camera picture or an MCP client).
  const looks = [];
  if (env.home) looks.push(app.view.loadHome(`${envDir}${env.home}`).catch((error) => console.warn(`no photographic room for ${env.name}: ${error.message}`)));
  else if (env.light) looks.push(app.view.loadLight(`${envDir}${env.light}`).catch((error) => console.warn(`no baked light for ${env.name}: ${error.message}`)));
  if (dressing) looks.push(app.view.loadDressing(`${envDir}${env.dressing.slice(0, env.dressing.lastIndexOf("/") + 1)}`).catch((error) => console.warn(`no furniture models for ${env.name}: ${error.message}`)));
  app.looksLoading = Promise.all(looks);
  if (app.view.style === "splat" && !env.splat) await setStyle("lit");
  else if (app.view.style === "splat" || app.view.style === "pixel") await setStyle(app.view.style); // this environment's splat
  refreshSceneUi();
  $("loading").hidden = true;
  const url = new URL(location.href);
  url.searchParams.set("env", env.id);
  history.replaceState(null, "", url);
}

function resetScene() {
  app.skills.cancel("reset");
  app.sim.restore(app.settled);
  app.robot.home();
  app.sim.forward();
  app.household?.reset();
  app.episode = null;
  renderTask();
}

/** An environment's household: its tasks' registry and BDDL problems, tied to the simulation. */
async function loadHousehold(env, sim, robot) {
  const base = `${BASE}environments/${env.xml.slice(0, env.xml.lastIndexOf("/") + 1)}`;
  const registry = await json(`${base}${env.tasks}`);
  const dir = env.tasks.slice(0, env.tasks.lastIndexOf("/") + 1);
  const texts = await Promise.all(registry.tasks.map((t) => text(`${base}${dir}${t.file}`)));
  return new Household(sim, robot, registry, Object.fromEntries(registry.tasks.map((t, k) => [t.file, texts[k]])));
}

/** Movable objects: free bodies that are not the robot. */
function objects() {
  if (!app.sim) return [];
  return app.sim.freeBodies(app.robot?.roots ?? (app.robot?.root >= 0 ? [app.robot.root] : []));
}

/** Height of the highest static box top under a world point, below `below` (for placing things). */
function surfaceBelow(point, below = Infinity) {
  const { model, data } = app.sim;
  let best = 0;
  for (let g = 0; g < model.ngeom; g++) {
    if (model.geom_type[g] !== 6 || model.body_weldid[model.geom_bodyid[g]] !== 0 || !model.geom_contype[g]) continue;
    const c = data.geom_xpos.subarray(3 * g, 3 * g + 3);
    const R = data.geom_xmat.subarray(9 * g, 9 * g + 9);
    const s = model.geom_size.subarray(3 * g, 3 * g + 3);
    const d = [point[0] - c[0], point[1] - c[1], 0];
    const lx = R[0] * d[0] + R[3] * d[1];
    const ly = R[1] * d[0] + R[4] * d[1];
    if (Math.abs(lx) > s[0] || Math.abs(ly) > s[1]) continue;
    const top = c[2] + Math.abs(R[6]) * s[0] + Math.abs(R[7]) * s[1] + Math.abs(R[8]) * s[2];
    if (top < below && top > best) best = top;
  }
  return best;
}

// ---------------------------------------------------------------------------------------------
// Renderer, cameras, keys, sliders

const styleButtons = [...document.querySelectorAll("[data-style]")];
const STYLES = styleButtons.map((b) => b.dataset.style);
const pressStyle = (style) => {
  for (const b of styleButtons) b.setAttribute("aria-pressed", String(b.dataset.style === style));
};

/**
 * Switch renderer: "toon", "lit", "splat" or "pixel" (pixel art of the splat, or of the Toon scene where
 * the environment has none). If the 3DGS renderer cannot load, the scene keeps running, in Lit or in
 * Pixel's modelled scene, and the panel says why.
 */
async function setStyle(style) {
  const env = app.envs.find((e) => e.id === app.envId);
  if (style === "simple") style = "toon"; // its earlier name, maybe in an old link
  if (style === "splat" && !env?.splat) style = "lit";
  pressStyle(style);
  $("style-note").hidden = true;
  let loading = (style === "splat" || style === "pixel") && Boolean(env?.splat);
  if (loading) app.activity = "Loading the 3D Gaussian splat";
  const onBytes = (got, total) => {
    if (loading && total) app.activity = `Loading the 3D Gaussian splat, ${Math.round((100 * got) / total)}%`;
  };
  try {
    await app.view.setStyle(style, { onBytes });
  } catch (error) {
    console.error(error);
    if (style === "pixel") {
      $("style-note").textContent = `Could not load the 3DGS scene (${error.message}). Pixel shows the modelled scene instead.`;
    } else {
      await app.view.setStyle("lit");
      pressStyle("lit");
      $("style-note").textContent = `Could not load the 3DGS renderer (${error.message}). Showing Lit instead.`;
    }
    $("style-note").hidden = false;
  } finally {
    if (loading) app.activity = null;
    loading = false; // a download that outlives a failure reports nothing
  }
}

function refreshSceneUi() {
  const env = app.envs.find((e) => e.id === app.envId);
  $("env").value = app.envId;
  $("env-note").textContent = env.description ?? "";
  for (const b of styleButtons) if (b.dataset.style === "splat") b.disabled = !env.splat;
  // Robot cameras
  const cams = app.view.robotCameras;
  $("cameras-section").hidden = Object.keys(cams).length === 0;
  // None by default: each draws the scene again (in 3DGS, the splat too). A visitor's choice is kept.
  const saved = (store.get("views") ?? "").split(",").filter(Boolean);
  $("cameras").innerHTML = Object.entries(cams)
    .map(([name, c]) => `<label><input type="checkbox" data-view="${name}" ${saved.includes(name) ? "checked" : ""}/> ${c.label}</label>`)
    .join("");
  const boxes = [...document.querySelectorAll("[data-view]")];
  // Saved when the visitor ticks a box, not here: a robot without some cameras keeps the choice for others.
  const setViews = (save) => {
    const names = boxes.filter((b) => b.checked).map((b) => b.dataset.view);
    app.view.setViews(names);
    if (save) store.set("views", names.join(","));
  };
  for (const b of boxes) b.addEventListener("change", () => setViews(true));
  setViews(false);
  // Keys or sliders
  const xl = app.robot instanceof XLeRobot;
  const g1 = app.robot instanceof G1Robot;
  $("keys-section").hidden = !xl && !g1;
  $("keys").innerHTML = (g1 ? G1_KEYS : TELEOP_KEYS).map(([k, what]) => `<dt><kbd>${k}</kbd></dt><dd>${what}</dd>`).join("");
  $("sliders-section").hidden = xl || g1;
  if (!xl && !g1) {
    $("sliders").innerHTML = app.robot.actuators
      .map((a) => `<label>${a.name}<input type="range" min="${a.range[0]}" max="${a.range[1]}" step="${(a.range[1] - a.range[0]) / 200}" value="${app.robot.targets[a.id]}" data-act="${a.name}"/></label>`)
      .join("");
    for (const input of $("sliders").querySelectorAll("input")) input.addEventListener("input", () => app.robot.set(input.dataset.act, Number(input.value)));
  }
  for (const b of document.querySelectorAll("[data-skill]")) b.disabled = !xl;
  $("skill-status").textContent = xl ? "" : "Skills, the pick policy and the agent drive XLeRobot; choose it under Scene → Robot.";
  refreshObjects();
  refreshTasks();
  // State table
  $("state").innerHTML = "";
  stateCells = [];
  if (xl) {
    for (const name of Object.keys(app.robot.qpos)) {
      const row = document.createElement("tr");
      row.innerHTML = `<th>${name}</th><td>0</td>`;
      $("state").append(row);
      stateCells.push([name, row.lastChild]);
    }
  }
}
let stateCells = [];

function refreshObjects() {
  const list = objects();
  const keep = $("object").value;
  $("object").innerHTML = list.map((o) => `<option value="${o.name}">${o.name}</option>`).join("");
  if (list.some((o) => o.name === keep)) $("object").value = keep;
  const keepTarget = $("place-target").value;
  $("place-target").innerHTML = `<option value="">in front of the robot</option>` + list.map((o) => `<option value="${o.name}">on / in the ${o.name}</option>`).join("");
  if ([...$("place-target").options].some((o) => o.value === keepTarget)) $("place-target").value = keepTarget;
}

// ---------------------------------------------------------------------------------------------
// Policy

async function loadPolicy() {
  if (app.policy) return app.policy;
  app.policyLoading ??= (async () => {
    const list = await json(`${BASE}policies/index.json`);
    const entry = list.find((p) => p.robot === "xlerobot");
    if (!entry) throw new Error("no policy for this robot in policies/index.json");
    const dir = `${BASE}policies/${entry.dir}/`;
    const meta = await json(`${dir}policy.json`);
    const status = $("policy-status");
    const track = progress({ ort: 3.8e6, onnx: 17e6 }, (f) => (status.textContent = `Loading the policy… ${Math.round(f * 100)}%`));
    const [ort, bytes] = await Promise.all([onnxRuntime(track("ort")), download(`${dir}${meta.onnx}`, track("onnx"))]);
    app.policy = await PolicyRunner.load(ort, bytes, meta);
    status.textContent = `${meta.name}: ${(meta.parameters / 1e6).toFixed(1)} M parameters, chunks of ${meta.chunk_size} actions at ${meta.fps} Hz, ${meta.n_action_steps} executed per inference.`;
    return app.policy;
  })();
  try {
    return await app.policyLoading;
  } catch (error) {
    app.policyLoading = null;
    $("policy-status").textContent = `Could not load the policy: ${error.message}`;
    throw error;
  }
}

/** A walking robot's locomotion policy: ONNX Runtime and a session on its ONNX file, loaded once. */
function walkingPolicy(robotData) {
  const id = robotData.name;
  app.walking[id] ??= (async () => {
    const track = progress({ ort: 3.8e6, onnx: 0.9e6 }, (f) => setLoading(`Loading ${robotData.meta.name}'s walking policy…`, f));
    const [ort, bytes] = await Promise.all([onnxRuntime(track("ort")), download(robotData.policyUrl, track("onnx"))]);
    const session = await ort.InferenceSession.create(bytes, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
    return { ort, session };
  })();
  app.walking[id].catch(() => delete app.walking[id]); // try again next time
  return app.walking[id];
}

// ---------------------------------------------------------------------------------------------
// Skills tab and agent tools

const tools = createTools({
  get sim() {
    return app.sim;
  },
  get robot() {
    return app.robot;
  },
  get skills() {
    return app.skills;
  },
  objects,
  loadPolicy,
  get household() {
    return app.household;
  },
  get episode() {
    return app.episode;
  },
  surfaceBelow: (p) => surfaceBelow(p),
  snapshot: (name) => app.view.snapshot(name),
  envInfo: () => {
    const env = app.envs.find((e) => e.id === app.envId);
    return `${env.name}: ${env.description}`;
  },
  cameras: () => Object.keys(app.view?.robotCameras ?? {}),
  picture: (name, width) => picture(name, width),
  lastPicture: (name) => app.pictures[name] ?? null,
  perception: () => ({ key: geminiKey(), model: GEMINI_MODEL, thinking: $("locate-thinking").value || "low", cameraOnly: $("camera-only").checked }),
});

/**
 * A robot camera's picture and the camera's pose and lens as it was taken (for locate, which maps points in
 * it to positions); the last one of each camera is kept, for points an agent finds in it itself.
 */
async function picture(name, width = 512) {
  if (!app.view?.robotCameras?.[name]) return null;
  await app.looksLoading; // the scene as it will look, not as it looked while its models loaded
  if (app.view.sim !== app.sim) return null; // a new scene is loading
  app.view.update(); // a hidden tab has drawn nothing since the physics moved
  const frame = app.view.cameraFrame(name, width);
  const image = await app.view.snapshot(name, width);
  if (!image) return null;
  app.pictures[name] = { image, frame, time: performance.now() };
  return { image, frame };
}

/** The Gemini API key for locate and the Gemini agent: this browser's, else the MCP server's (GEMINI_API_KEY). */
const geminiKey = () => $("gemini-key").value.trim() || bridge.geminiKey || "";

// The Skills tab's buttons name objects, whatever an agent's perception.
const HUMAN = { human: true };

async function runSkill(label, promise) {
  $("skill-status").textContent = `${label}…`;
  const result = await promise;
  $("skill-status").textContent = `${label}: ${result.message ?? (result.ok ? "done" : "failed")}`;
  return result;
}

for (const button of document.querySelectorAll("[data-skill]")) {
  button.addEventListener("click", async () => {
    const object = $("object").value;
    const kind = button.dataset.skill;
    if (kind === "stop") return app.skills.cancel("stopped");
    if (kind === "go_to") return runSkill(`Go to the ${object}`, tools.call("go_to", { object }, HUMAN));
    if (kind === "pick") return runSkill(`Pick the ${object}`, tools.call("pick", { object }, HUMAN));
    if (kind === "pick_policy") return runSkill(`Policy picks the ${object}`, tools.call("pick", { object, method: "policy" }, HUMAN));
    if (kind === "home") return runSkill("Rest the arms", tools.call("home_arms", {}, HUMAN));
    if (kind === "place") {
      const side = ["left", "right"].find((s) => objects().some((o) => holding(app.robot, s, o.id)));
      if (!side) return ($("skill-status").textContent = "Neither gripper holds anything.");
      const on = $("place-target").value;
      return runSkill("Place", tools.call("place", on ? { arm: side, on } : { arm: side, forward_m: 0.3, left_m: side === "left" ? 0.05 : -0.05 }, HUMAN));
    }
  });
}

// ---------------------------------------------------------------------------------------------
// Tasks tab: household tasks in the style of the BEHAVIOR Challenge

function refreshTasks() {
  const h = app.household;
  $("tasks-none").hidden = Boolean(h);
  $("tasks-body").hidden = !h;
  if (!h) return;
  const keep = $("task").value || store.get("task");
  $("task").innerHTML = h.tasks.map((t) => `<option value="${t.id}">${t.title} (${t.goals.length})</option>`).join("");
  if (h.task(keep)) $("task").value = keep;
  renderTask();
}

/** The selected task: its instruction and BDDL, and the episode's goal, score and measures if it is this one's. */
function renderTask() {
  const h = app.household;
  const t = h?.task($("task").value);
  if (!t) return;
  const e = app.episode?.task === t ? app.episode : null;
  $("task-instruction").textContent = t.instruction;
  $("task-bddl").textContent = t.problem.text;
  const goals = e ? e.goals : t.goals.map((expr) => ({ label: h.describe(expr), done: false }));
  $("task-goals").innerHTML = goals.map((g) => `<li class="${e && g.done ? "done" : ""}">${escapeHtml(g.label)}</li>`).join("");
  const score = $("task-score");
  if (!e) {
    score.textContent = "";
    $("task-metrics").innerHTML = "";
    return;
  }
  const s = e.score();
  score.textContent = `${s.satisfied}/${s.total} · Q ${s.q.toFixed(2)}`;
  score.classList.toggle("success", s.success);
  const outcome = e.outcome === "success" ? "Done: every goal condition holds." : e.outcome === "timeout" ? "Time is up." : "";
  if (outcome) $("task-status").textContent = outcome;
  const rows = [
    ["instance", e.seed],
    ["time", `${e.time.toFixed(1)} / ${t.timeLimit} s`],
    ["base travelled", `${e.base.toFixed(2)} m`],
    ["hands moved", `${e.hands.toFixed(2)} m`],
  ];
  $("task-metrics").innerHTML = rows.map(([k, v]) => `<tr><th>${k}</th><td>${v}</td></tr>`).join("");
}

/** Set up an instance of the selected task and start its episode. */
function startTask() {
  const h = app.household;
  const t = h?.task($("task").value);
  if (!t) return null;
  app.skills.cancel("new task");
  if (agent.busy) agent.stop();
  const seed = Math.max(0, Math.floor(Number($("task-seed").value) || 0));
  $("task-seed").value = seed;
  h.setup(t, seed, app.settled);
  app.episode = new Episode(h, t, seed);
  // the whole room, from outside its walls (the view cuts them down), or the robot from behind
  const view = h.registry.overview;
  if (view) {
    app.view.camera.position.set(...view.position);
    app.view.controls.target.set(...view.target);
    app.view.controls.update();
  } else app.view.frameRobot(app.robot.pose(), { distance: 2.6, height: 2.0 });
  $("task-status").textContent = `Instance ${seed} set up.`;
  renderTask();
  return app.episode;
}

$("task").addEventListener("change", () => {
  store.set("task", $("task").value);
  $("task-status").textContent = "";
  renderTask();
});
$("task-start").addEventListener("click", () => startTask());
$("task-demo").addEventListener("click", async () => {
  const e = startTask();
  if (!e) return;
  const result = await app.skills.start("demonstrator", solve(app.household, e, { log: (m) => ($("task-status").textContent = m) }));
  if (app.episode === e && !e.outcome) $("task-status").textContent = result.message;
});
$("task-agent").addEventListener("click", () => {
  const e = startTask();
  if (!e) return;
  document.querySelector('[data-tab="agent"]').click();
  sendToAgent(`${e.task.instruction} (Household task "${e.task.title}": the task tool tells its goal conditions.)`);
});
$("task-stop").addEventListener("click", () => {
  agent.stop();
  app.skills.cancel("stopped");
});
$("tasks-open-kitchen").addEventListener("click", () => loadScene("kitchen", "xlerobot").catch(showError));

// ---------------------------------------------------------------------------------------------
// Agent tab

/** The model the agent talks to, as the Agent tab sets it: Hugging Face (or another OpenAI-compatible endpoint), Gemini or Claude. */
const agentSettings = () => {
  const provider = $("provider").value;
  if (provider === "claude") return { provider, apiKey: $("claude-key").value.trim(), model: $("claude-model").value || CLAUDE_DEFAULT, effort: $("effort").value || null, vision: true };
  if (provider === "gemini") return { provider, apiKey: geminiKey(), model: $("gemini-model").value.trim() || GEMINI_AGENT_DEFAULT, effort: $("effort").value || "medium", vision: true };
  const login = app.login;
  const endpoint = $("endpoint").value.trim() || HF_ROUTER;
  const key = $("api-key").value.trim() || (endpoint === HF_ROUTER ? login?.accessToken : "") || "";
  return { provider: "openai", baseUrl: endpoint, apiKey: key, model: $("model").value.trim() || DEFAULT_MODEL, vision: $("vision").checked };
};
const agent = new Agent(tools, agentSettings);

function chatLine(kind, html) {
  const div = document.createElement("div");
  div.className = `msg ${kind}`;
  div.innerHTML = html;
  $("chat").append(div);
  $("chat").scrollTop = $("chat").scrollHeight;
  return div;
}
const escapeHtml = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);

async function sendToAgent(textIn) {
  const settings = agentSettings();
  const missing = settings.apiKey
    ? null
    : { claude: "Paste an Anthropic API key under “Model and endpoint” (from console.anthropic.com).", gemini: "Paste a Gemini API key under Perception (from aistudio.google.com)." }[settings.provider] ??
      (settings.baseUrl === HF_ROUTER ? "Sign in with Hugging Face, or paste a token under “Model and endpoint”." : null);
  if (missing) {
    chatLine("error", missing);
    return;
  }
  chatLine("user", escapeHtml(textIn));
  $("send").disabled = true;
  $("stop-agent").hidden = false;
  $("examples").hidden = true;
  let pending = null;
  await agent.send(textIn, (e) => {
    if (e.type === "assistant") chatLine("assistant", escapeHtml(e.text).replace(/\n/g, "<br>"));
    else if (e.type === "tool") pending = chatLine("tool", `<span class="tool-name">${escapeHtml(e.name)}</span> <span class="tool-args">${escapeHtml(JSON.stringify(e.args))}</span> <span class="tool-result">…</span>`);
    else if (e.type === "result" && pending) {
      const r = e.result;
      const summary = e.name === "observe" ? `${r.objects?.length ?? 0} objects` : r.message ?? (r.ok ? "ok" : "failed");
      pending.querySelector(".tool-result").textContent = `→ ${summary}`;
      pending.classList.toggle("failed", r.ok === false);
    } else if (e.type === "image") chatLine("tool", `<img src="${e.url}" alt="Camera picture">`);
    else if (e.type === "error") chatLine("error", escapeHtml(e.message));
  });
  $("send").disabled = false;
  $("stop-agent").hidden = true;
}

$("chat-form").addEventListener("submit", (e) => {
  e.preventDefault();
  const t = $("chat-input").value.trim();
  if (!t || agent.busy) return;
  $("chat-input").value = "";
  sendToAgent(t);
});
$("chat-input").addEventListener("keydown", (e) => {
  if (e.key === "Enter" && !e.shiftKey) {
    e.preventDefault();
    $("chat-form").requestSubmit();
  }
});
$("stop-agent").addEventListener("click", () => {
  agent.stop();
  app.skills.cancel("stopped");
});
for (const b of $("examples").querySelectorAll("button")) b.addEventListener("click", () => sendToAgent(b.textContent));
$("claude-model").innerHTML = CLAUDE_MODELS.map((m) => `<option value="${m.id}">${m.label}</option>`).join("");
$("claude-model").value = CLAUDE_DEFAULT;
for (const id of ["model", "endpoint", "api-key", "claude-key", "gemini-key", "gemini-model"]) {
  $(id).value = store.get(id) ?? "";
  $(id).addEventListener("change", () => store.set(id, $(id).value.trim()));
}
for (const id of ["provider", "claude-model", "effort", "locate-thinking"]) {
  const v = store.get(id);
  if (v && [...$(id).options].some((o) => o.value === v)) $(id).value = v;
  $(id).addEventListener("change", () => store.set(id, $(id).value));
}
for (const id of ["vision", "camera-only"]) {
  $(id).checked = store.get(id) === "1";
  $(id).addEventListener("change", () => store.set(id, $(id).checked ? "1" : "0"));
}
$("model").placeholder = DEFAULT_MODEL;
$("gemini-model").placeholder = GEMINI_AGENT_DEFAULT;

/** The Agent tab shows what the chosen provider needs. */
function showProvider() {
  const p = $("provider").value;
  for (const el of document.querySelectorAll("[data-provider]")) el.hidden = !el.dataset.provider.split(" ").includes(p);
  showPerception();
}
$("provider").addEventListener("change", showProvider);

/** Where locate's Gemini key comes from. */
function showPerception() {
  const own = $("gemini-key").value.trim();
  $("perception-status").textContent = own
    ? `locate asks ${GEMINI_MODEL} with this browser's key.`
    : bridge.geminiKey
      ? `locate asks ${GEMINI_MODEL} with the MCP server's key (GEMINI_API_KEY).`
      : "No Gemini API key: locate then maps only points an agent gives it.";
}
$("gemini-key").addEventListener("input", showPerception);
routerModels()
  .then((models) => {
    $("models").innerHTML = models.map((m) => `<option value="${m.id}">${m.vision ? "text + images" : "text"}, $${m.price}/M input</option>`).join("");
    app.models = models;
    const pick = () => {
      const m = models.find((x) => x.id === ($("model").value.trim() || DEFAULT_MODEL));
      if (m && store.get("vision") === null) $("vision").checked = m.vision;
    };
    $("model").addEventListener("change", pick);
    pick();
  })
  .catch(() => {});

async function refreshLogin() {
  app.login = await currentLogin();
  $("signed-out").hidden = Boolean(app.login);
  $("signed-in").hidden = !app.login;
  if (app.login) $("hf-user").textContent = app.login.name || "Hugging Face user";
}
$("hf-signin").addEventListener("click", () => signIn());
$("hf-signout").addEventListener("click", () => {
  signOut();
  refreshLogin();
});

// ---------------------------------------------------------------------------------------------
// Claude Code: an MCP client on this computer drives the robot through tools/mcp/server.mjs, which the page
// connects to (src/agent/bridge.js) when its URL says ?bridge or the Connect button is pressed. Its calls
// run the agent's tools (tools.js) and the bridge's own (specs.js BRIDGE_SPECS, below), one at a time.

// Calls that only look: they may run while the page's own agent works.
const LOOKING = new Set(["status", "observe", "task", "camera", "locate"]);

/** What an MCP client is told about the page. */
function pageInfo() {
  const env = app.envs.find((e) => e.id === app.envId);
  return {
    page: location.origin + location.pathname,
    scene: env ? { id: env.id, name: env.name, description: env.description } : null,
    scenes: app.envs.map((e) => ({ id: e.id, name: e.name })),
    robot: app.robotData[app.robotId]?.meta.name ?? app.robotId,
    renderer: app.view.style,
    cameras: [...Object.keys(app.view.robotCameras), "view"],
    skill_running: app.skills.label,
    page_hidden: document.hidden,
    task: app.episode?.report() ?? null,
    tasks: (app.household?.tasks ?? []).map((t) => ({ id: t.id, title: t.title, time_limit_s: t.timeLimit })),
    perception: {
      locate: geminiKey() ? `Gemini (${GEMINI_MODEL})` : "no Gemini API key: locate maps the points you give it",
      camera_only: $("camera-only").checked,
    },
  };
}

/** A picture from a robot camera, or from the main view ("view"), for the bridge's camera tool. */
async function cameraImage({ camera = "head", width = 512 }) {
  const w = Math.max(64, Math.min(1280, Math.round(Number(width) || 512)));
  const name = String(camera || "head").trim().toLowerCase().replace(/[\s-]+/g, "_");
  const names = [...Object.keys(app.view.robotCameras), "view"];
  if (name === "view" || name === "main") {
    await app.looksLoading; // the scene as it will look, not as it looked while its models loaded
    app.view.update(); // a hidden tab has drawn nothing since the physics moved
    return { ok: true, camera: "view", image: app.view.capture(w) };
  }
  if (!app.view.robotCameras[name]) return { ok: false, message: `no camera "${camera}"; cameras: ${names.join(", ")}` };
  const shot = await picture(name, w);
  if (!shot) return { ok: false, message: `the ${name} camera took no picture` };
  return { ok: true, camera: name, image: shot.image, note: "locate maps points you see in this picture ([y, x] on a 0-1000 grid) to positions" };
}

async function bridgeCall(name, args) {
  if (agent.busy && !LOOKING.has(name)) return { ok: false, message: "the page's own agent is working (Agent tab): stop it first" };
  if (name === "status") return { ok: true, ...pageInfo() };
  if (name === "camera") return cameraImage(args);
  if (name === "load_scene") {
    const want = String(args.scene ?? "").trim().toLowerCase();
    const env = app.envs.find((e) => e.id.toLowerCase() === want || e.name.toLowerCase() === want);
    if (!env) return { ok: false, message: `no scene "${args.scene}"; scenes: ${app.envs.map((e) => e.id).join(", ")}` };
    $("robot").value = "xlerobot"; // the tools drive XLeRobot
    await loadScene(env.id, "xlerobot").catch((error) => {
      showError(error);
      throw error;
    });
    await app.looksLoading;
    return { ok: true, message: `loaded the ${env.name} scene`, ...pageInfo() };
  }
  if (name === "reset_scene") {
    resetScene();
    return { ok: true, message: "the scene is as it was loaded" };
  }
  if (name === "start_task") {
    const h = app.household;
    if (!h) return { ok: false, message: "this scene has no household tasks: load_scene kitchen first" };
    const want = String(args.task ?? "").trim().toLowerCase();
    const t = h.tasks.find((x) => x.id === want || x.title.toLowerCase() === want || x.id === want.replace(/[\s-]+/g, "_"));
    if (!t) return { ok: false, message: `no task "${args.task}"; tasks: ${h.tasks.map((x) => x.id).join(", ")}` };
    $("task").value = t.id;
    $("task-seed").value = Math.max(0, Math.min(99, Math.floor(Number(args.instance) || 0)));
    $("task-status").textContent = "";
    return { ok: true, ...startTask().report() };
  }
  return tools.call(name, args);
}

/** How a client names itself to the server ("claude-code"), as the panel says it. */
const clientName = (name) => (name ? ({ "claude-code": "Claude Code" }[name] ?? name) : "The MCP client");

function showBridgeStatus(state) {
  const port = bridge.port;
  $("bridge-status").textContent = {
    off: "Not connected.",
    connecting: `Connecting to the MCP server on port ${port}…`,
    waiting:
      bridge.access === "denied"
        ? "The browser keeps this page from reaching the MCP server on 127.0.0.1: allow it in the site's settings (left of the address bar), or let Claude Code open the page (open_sim)."
        : bridge.access === "prompt"
          ? `Waiting for the MCP server on port ${port}. If the browser asks whether this page may reach apps on this device, allow it.`
          : `Waiting for the MCP server on port ${port}: start Claude Code with it.`,
    connected: `Connected: ${clientName(bridge.client)} drives the robot here.`,
    replaced: "Another tab connected to the MCP server instead of this one.",
  }[state];
  $("bridge-status").classList.toggle("on", state === "connected");
  $("bridge-connect").textContent = state === "off" || state === "replaced" ? "Connect" : "Disconnect";
  showPerception(); // the server may have given a Gemini key
}

let bridgeLine = null; // the chat line of the call running
const bridge = new Bridge(
  {
    hello: () => ({ tools: [...TOOL_SPECS, ...BRIDGE_SPECS].map(({ vision, ...spec }) => spec), guide: TOOL_GUIDE, info: pageInfo() }),
    call: bridgeCall,
    cancel: () => app.skills.cancel("stopped by the MCP client"),
    activity: () => app.skills.label ?? app.activity,
    pump: () => pump(),
  },
  {
    status: showBridgeStatus,
    call: (name, args) => {
      $("examples").hidden = true;
      const shown = Object.keys(args).length ? escapeHtml(JSON.stringify(args)) : "";
      bridgeLine = chatLine("tool bridge", `<span class="who">${escapeHtml(clientName(bridge.client))}</span> <span class="tool-name">${escapeHtml(name)}</span> <span class="tool-args">${shown}</span> <span class="tool-result">…</span>`);
    },
    result: (name, result) => {
      const line = bridgeLine;
      bridgeLine = null;
      if (!line) return;
      const { image, ...rest } = result;
      const summary = name === "observe" ? `${rest.objects?.length ?? 0} objects` : name === "status" || name === "camera" ? (rest.ok === false ? rest.message : "ok") : rest.message ?? (rest.ok === false ? "failed" : "ok");
      line.querySelector(".tool-result").textContent = `→ ${summary}`;
      line.classList.toggle("failed", rest.ok === false);
      if (image) line.insertAdjacentHTML("beforeend", `<img src="${image}" alt="${escapeHtml(rest.camera ?? "camera")} image">`);
      $("chat").scrollTop = $("chat").scrollHeight;
    },
  },
);
$("bridge-connect").addEventListener("click", () => {
  if (bridge.state === "off" || bridge.state === "replaced") bridge.connect();
  else bridge.disconnect();
});
showProvider();

// ---------------------------------------------------------------------------------------------
// Tabs

for (const tab of document.querySelectorAll("[data-tab]")) {
  tab.addEventListener("click", () => {
    for (const t of document.querySelectorAll("[data-tab]")) t.setAttribute("aria-selected", String(t === tab));
    for (const p of document.querySelectorAll("[data-panel]")) p.hidden = p.dataset.panel !== tab.dataset.tab;
    store.set("tab", tab.dataset.tab);
  });
}

// ---------------------------------------------------------------------------------------------
// Keyboard: teleop keys go to the robot unless the focus is in a text field.

const teleopCodes = new Map([
  [XLeRobotTeleop, XLeRobotTeleop.codes()],
  [G1Teleop, G1Teleop.codes()],
]);
window.addEventListener("keydown", (e) => {
  const t = e.target;
  if (t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t instanceof HTMLSelectElement) return;
  if (!app.teleop || !teleopCodes.get(app.teleop.constructor)?.has(e.code)) return;
  app.teleop.down.add(e.code);
  e.preventDefault();
});
window.addEventListener("keyup", (e) => app.teleop?.down.delete(e.code));
window.addEventListener("blur", () => app.teleop?.down.clear());

// ---------------------------------------------------------------------------------------------
// Main loop: physics follows the wall clock; control runs every 1/50 s inside it.

function control(dt) {
  const { robot, teleop, skills } = app;
  app.view.applyDrag();
  // devices (the radio's switch) and the task being done, once per control period
  app.household?.update();
  if (app.episode && !app.episode.outcome) app.episode.tick(dt);
  if (skills.running) {
    if (teleop?.engaged) {
      skills.cancel("the keyboard took over");
    } else {
      skills.tick();
      if (skills.waiting) return false; // the policy is still thinking: hold the physics
    }
  }
  // A walking robot's policy answers asynchronously: the period's keys count once, when it is asked.
  if (!skills.running && teleop && !robot.pending && !robot.ready) teleop.tick(dt);
  return robot.update(dt) !== false; // false: the walking policy is still thinking, hold the physics
}

let last = performance.now();
let carry = 0;

/**
 * Physics for the wall-clock time since the last frame. A policy (the G1's walking, the pick policy)
 * answers asynchronously and the physics waits for it; it answers within microseconds to milliseconds,
 * so a frame waits a few times rather than covering only one control period. `most`: the longest stretch
 * of time one call covers (the hidden tab's pump covers more).
 */
async function advance(now, most = 0.1) {
  const sim = app.sim;
  const dt = Math.min(most, (now - last) / 1000);
  last = now;
  carry += dt;
  const want = Math.floor(carry / sim.timestep);
  let done = 0;
  for (let waits = 0; done < want; waits++) {
    done += sim.runSteps(want - done, control);
    const pending = app.robot?.pending ?? app.skills.pending;
    if (done >= want || !pending || waits >= 12) break;
    await pending;
    if (app.sim !== sim) return; // the scene changed meanwhile
  }
  carry -= done * sim.timestep;
  if (done < want) carry = Math.min(carry, 0.05); // still held: do not race to catch up
}

let frames = 0;
let fpsTime = last;
let uiTime = 0;
let stepping = false;
let frameAt = 0; // when the last animation frame came (pump steps the physics without them)
async function frame(now) {
  requestAnimationFrame(frame);
  frameAt = performance.now();
  if (!app.sim || stepping) return;
  stepping = true;
  try {
    await advance(now);
  } finally {
    stepping = false;
  }
  // While a new scene loads, the view still has the old one, whose physics is gone already.
  if (!app.sim || app.view.sim !== app.sim) return;
  app.view.update();
  app.view.render();
  frames++;
  if (now - fpsTime > 1000) {
    $("fps").textContent = `${Math.round((frames * 1000) / (now - fpsTime))} fps`;
    frames = 0;
    fpsTime = now;
  }
  if (now - uiTime > 200) {
    uiTime = now;
    const label = app.skills.label ?? app.activity;
    $("activity").hidden = !label;
    if (label) $("activity").textContent = `${label}…`;
    $("view-labels").innerHTML = app.view
      .viewRects()
      .map((r) => `<span style="left:${r.x + 8}px;top:${r.y + 6}px">${r.label}</span>`)
      .join("");
    if (app.household) {
      for (const sw of app.household.switches()) if (sw.light) app.view.setGlow(sw.light, sw.on);
      if (app.episode && !$("tasks-body").hidden) renderTask();
    }
    if (app.robot instanceof XLeRobot) {
      const q = app.robot.joints();
      for (const [name, cell] of stateCells) cell.textContent = q[name].toFixed(3);
      const sel = objects().find((o) => o.name === $("object").value);
      if (sel) {
        const c = comfortable(app.robot, sel.id);
        $("object-note").textContent = c.plan.reason ? `Out of reach: ${c.plan.reason}.` : `In reach of the ${c.plan.side} arm.`;
      }
    }
  }
}

/**
 * Physics while the page gets no animation frames, or few (a hidden tab: another tab in front, a minimised
 * window or one covered by others): while an MCP client may be driving the robot from another window, the
 * bridge's ticks (during a call) and a timer (which a hidden tab runs about once a second) keep it going.
 */
async function pump() {
  if (!app.sim || stepping || performance.now() - frameAt < 200) return;
  stepping = true;
  try {
    await advance(performance.now(), 1);
  } finally {
    stepping = false;
  }
}
setInterval(() => {
  if (bridge.connected) pump();
}, 250);

// ---------------------------------------------------------------------------------------------
// Boot

async function main() {
  app.view = new SceneView($("view"));
  const track = progress({ mujoco: 2.8e6, robot: 1.7e6 }, (f) => setLoading(null, f));
  const [mujoco, envs, robots] = await Promise.all([mujocoModule(track("mujoco")), json(`${BASE}environments/index.json`), json(`${BASE}robots/index.json`)]);
  app.mujoco = mujoco;
  app.envs = envs;
  app.robots = robots;
  app.robotData.xlerobot = await fetchRobot(BASE, "xlerobot", track("robot"));
  $("env").innerHTML = envs.map((e) => `<option value="${e.id}">${e.name}</option>`).join("");
  $("robot").innerHTML = robots.map((r) => `<option value="${r.id}">${r.name}</option>`).join("");
  // The page opens on the kitchen (in Lit, below) unless its URL names a scene (?env=tabletop).
  const wanted = new URL(location.href).searchParams.get("env");
  const first = [wanted, DEFAULT_ENV].find((id) => envs.some((e) => e.id === id)) ?? envs[0].id;
  await loadScene(first, "xlerobot");
  requestAnimationFrame(frame);

  $("env").addEventListener("change", () => loadScene($("env").value, app.robotId).catch(showError));
  $("robot").addEventListener("change", async () => {
    const id = $("robot").value;
    if (!app.robotData[id]) app.robotData[id] = await fetchRobot(BASE, id);
    loadScene(app.envId, id).catch(showError);
  });
  $("upload-robot").addEventListener("click", () => $("robot-folder").click());
  $("robot-folder").addEventListener("change", async (e) => {
    const files = [...e.target.files];
    if (!files.length) return;
    try {
      const robot = await readRobotFolder(files);
      app.robotData[robot.name] = robot;
      if (![...$("robot").options].some((o) => o.value === robot.name)) $("robot").append(new Option(`${robot.meta.name} (uploaded)`, robot.name));
      $("robot").value = robot.name;
      await loadScene(app.envId, robot.name);
    } catch (error) {
      showError(error);
      setTimeout(() => ($("loading").hidden = true), 4000);
    }
  });
  for (const b of styleButtons) b.addEventListener("click", () => setStyle(b.dataset.style).catch(showError));
  $("reset").addEventListener("click", resetScene);
  const tab = store.get("tab");
  if (tab) document.querySelector(`[data-tab="${tab}"]`)?.click();

  await refreshLogin();
  if (signInRequested() && !app.login) signIn();
  else if (signInRequested()) document.querySelector('[data-tab="agent"]').click();

  window.xlerobotSim = {
    ready: true,
    get sim() {
      return app.sim;
    },
    get robot() {
      return app.robot;
    },
    view: app.view,
    skills: app.skills,
    tools,
    agent,
    objects: () => objects().map((o) => o.name),
    observe: () => tools.call("observe"),
    call: (name, args) => tools.call(name, args),
    setEnvironment: (id) => loadScene(id, app.robotId),
    setStyle,
    reset: resetScene,
    loadPolicy,
    objectInfo: (name) => objectInfo(app.sim, app.sim.id("body", name)),
    homeArms: () => app.skills.start("home", homeArm(app.robot, "left")),
    // household tasks: list(), start(id, instance), demo() (the scripted demonstrator), report()
    tasks: {
      list: () => (app.household?.tasks ?? []).map((t) => ({ id: t.id, title: t.title, instruction: t.instruction, goals: t.goals.length, timeLimit: t.timeLimit })),
      start: (id, instance = 0) => {
        if (!app.household?.task(id)) throw new Error(`no task ${id} here`);
        $("task").value = id;
        $("task-seed").value = instance;
        return startTask()?.report();
      },
      demo: () => (app.episode ? app.skills.start("demonstrator", solve(app.household, app.episode)) : Promise.resolve({ ok: false, message: "start a task first" })),
      report: () => app.episode?.report() ?? null,
    },
    bridge, // the MCP bridge: connect(port), disconnect(), state
  };
  // Opened for an MCP client (tools/mcp/server.mjs's open_sim, or a link with ?bridge): its calls show in the
  // Agent tab.
  const bridgePort = bridgeRequested();
  if (bridgePort) {
    document.querySelector('[data-tab="agent"]').click();
    $("bridge-section").open = true;
    $("bridge-status").textContent = "Connecting once the scene has loaded…";
  }
  // The renderer last: a 3DGS splat downloads while the scene already runs. A page that embeds this one
  // names the renderer in the URL (?env=tabletop&style=pixel); otherwise Lit, whatever was chosen last time.
  const asked = new URL(location.href).searchParams.get("style");
  await setStyle(STYLES.includes(asked) ? asked : "lit");
  // The MCP client's first look at the scene should be the one it keeps: connect once its models are in.
  if (bridgePort) {
    await app.looksLoading;
    bridge.connect(bridgePort);
  }
}

main().catch(showError);