flodl 0.7.0

floDl — a flow-graph deep learning framework built on libtorch
Documentation
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
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>floDl Training Dashboard</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
:root{--bg:#0f1117;--card:#1a1d27;--border:#2a2d3a;--text:#e4e6eb;--dim:#8b8fa3;
--accent:#6c8cff;--green:#34d399;--red:#f87171;--yellow:#fbbf24;--purple:#a78bfa;
--cyan:#67e8f9;
/* Tooltip and the SVG card's paper both need to flip with the theme; they were
   the only two places assuming a dark page. */
--tooltip-bg:rgba(26,29,39,0.95);--paper:#fff}
/* Light theme. Values lifted verbatim from flodl.dev
   (`site/assets/css/style.css`), which already declares this palette under the
   same variable names — so the dashboard and the site stay one product rather
   than two takes on a similar idea. */
:root[data-theme="light"]{--bg:#fbfbfc;--card:#ffffff;--border:#dde0e8;
--text:#1a1d27;--dim:#5a5f72;--accent:#3656c7;--green:#0e9968;--red:#c93c3c;
--yellow:#8f5b10;--purple:#6e4ad0;--cyan:#0b7b95;
--tooltip-bg:rgba(26,29,39,0.95);--paper:#fbfbfc}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
background:var(--bg);color:var(--text);padding:0;min-height:100vh}

/* Header */
.header{background:var(--card);border-bottom:1px solid var(--border);padding:16px 24px;
display:flex;flex-direction:column;gap:8px}
.header-row{display:flex;align-items:center;gap:24px;flex-wrap:wrap}
.header h1{font-size:18px;font-weight:600;color:var(--accent);letter-spacing:-0.5px}
.header h1 span{color:var(--dim);font-weight:400}
.hw-info{color:var(--dim);font-size:11px;letter-spacing:0.3px;font-family:monospace}
.stat{display:flex;flex-direction:column;gap:2px}
.stat-label{font-size:10px;text-transform:uppercase;letter-spacing:0.5px;color:var(--dim)}
.stat-value{font-size:16px;font-weight:600;font-variant-numeric:tabular-nums}
.progress-bar{flex:1;min-width:120px;max-width:300px;height:6px;background:var(--border);
border-radius:3px;overflow:hidden}
.progress-fill{height:100%;background:var(--accent);border-radius:3px;transition:width 0.3s}

/* Breadcrumb navigation — one bar for every level, replacing per-device tabs */
.crumbs{background:var(--card);border-bottom:1px solid var(--border);padding:9px 24px;
display:flex;align-items:center;gap:6px;overflow-x:auto;white-space:nowrap;font-size:12px}
.crumb{color:var(--accent);cursor:pointer;padding:3px 8px;border-radius:4px;
transition:background 0.15s;user-select:none}
.crumb:hover{background:rgba(108,140,255,0.12)}
.crumb.here{color:var(--text);font-weight:600;cursor:default}
.crumb.here:hover{background:none}
.crumb-sep{color:var(--dim);opacity:0.6}
.crumb-note{color:var(--dim);margin-left:8px;font-size:11px;font-family:monospace}
.crumb-badge{margin-left:auto;font-size:11px;padding:3px 9px;border-radius:10px;
background:rgba(248,113,113,0.15);color:var(--red);cursor:pointer;display:none}
.crumb-badge.warn{background:rgba(251,191,36,0.15);color:var(--yellow)}
.crumb-badge.on{display:inline-block}
/* Immediate children, one click below the breadcrumb. The children CARD
   compares them; this is the navigation twin — drilling down should not
   require scrolling to a chart first. Hidden at a leaf. */
.kidbar{background:var(--card);border-bottom:1px solid var(--border);
        padding:7px 24px;display:flex;align-items:center;gap:6px;flex-wrap:wrap}
.kidbar-label{color:var(--dim);font-size:11px;text-transform:uppercase;
              letter-spacing:0.5px;margin-right:2px}
.kid{color:var(--accent);cursor:pointer;padding:3px 9px;border-radius:4px;
     font-size:12px;border:1px solid var(--border)}
.kid:hover{background:rgba(108,140,255,0.12)}
.kid.lost{color:var(--dim);text-decoration:line-through}
.kid-note{color:var(--dim);font-size:11px;margin-left:3px}

/* Layout */
.grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;padding:16px 24px}
@media(max-width:900px){.grid{grid-template-columns:1fr}}
.card{background:var(--card);border:1px solid var(--border);border-radius:8px;padding:16px;overflow:hidden}
.card h2{font-size:13px;text-transform:uppercase;letter-spacing:0.5px;color:var(--dim);margin-bottom:12px;
display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.card h2 .sub{text-transform:none;letter-spacing:0;font-weight:400;opacity:0.8}
.full-width{grid-column:1/-1}
select{background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:4px;
font-size:11px;padding:2px 6px;font-family:inherit}

/* Charts */
canvas{width:100%;height:260px;cursor:crosshair}
.legend{display:flex;flex-wrap:wrap;gap:10px;margin-top:10px}
.legend-item{display:flex;align-items:center;gap:5px;font-size:11px;color:var(--dim);cursor:pointer;
user-select:none;padding:2px 6px;border-radius:4px;transition:opacity 0.2s,background 0.15s}
.legend-item:hover{background:rgba(108,140,255,0.1)}
.legend-item.dimmed{opacity:0.3}
.legend-item.solo{background:rgba(108,140,255,0.15)}
.legend-dot{width:8px;height:8px;border-radius:50%}
.empty{color:var(--dim);font-size:12px;padding:24px 0;text-align:center}

/* Resource bars */
.res-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:12px}
.res-item{display:flex;flex-direction:column;gap:4px}
.res-label{display:flex;justify-content:space-between;font-size:11px;color:var(--dim);gap:8px}
.res-bar{height:8px;background:var(--border);border-radius:4px;overflow:hidden}
.res-fill{height:100%;border-radius:4px;transition:width 0.5s}
.res-fill.cpu{background:var(--accent)}
.res-fill.ram{background:var(--purple)}
.res-fill.gpu{background:var(--green)}
.res-fill.vram{background:var(--yellow)}

/* Tables (children / log / alerts) */
.scroll-wrap{max-height:300px;overflow:auto;scrollbar-width:thin;scrollbar-color:var(--border) transparent}
.scroll-wrap::-webkit-scrollbar{width:6px;height:6px}
.scroll-wrap::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}
table{width:100%;border-collapse:collapse;font-size:12px;font-variant-numeric:tabular-nums}
th{text-align:left;color:var(--dim);font-weight:500;padding:6px 8px;white-space:nowrap;
border-bottom:1px solid var(--border);position:sticky;top:0;background:var(--card);z-index:1}
td{padding:5px 8px;border-bottom:1px solid var(--border);white-space:nowrap}
tr:hover td{background:rgba(108,140,255,0.05)}
tr.drill{cursor:pointer}
tr.drill:hover td{background:rgba(108,140,255,0.12)}
tr.epoch-row td{border-left:2px solid var(--accent)}
tr.epoch-row td:first-child{font-weight:600}
tr.dead td{color:var(--red)}
.node-cell{color:var(--accent)}
.node-cell .lbl{color:var(--dim);font-size:11px;margin-left:6px}
.sev-critical{color:var(--red)}
.sev-warn{color:var(--yellow)}
.sev-info{color:var(--dim)}
.res-cell{color:var(--dim);font-size:11px}

/* Theme toggle — same markup, icons and behaviour as flodl.dev's nav toggle. */
.theme-toggle{margin-left:auto;background:none;border:none;color:var(--dim);cursor:pointer;padding:6px;
display:inline-flex;align-items:center;border-radius:4px;line-height:0;
transition:color 0.15s,background 0.15s}
.theme-toggle:hover{color:var(--text);background:rgba(108,140,255,0.08)}
.theme-toggle svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:2;
stroke-linecap:round;stroke-linejoin:round}
.theme-toggle .sun{display:inline-block}
.theme-toggle .moon{display:none}
:root[data-theme="light"] .theme-toggle .sun{display:none}
:root[data-theme="light"] .theme-toggle .moon{display:inline-block}

/* SVG toggle */
.svg-toggle{cursor:pointer;user-select:none;display:flex;align-items:center;gap:6px}
.svg-toggle .arrow{transition:transform 0.2s;font-size:10px}
.svg-toggle.open .arrow{transform:rotate(90deg)}
.svg-container{max-height:0;overflow:hidden;transition:max-height 0.3s ease;background:var(--paper);border-radius:6px;margin-top:8px}
/* A deep model's graph is a tall, narrow ribbon (ResNet-56 renders ~272pt
   wide by ~7500pt high). `width:100%` upscaled that thinness to the card
   width and multiplied the height by the same factor, so the card grew to
   tens of thousands of pixels. Render at natural size, shrink only when the
   graph is genuinely wider than the card, and centre the column. */
.svg-container svg{max-width:100%;height:auto;display:block;margin:0 auto}

/* Tooltip */
.tooltip{position:fixed;background:var(--tooltip-bg);color:#e4e6eb;padding:8px 12px;
border-radius:6px;font-size:11px;pointer-events:none;display:none;z-index:100;
border:1px solid var(--border);white-space:nowrap;backdrop-filter:blur(8px)}

/* Status */
.status{display:inline-flex;align-items:center;gap:6px;font-size:12px}
.status-dot{width:8px;height:8px;border-radius:50%;background:var(--green);
animation:pulse 2s ease-in-out infinite}
.status-dot.done{background:var(--dim);animation:none}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.4}}
</style>
<script>
// Resolve the theme BEFORE the body paints, or the page flashes the wrong one.
//
// Precedence, narrowest intent first:
//   1. the reader's own toggle (localStorage) — always wins, per browser
//   2. ARCHIVE_THEME — baked at save time; an artifact gets a FIXED look, so a
//      saved page renders the same on every machine it is opened on. Absent on
//      the live page; may be "auto" to opt an artifact into (3) deliberately.
//   3. prefers-color-scheme — the OS preference, the friendly live default
//   4. dark
(function(){
  var t=null;
  try{t=localStorage.getItem('flodl-theme')}catch(e){}
  if(t!=='light'&&t!=='dark'){
    t=(typeof ARCHIVE_THEME!=='undefined'&&ARCHIVE_THEME)?ARCHIVE_THEME:'auto';
    if(t==='auto'){
      t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)
        ?'light':'dark';
    }
  }
  if(t==='light')document.documentElement.setAttribute('data-theme','light');
})();
</script>
</head>
<body>

<div class="header">
  <div class="header-row">
    <h1>floDl <span>Training Dashboard</span></h1>
    <div class="status" id="status">
      <div class="status-dot" id="statusDot"></div>
      <span id="statusText">Waiting...</span>
    </div>
    <div class="stat">
      <div class="stat-label">Epoch</div>
      <div class="stat-value" id="epochNum">&mdash;</div>
    </div>
    <div class="progress-bar"><div class="progress-fill" id="progressFill"></div></div>
    <div class="stat">
      <div class="stat-label">ETA</div>
      <div class="stat-value" id="etaDisplay">&mdash;</div>
    </div>
    <div class="stat">
      <div class="stat-label">Elapsed</div>
      <div class="stat-value" id="elapsedDisplay">&mdash;</div>
    </div>
    <button class="theme-toggle" onclick="toggleTheme()" aria-label="Toggle light/dark theme" title="Toggle light/dark theme">
      <svg class="sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
      <svg class="moon" viewBox="0 0 24 24"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
    </button>
  </div>
  <div class="hw-info" id="hwInfo" style="display:none"></div>
</div>

<div class="crumbs" id="crumbs">
  <span class="crumb here">root</span>
  <span class="crumb-badge" id="alertBadge" onclick="scrollToAlerts()"></span>
</div>

<div class="kidbar" id="kidbar" style="display:none"></div>

<div class="grid">
  <div class="card">
    <h2>Metrics <span class="sub" id="metricsScope"></span></h2>
    <canvas id="metricsChart"></canvas>
    <div class="legend" id="metricsLegend"></div>
  </div>

  <div class="card">
    <h2>Resources <span class="sub" id="resourceScope"></span></h2>
    <canvas id="resourceChart"></canvas>
    <div class="legend" id="resourceLegend"></div>
    <div class="res-grid" id="resGrid">
      <div class="res-item"><div class="res-label"><span id="cpuLabel">CPU</span><span id="cpuVal">&mdash;</span></div>
        <div class="res-bar"><div class="res-fill cpu" id="cpuBar" style="width:0"></div></div></div>
      <div class="res-item"><div class="res-label"><span id="ramLabel">RAM</span><span id="ramVal">&mdash;</span></div>
        <div class="res-bar"><div class="res-fill ram" id="ramBar" style="width:0"></div></div></div>
      <div class="res-item"><div class="res-label"><span>GPU</span><span id="gpuVal">&mdash;</span></div>
        <div class="res-bar"><div class="res-fill gpu" id="gpuBar" style="width:0"></div></div></div>
      <div class="res-item"><div class="res-label"><span>VRAM</span><span id="vramVal">&mdash;</span></div>
        <div class="res-bar"><div class="res-fill vram" id="vramBar" style="width:0"></div></div></div>
    </div>
  </div>

  <div class="card full-width" id="childrenCard" style="display:none">
    <h2>Children <span class="sub" id="childrenCount"></span>
      <span class="sub">compare</span> <select id="compareMetric" onchange="onCompareChange()"></select></h2>
    <div class="sub" id="childrenNote" style="display:none;margin-bottom:8px"></div>
    <canvas id="childrenChart"></canvas>
    <div class="legend" id="childrenLegend"></div>
    <div class="scroll-wrap" style="margin-top:12px">
      <table>
        <thead><tr id="childrenHeader"></tr></thead>
        <tbody id="childrenBody"></tbody>
      </table>
    </div>
  </div>

  <div class="card full-width">
    <h2>Log <span class="sub" id="logScope"></span></h2>
    <div class="scroll-wrap">
      <table>
        <thead><tr id="logHeader"></tr></thead>
        <tbody id="logBody"></tbody>
      </table>
    </div>
    <div class="empty" id="logEmpty">waiting for the first record...</div>
  </div>

  <div class="card full-width" id="alertsCard" style="display:none">
    <h2>Alerts <span class="sub">whole run, deepest origin path</span></h2>
    <div class="scroll-wrap">
      <table>
        <thead><tr><th>When</th><th>Class</th><th>Origin</th><th>Detail</th><th>Count</th></tr></thead>
        <tbody id="alertsBody"></tbody>
      </table>
    </div>
  </div>

  <div class="card full-width" id="metaCard" style="display:none">
    <details>
      <summary style="cursor:pointer;color:var(--dim);font-size:13px;text-transform:uppercase;letter-spacing:0.5px">Training Configuration</summary>
      <pre id="metaPre" style="margin-top:12px;color:var(--text);font-size:12px;white-space:pre-wrap;word-break:break-word"></pre>
    </details>
  </div>

  <div class="card full-width" id="svgCard" style="display:none">
    <div class="svg-toggle" id="svgToggle" onclick="toggleSvg()">
      <span class="arrow">&#9654;</span>
      <h2 style="margin:0">Graph Architecture</h2>
    </div>
    <div class="svg-container" id="svgContainer"></div>
  </div>
</div>

<div class="tooltip" id="tooltip"></div>

<script>
// ===========================================================================
// floDl monitoring portal
//
// One recursive view over the record stream: every level renders the same way
// (its own metrics + resources plotted, its children compared and drillable,
// its log listing epoch and sub-epoch rows interleaved). Navigation is the
// record `path` — a breadcrumb, not per-device tabs.
//
// Three data owners, no overlap:
//   * `/events`  — the run clock: epoch/total, ETA, elapsed, completion, and
//                  host CPU/RAM (per-host facts that are deliberately not in
//                  the record tree, so they show as gauges only).
//   * `/stream?path=` + `/history?path=` — every level's rows, children and
//                  alerts. The record plane exists in cluster runs.
//   * `/events` again, as a FALLBACK level source when no record plane exists
//                  (single-process runs, and the baked HTML archive): each
//                  epoch becomes a root row, and `gpus[]` becomes one child
//                  per device, so the same renderer covers both.
// ===========================================================================

// Series palettes. The dark ramp ends in pale tints that wash out on white, so
// light gets its own — anchored on flodl.dev's light accents and darkened rather
// than inverted. Twelve either way, same order, so a series keeps its position.
const COLORS_DARK=['#6c8cff','#f87171','#34d399','#fbbf24','#a78bfa','#fb923c','#67e8f9','#f472b6','#86efac','#fcd34d','#c4b5fd','#fdba74'];
const COLORS_LIGHT=['#3656c7','#c93c3c','#0e9968','#8f5b10','#6e4ad0','#b4530c','#0b7b95','#b83280','#12734f','#8a6d0f','#5b3fa8','#9a4a12'];
/// Chart-drawing colours cannot be `var(--…)` — canvas has no CSS cascade. Read
/// them once per render (never per stroke) and let the CSS stay the single
/// source of truth for the palette.
let THEME={};
function refreshTheme(){
  const light=document.documentElement.getAttribute('data-theme')==='light';
  const cs=getComputedStyle(document.documentElement);
  const v=(n,fb)=>{const x=cs.getPropertyValue(n).trim();return x||fb};
  THEME={
    light,
    dim:v('--dim',light?'#5a5f72':THEME.dim),
    text:v('--text',light?'#1a1d27':'#e4e6eb'),
    grid:light?'rgba(221,224,232,0.9)':'rgba(42,45,58,0.8)',
    ref:light?'rgba(201,60,60,0.7)':'rgba(248,113,113,0.7)',
    refDim:light?'rgba(201,60,60,0.45)':'rgba(248,113,113,0.4)',
    series:light?COLORS_LIGHT:COLORS_DARK,
  };
}
refreshTheme();
/// `COLORS` stays the name every call site already uses; it just follows the
/// theme now.
const COLORS=new Proxy([],{
  get(_,k){
    const s=THEME.series||COLORS_DARK;
    return k==='length'?s.length:s[k];
  },
});
function toggleTheme(){
  const root=document.documentElement;
  const light=root.getAttribute('data-theme')==='light';
  if(light)root.removeAttribute('data-theme');else root.setAttribute('data-theme','light');
  try{localStorage.setItem('flodl-theme',light?'dark':'light')}catch(e){}
  // Canvases hold no CSS-derived state, so they must be redrawn, not restyled.
  refreshTheme();
  for(const k in soloState)soloState[k]=null;
  render();
}
// `gpu peak` shares the gpu hue at lower saturation: it is the same quantity
// seen a different way (interval max vs interval mean), so it should read as a
// companion to the gpu line rather than a fifth unrelated series.
const RES_COLORS={cpu:'#6c8cff',ram:'#a78bfa',gpu:'#34d399',vram:'#fbbf24',
                  gpuPeak:'#a7f3d0'};
const ROOT='root';
// Rows retained per node. Bounds the DOM and the chart point count on a long
// run; the durable history is the record log on disk, not this page.
const MAX_ROWS=2000;
// Log rows rendered at once. The charts still use every retained row; this only
// bounds the DOM the log table rebuilds on each update. Never silent — the card
// says how many of how many are shown.
const MAX_LOG_ROWS=500;
const HISTORY_N=2048;

// --- Store -----------------------------------------------------------------
// path -> node. Rows are the interleaved cadences (window reports + epoch
// boundaries) in `t` order; `metricKeys` is the union seen at this path.
const NODES=new Map();
// Alert stream, newest first, collapsed per (class, path).
const ALERTS=new Map();
// Wall-clock origin (ms) for the record axis; `null` until the first record.
let T0=null;
// Latches true on the first `node` record — from then on the record plane owns
// every level and the `/events` fallback tree is dropped (different clock).
let recordMode=false;
let META=null;
// Host resources from `/events`: last values only (see the header comment).
let HOST={cpu:null,ram_used:null,ram_total:null,gpu:null,vram_alloc:null,vram_total:null};
// Cumulative epoch time, the `/events` fallback axis (epoch JSON has no `ts`),
// and the epochs already folded into it. `/events` replays its whole history on
// every connect, and EventSource reconnects on its own after any drop — so the
// epoch number, not the running clock, is what makes a row unique.
let legacyT=0;
const legacySeen=new Set();
// Device identity pushed before the first epoch (LIVE_GPU_INIT): dev -> {name, vram_total}.
const GPU_INIT=new Map();

let current=ROOT;
let levelSse=null;
// Set when the current level's stream or history fetch could not be reached,
// so an empty children view can distinguish "not loaded" from "no children".
let levelUnreachable=false;
let rootSse=null;
let compareKey=null;
const soloState={metricsChart:null,resourceChart:null,childrenChart:null};
let startTime=null;
let elapsedTimer=null;
let renderQueued=false;

// How a metric key rolls up over a node's direct children. Mirrors
// `record::core_reduction`; anything else is a user metric, whose declared
// reduction rides the `meta` record (default mean). Shown in an interior
// level's legend, where a metric IS a roll-up — never at a leaf, where it is
// a raw measurement.
const CORE_REDUCTION={throughput:'sum',batch_share:'sum',loss:'mean',
                      data_starve:'max',compute_only_ms:'max'};
function reductionOf(key){
  if(CORE_REDUCTION[key])return CORE_REDUCTION[key];
  if(META&&META.reductions&&META.reductions[key])return META.reductions[key];
  return 'mean';
}

function parentOf(path){
  const i=path.lastIndexOf('/');
  return i<0?null:path.slice(0,i);
}
/// Numeric-aware compare, so `rank2` sorts before `rank10` in every legend and
/// table (plain lexicographic order scrambles a double-digit cohort).
function natCmp(a,b){
  const re=/(\d+)|(\D+)/g;
  const as=String(a).match(re)||[],bs=String(b).match(re)||[];
  for(let i=0;i<Math.min(as.length,bs.length);i++){
    const x=as[i],y=bs[i];
    const nx=/^\d/.test(x),ny=/^\d/.test(y);
    if(nx&&ny){const d=parseInt(x,10)-parseInt(y,10);if(d)return d}
    else if(x!==y)return x<y?-1:1;
  }
  return as.length-bs.length;
}
function lastSeg(path){
  const i=path.lastIndexOf('/');
  return i<0?path:path.slice(i+1);
}
function nodeOf(path){
  let n=NODES.get(path);
  if(n)return n;
  n={path,rows:[],keys:new Set(),metricKeys:new Set(),resKeys:new Set(),
     children:new Set(),label:null,device:null,alive:null,isLeaf:null,lastRow:null};
  NODES.set(path,n);
  // Creating a node creates its ancestors, so a deep `/history` fetch still
  // yields a walkable breadcrumb even if no ancestor record arrived yet.
  const p=parentOf(path);
  if(p)nodeOf(p).children.add(path);
  return n;
}

/// Insert one row, ignoring a repeat. Duplicates are expected by design: the
/// server registers a `/stream` subscriber BEFORE replaying its preamble (a
/// lost record is unrecoverable, a duplicated one is not, since every node
/// record is an absolute snapshot) and the root subscription overlaps the
/// level one. Absolute snapshots are idempotent, but APPENDING one twice
/// would double-plot — so the identity check lives here.
function addRow(path,row){
  const n=nodeOf(path);
  const key=row.ts+'|'+row.tick+'|'+row.epoch1+'|'+(row.ec?1:0);
  if(n.keys.has(key))return false;
  row.key=key;
  n.keys.add(key);
  // Binary insert by `t`: a level's history preamble arrives after the live
  // rows that opened the subscription, so arrival order is not time order.
  let lo=0,hi=n.rows.length;
  while(lo<hi){const mid=(lo+hi)>>1;if(n.rows[mid].t<=row.t)lo=mid+1;else hi=mid}
  n.rows.splice(lo,0,row);
  while(n.rows.length>MAX_ROWS){const drop=n.rows.shift();n.keys.delete(drop.key)}
  for(const k in row.metrics)n.metricKeys.add(k);
  for(const k in row.res)n.resKeys.add(k);
  if(!n.lastRow||row.t>=n.lastRow.t)n.lastRow=row;
  return true;
}

// --- Ingest: record plane --------------------------------------------------
function ingestRecord(rec){
  if(!rec||typeof rec!=='object')return;
  if(rec.kind==='meta'){META=rec;return}
  if(rec.kind==='event'){ingestAlert(rec);return}
  if(rec.kind!=='node')return;
  if(!recordMode)latchRecordMode();
  if(T0===null)T0=rec.ts||0;
  const n=nodeOf(rec.path);
  // Node identity is last-known-wins: `label` rides the epoch record only, so
  // a window report must not blank it.
  if(rec.label!=null)n.label=rec.label;
  if(rec.device!=null)n.device=rec.device;
  // A leaf carries `alive` as a bool; an interior node as a live-child count.
  if(typeof rec.alive==='boolean'){n.isLeaf=true;n.alive=rec.alive}
  else if(rec.alive!=null){n.isLeaf=false;n.aliveCount=rec.alive;n.childCount=rec.children}
  addRow(rec.path,{
    t:((rec.ts||0)-T0)/1000,
    ts:rec.ts||0,
    epoch1:rec.epoch!=null?rec.epoch+1:null,   // records carry a 0-based epoch
    tick:rec.tick!=null?rec.tick:null,
    ec:rec.epoch_complete===true,
    metrics:rec.metrics||{},
    res:rec.res||{},
    work:rec.work!=null?rec.work:null,
  });
  scheduleRender();
}

/// Drop the `/events` fallback tree on the first record. The two sources put
/// rows on different clocks (cumulative epoch duration vs the producer's
/// wall-clock `ts`), so keeping both would plot one series against two axes.
/// Nothing is lost: the level's `/history` preamble re-supplies the past.
function latchRecordMode(){
  recordMode=true;
  NODES.clear();
  T0=null;
  const wasDeep=current!==ROOT;
  current=ROOT;
  if(levelSse){levelSse.close();levelSse=null}
  // A fallback-tree path (`root/gpu0`) does not exist in the record tree, so
  // send the viewer back to root rather than leaving them on a dead level.
  if(wasDeep)location.hash='#path='+encodeURIComponent(ROOT);
}

/// Alerts collapse per (class, path). Stream `count` is an INCREMENT (the
/// occurrences the record represents), so the running total is their sum.
function ingestAlert(rec){
  const key=rec.class+'|'+rec.path;
  const cur=ALERTS.get(key);
  const add=rec.count!=null?rec.count:1;
  if(cur&&cur.ts>=rec.ts){cur.total+=add}
  else ALERTS.set(key,{class:rec.class,path:rec.path,sev:rec.sev,detail:rec.detail,
                       ts:rec.ts,total:(cur?cur.total:0)+add});
  scheduleRender();
}

// --- Ingest: `/events` epoch feed -----------------------------------------
function ingestEpoch(d){
  updateHeader(d);
  const r=d.resources||{};
  HOST={cpu:r.cpu!=null?r.cpu:null,
        ram_used:r.ram_used!=null?r.ram_used:null,
        ram_total:r.ram_total!=null?r.ram_total:null,
        gpu:r.gpu!=null?r.gpu:null,
        vram_alloc:r.vram_alloc!=null?r.vram_alloc:null,
        vram_total:r.vram_total!=null?r.vram_total:null};
  for(const g of d.gpus||[]){
    if(g.dev==null)continue;
    const cur=GPU_INIT.get(g.dev)||{};
    GPU_INIT.set(g.dev,{name:g.name||cur.name,vram_total:g.vram_total!=null?g.vram_total:cur.vram_total});
  }
  // The record plane owns the levels once it exists; this feed stays the run
  // clock and the host gauges, and contributes no rows (they would duplicate
  // the epoch records at the same paths).
  if(!recordMode)ingestEpochAsLevels(d,r);
  scheduleRender();
}

/// Fallback tree for a run with no record plane: the epoch becomes a root row,
/// and `gpus[]` becomes one child per device. Mirrors the record plane's own
/// tiering rule — a lone device collapses into root rather than adding a level
/// that repeats it.
function ingestEpochAsLevels(d,r){
  // A replayed epoch is already on the axis; re-adding it would both duplicate
  // the row and push every later epoch further along a clock that only ever
  // grows. The header still tracks the replay (it is absolute, not cumulative).
  if(legacySeen.has(d.epoch))return;
  legacySeen.add(d.epoch);
  legacyT+=d.duration||0;
  const gpus=d.gpus||[];
  const tiered=gpus.length>=2;
  const rootRes={};
  if(r.cpu!=null)rootRes.cpu=r.cpu;
  if(r.ram_used!=null)rootRes.ram_used=r.ram_used;
  if(r.ram_total!=null)rootRes.ram_total=r.ram_total;
  if(r.gpu!=null)rootRes.gpu_util=r.gpu;
  if(r.vram_alloc!=null)rootRes.vram_alloc=r.vram_alloc;
  if(r.vram_total!=null)rootRes.vram_total=r.vram_total;
  addRow(ROOT,{t:legacyT,ts:Math.round(legacyT*1000),epoch1:d.epoch,tick:null,ec:true,
               metrics:cleanMetrics(d.metrics),res:rootRes,work:null});
  const rootNode=nodeOf(ROOT);
  if(!tiered)rootNode.isLeaf=gpus.length<=1;
  if(!tiered)return;
  rootNode.isLeaf=false;
  for(const g of gpus){
    if(g.dev==null)continue;
    // `gpu<dev>` names what the epoch feed actually reports: a GPU-shaped
    // entry at index `dev`. In a live single-process run that is a physical
    // device; in a cluster run's baked archive it is a rank (the feed rewrites
    // `dev` to the global rank and puts `host:lr=.. gr=..` in the name, which
    // then shows in the legend).
    const path=ROOT+'/gpu'+g.dev;
    const kid=nodeOf(path);
    kid.isLeaf=true;
    kid.alive=true;
    kid.device=g.dev;
    const init=GPU_INIT.get(g.dev)||{};
    if(init.name)kid.label=shortGpuName(init.name);
    const metrics={};
    if(g.throughput!=null)metrics.throughput=g.throughput;
    if(g.chunk!=null)metrics.batch_share=g.chunk;
    const res={};
    if(g.util!=null)res.gpu_util=g.util;
    if(g.vram_alloc!=null)res.vram_alloc=g.vram_alloc;
    const vt=g.vram_total!=null?g.vram_total:init.vram_total;
    if(vt!=null)res.vram_total=vt;
    addRow(path,{t:legacyT,ts:Math.round(legacyT*1000),epoch1:d.epoch,tick:null,ec:true,
                 metrics,res,work:null});
  }
}

/// `/events` writes `null` for a non-finite metric (absent != zero); drop the
/// key rather than carrying a null into a series.
function cleanMetrics(m){
  const out={};
  for(const k in m||{})if(m[k]!=null)out[k]=m[k];
  return out;
}

function markComplete(msg){
  document.getElementById('statusDot').classList.add('done');
  document.getElementById('statusText').textContent=msg||'Complete';
  if(elapsedTimer){clearInterval(elapsedTimer);elapsedTimer=null}
}

// --- Navigation ------------------------------------------------------------
function pathFromHash(){
  const h=(location.hash||'').replace(/^#/,'');
  if(!h)return ROOT;
  const m=/^path=(.*)$/.exec(h);
  return m?decodeURIComponent(m[1]):ROOT;
}
function navigate(path){
  // Route through the hash so a level is linkable and Back works.
  const target='#path='+encodeURIComponent(path);
  if(location.hash===target)setLevel(path);
  else location.hash=target;
}
function setLevel(path){
  current=path||ROOT;
  nodeOf(current);
  subscribeLevel(current);
  render();
}
window.addEventListener('hashchange',()=>setLevel(pathFromHash()));

function renderCrumbs(){
  const el=document.getElementById('crumbs');
  const badge=document.getElementById('alertBadge');
  const segs=current.split('/');
  let html='';
  for(let i=0;i<segs.length;i++){
    const p=segs.slice(0,i+1).join('/');
    const here=i===segs.length-1;
    if(i>0)html+='<span class="crumb-sep">/</span>';
    html+='<span class="crumb'+(here?' here':'')+'" data-path="'+esc(p)+'">'+esc(segs[i])+'</span>';
  }
  const n=NODES.get(current);
  const note=[];
  if(n&&n.label)note.push(n.label);
  if(n&&n.device!=null)note.push('dev '+n.device);
  if(n&&n.isLeaf===false&&n.childCount!=null)note.push(n.aliveCount+'/'+n.childCount+' alive');
  if(n&&n.isLeaf===true&&n.alive===false)note.push('LOST');
  if(note.length)html+='<span class="crumb-note">'+esc(note.join(' · '))+'</span>';
  el.innerHTML=html;
  el.appendChild(badge);
  el.querySelectorAll('.crumb:not(.here)').forEach(c=>{
    c.onclick=()=>navigate(c.dataset.path);
  });
  renderKidBar();
}

// Immediate children as navigation chips, directly under the breadcrumb.
// The children card already compares them and is clickable, but it sits below
// the charts — drilling down should not mean scrolling to a chart first. The
// breadcrumb walks UP, this walks DOWN, and together they make every adjacent
// level reachable without scrolling.
//
// Only LOADED children can be linked (a level is fetched when opened), so when
// the node declares more than arrived we say so rather than quietly showing a
// short list — the same absent≠zero honesty the children card uses.
function renderKidBar(){
  const bar=document.getElementById('kidbar');
  const node=NODES.get(current);
  const kids=node?childPaths(node):[];
  if(!kids.length){bar.style.display='none';bar.innerHTML='';return}
  let html='<span class="kidbar-label">in here</span>';
  for(const p of kids){
    const k=NODES.get(p);
    const lost=k&&k.isLeaf===true&&k.alive===false;
    const seg=p.split('/').pop();
    html+='<span class="kid'+(lost?' lost':'')+'" data-path="'+esc(p)+'" title="'+esc(p)+'">'
        +esc(seg)+(k&&k.label?' <span class="kid-note">'+esc(k.label)+'</span>':'')+'</span>';
  }
  const declared=node.childCount;
  if(declared!=null&&declared>kids.length){
    html+='<span class="kid-note">'+(declared-kids.length)+' more not loaded</span>';
  }
  bar.innerHTML=html;
  bar.style.display='flex';
  bar.querySelectorAll('.kid').forEach(c=>{c.onclick=()=>navigate(c.dataset.path)});
}

// --- Subscriptions ---------------------------------------------------------
// Two record subscriptions, on purpose:
//   * `rootSse` is pinned for the whole session. `/stream` scopes NODE records
//     to the level and its direct children, but EVENT records to the whole
//     subtree — so a root subscription is the one place that sees every alert,
//     whatever level the viewer is on. It is also the alert lane's only
//     consumer: alert counts are increments and cannot be deduplicated by
//     identity, so exactly one subscription may feed them.
//   * `levelSse` follows navigation, and is skipped at root (already covered).
function subscribeRoot(){
  rootSse=new EventSource('/stream?path='+encodeURIComponent(ROOT));
  rootSse.addEventListener('record',e=>{try{ingestRecord(JSON.parse(e.data))}catch(err){}});
}
function subscribeLevel(path){
  if(levelSse){levelSse.close();levelSse=null}
  levelUnreachable=false;
  if(path===ROOT||!rootSse)return;
  const enc=encodeURIComponent(path);
  levelSse=new EventSource('/stream?path='+enc);
  levelSse.addEventListener('record',e=>{
    try{
      const rec=JSON.parse(e.data);
      // The pinned root subscription owns the alert lane.
      if(rec.kind!=='event')ingestRecord(rec);
    }catch(err){}
  });
  // A level's records are fetched when you open it, so once the run's server
  // is gone a level never visited while live has nothing to show. Remember
  // that the reach failed so the children view can say so rather than render
  // as an empty node (see `renderChildren`).
  levelSse.addEventListener('error',()=>{levelUnreachable=true;scheduleRender()});
  // Subscribe first, then backfill: the same duplicate-over-loss ordering the
  // server uses for its own preamble, and `addRow` absorbs the overlap.
  fetch('/history?path='+enc+'&n='+HISTORY_N)
    .then(r=>r.ok?r.json():[])
    .then(rows=>{for(const r of rows)if(r.kind!=='event')ingestRecord(r)})
    .catch(()=>{levelUnreachable=true;scheduleRender()});
}

// --- Header ----------------------------------------------------------------
function updateHeader(d){
  if(!startTime&&d.duration!=null)startTime=Date.now()-(d.epoch*d.duration*1000);
  document.getElementById('epochNum').textContent=d.epoch+'/'+d.total;
  document.getElementById('progressFill').style.width=(d.epoch/d.total*100)+'%';
  document.getElementById('statusDot').classList.remove('done');
  document.getElementById('statusText').textContent='Training';
  if(d.eta!=null)document.getElementById('etaDisplay').textContent=fmtDur(d.eta);
  updateElapsed();
}
function updateElapsed(){
  if(!startTime)return;
  document.getElementById('elapsedDisplay').textContent=fmtDur((Date.now()-startTime)/1000);
}

// --- Series helpers --------------------------------------------------------
function seriesOf(node,group,key){
  const out=[];
  for(const r of node.rows){const v=r[group][key];if(v!=null)out.push({t:r.t,v,row:r})}
  return out;
}
/// Percentage series from a used/total pair; absent either side means absent.
function pctSeries(node,usedKey,totalKey){
  const out=[];
  for(const r of node.rows){
    const u=r.res[usedKey],tt=r.res[totalKey];
    if(u!=null&&tt)out.push({t:r.t,v:u/tt*100,row:r});
  }
  return out;
}
function epochMarks(node){
  const out=[];
  for(const r of node.rows)if(r.ec&&r.epoch1!=null)out.push({t:r.t,label:'e'+r.epoch1});
  return out;
}
function metricKeys(node){
  return Array.from(node.metricKeys).sort();
}
function lastOf(series){
  return series.length?series[series.length-1].v:null;
}

// --- Render ----------------------------------------------------------------
function scheduleRender(){
  if(renderQueued)return;
  renderQueued=true;
  requestAnimationFrame(()=>{renderQueued=false;render()});
}
/// The level a card is describing. Shared because `drawMetrics` re-sets the
/// metrics one on its own (a legend click redraws that chart WITHOUT going
/// through `render`), and the two must not drift.
function scopeLabel(){return current===ROOT?'run total':lastSeg(current)}
function render(){
  renderCrumbs();
  const scope=scopeLabel();
  document.getElementById('metricsScope').textContent=scope;
  document.getElementById('resourceScope').textContent=scope;
  const total=nodeOf(current).rows.length;
  document.getElementById('logScope').textContent=
    (recordMode?'epoch + sub-epoch rows, newest first':'epoch rows, newest first')+
    (total>MAX_LOG_ROWS?' — showing newest '+MAX_LOG_ROWS+' of '+total:'');
  renderHardware();
  drawMetrics();
  drawResources();
  renderChildren();
  renderLog();
  renderAlerts();
  // Run-scoped cards describe the whole run, not a level.
  const atRoot=current===ROOT;
  for(const id of ['metaCard','svgCard']){
    const el=document.getElementById(id);
    if(el.dataset.have==='1')el.style.display=atRoot?'block':'none';
  }
}

function drawMetrics(){
  const node=nodeOf(current);
  const keys=metricKeys(node);
  const series={},labels={};
  // Level-aware legend: at an interior node every metric is a work-weighted
  // roll-up over the direct children, so the legend names the reduction. At a
  // leaf it is a raw measurement and the bare key is the honest label.
  const interior=node.isLeaf===false;
  for(const k of keys){
    series[k]=seriesOf(node,'metrics',k);
    labels[k]=interior?k+' ('+reductionOf(k)+')':k;
  }
  const solo=soloState.metricsChart;
  // The only chart with mixed units on one canvas — loss, throughput,
  // batch_share and compute_only_ms span five orders of magnitude, so a shared
  // axis shows the milliseconds and flattens everything else. Each curve gets
  // the full height instead; click one in the legend for its true axis.
  drawChart('metricsChart',series,COLORS,{
    marks:epochMarks(node),
    yFmt:solo?fmtForKey(solo):null,
    normalize:true,
    labels,
  });
  updateLegend('metricsLegend',keys,COLORS,'metricsChart',drawMetrics,labels);
  // Say so, rather than letting a 0-100% axis imply the metrics ARE
  // percentages. Sets the WHOLE label rather than appending: a legend click
  // redraws this chart without going through `render`, so an append would
  // stack up across toggles.
  const scopeEl=document.getElementById('metricsScope');
  if(scopeEl){
    const scaling=!solo&&keys.length>1;
    scopeEl.textContent=scopeLabel()+
      (scaling?' · each curve scaled to its own range, click one for real values':'');
  }
}

function drawResources(){
  const node=nodeOf(current);
  const solo=soloState.resourceChart;
  const names=[],series={},colors=[];
  const add=(name,s,color)=>{if(s.length){names.push(name);series[name]=s;colors.push(color)}};
  add('gpu',seriesOf(node,'res','gpu_util'),RES_COLORS.gpu);
  // Each point is an INTERVAL, not an instant: `gpu` is the mean over the
  // window, `gpu peak` the max. Both matter and neither implies the other —
  // a device pegged for most of a window between two idle syncs has a modest
  // mean and a peak of 100, and reporting only one of them is how a busy GPU
  // came to look idle. Absent on archives written before peaks existed, and
  // `add` skips empty series, so those pages simply keep one gpu line.
  add('gpu peak',seriesOf(node,'res','gpu_util_max'),RES_COLORS.gpuPeak);
  add('vram',pctSeries(node,'vram_alloc','vram_total'),RES_COLORS.vram);
  // cpu / ram exist only where the level's own rows carry them (the `/events`
  // fallback root). They are per-host facts outside the record tree, so in a
  // cluster run they appear as gauges only, never as a curve on an axis they
  // do not share.
  add('cpu',seriesOf(node,'res','cpu'),RES_COLORS.cpu);
  add('ram',pctSeries(node,'ram_used','ram_total'),RES_COLORS.ram);

  const vramTotal=lastResValue(node,'vram_total');
  let drawn=series,drawColors=colors,pct=true,yFmt=null,ref=null;
  if(solo==='vram'&&vramTotal){
    // Solo VRAM: absolute bytes against the physical limit.
    drawn={vram:seriesOf(node,'res','vram_alloc')};drawColors=[RES_COLORS.vram];pct=false;
    yFmt=fmtBytes;ref={value:vramTotal,dotted:false,color:THEME.ref,label:'Physical VRAM'};
  }else if(solo==='ram'){
    drawn={ram:seriesOf(node,'res','ram_used')};drawColors=[RES_COLORS.ram];pct=false;yFmt=fmtBytes;
  }else if(solo==='gpu'||solo==='cpu'||solo==='gpu peak'){
    // Colour comes from the parallel `names`/`colors` arrays rather than
    // `RES_COLORS[solo]`: a series' DISPLAY name need not be a palette key
    // (`gpu peak` isn't), and indexing the palette by display name silently
    // yields undefined instead of failing.
    drawn={};drawn[solo]=series[solo]||[];
    drawColors=[colors[names.indexOf(solo)]];yFmt=pctFmt;
  }else if(names.includes('vram')&&vramTotal){
    ref={value:100,dotted:true,color:THEME.refDim,label:'VRAM limit'};
  }
  // Whatever branch ran, the drawn key set is named exactly as the legend is,
  // so `soloState` alone drives the filtering inside drawChart.
  drawChart('resourceChart',drawn,drawColors,{
    percent:pct,yFmt:yFmt||(pct?pctFmt:null),refLine:ref,marks:epochMarks(node),
  });
  updateLegend('resourceLegend',names,colors,'resourceChart',drawResources,
               {cpu:'CPU',gpu:'GPU (mean)',ram:'RAM',vram:'VRAM','gpu peak':'GPU (peak)'});
  updateGauges(node);
}

function lastResValue(node,key){
  for(let i=node.rows.length-1;i>=0;i--){const v=node.rows[i].res[key];if(v!=null)return v}
  return null;
}

/// Gauges are last-known values. GPU / VRAM follow the level (drilling into a
/// rank shows that rank's card); CPU / RAM come from the run feed, whose scope
/// is the cohort in a cluster run and the host in a single-process one.
function updateGauges(node){
  const cohort=recordMode;
  document.getElementById('cpuLabel').textContent=cohort?'CPU (cohort mean)':'CPU';
  document.getElementById('ramLabel').textContent=cohort?'RAM (cohort)':'RAM';
  setBar('cpu',HOST.cpu,pctFmt);
  if(HOST.ram_used!=null&&HOST.ram_total){
    document.getElementById('ramBar').style.width=(HOST.ram_used/HOST.ram_total*100)+'%';
    document.getElementById('ramVal').textContent=fmtBytes(HOST.ram_used)+' / '+fmtBytes(HOST.ram_total);
  }
  const util=lastResValue(node,'gpu_util');
  setBar('gpu',util!=null?util:(current===ROOT?HOST.gpu:null),pctFmt);
  const alloc=lastResValue(node,'vram_alloc');
  const total=lastResValue(node,'vram_total');
  const useAlloc=alloc!=null?alloc:(current===ROOT?HOST.vram_alloc:null);
  const useTotal=total!=null?total:(current===ROOT?HOST.vram_total:null);
  if(useAlloc!=null){
    const t=useTotal||0;
    const p=t>0?Math.min(useAlloc/t*100,100):0;
    const spill=t>0&&useAlloc>t?useAlloc-t:0;
    const bar=document.getElementById('vramBar');
    bar.style.width=p+'%';
    bar.style.background=spill>0?'var(--red)':'var(--yellow)';
    document.getElementById('vramVal').textContent=fmtBytes(useAlloc)+(t>0?' / '+fmtBytes(t):'');
  }
}
function setBar(id,val,fmt){
  if(val==null)return;
  document.getElementById(id+'Bar').style.width=Math.min(val,100)+'%';
  document.getElementById(id+'Val').textContent=fmt(val);
}

// --- Children --------------------------------------------------------------
function childPaths(node){
  return Array.from(node.children).sort(natCmp);
}
function renderChildren(){
  const node=nodeOf(current);
  const kids=childPaths(node);
  const card=document.getElementById('childrenCard');
  const note=document.getElementById('childrenNote');
  if(!kids.length){
    // A node that declares children but has none loaded is not a childless
    // node — the level was never fetched. Saying so beats hiding the card and
    // letting it read as "this rank has nothing under it".
    const declared=node.childCount;
    if(declared>0){
      card.style.display='block';
      note.style.display='block';
      note.textContent=levelUnreachable
        ? declared+' children reported, none loaded — the dashboard server is not answering. '+
          'A level is fetched when you open it, so one never opened while the run was live '+
          'has no data once the run ends.'
        : declared+' children reported, waiting for their records…';
      document.getElementById('childrenCount').textContent=declared;
      document.getElementById('childrenHeader').innerHTML='';
      document.getElementById('childrenBody').innerHTML='';
      drawChart('childrenChart',{},[],{});
      updateLegend('childrenLegend',[],[],'childrenChart',renderChildren,{});
      return;
    }
    card.style.display='none';return;
  }
  card.style.display='block';
  note.style.display='none';

  // Level-aware legend: the child's own path segment, plus its label (the GPU
  // model the producer attached) when there is one.
  const labels={},keySet=new Set(),resSet=new Set();
  for(const p of kids){
    const k=NODES.get(p);
    labels[p]=childLegend(p);
    if(k)for(const m of k.metricKeys)keySet.add(m);
    if(k)for(const m of k.resKeys)resSet.add(m);
  }
  const metricCols=Array.from(keySet).sort();
  const options=metricCols.slice();
  if(resSet.has('gpu_util'))options.push('gpu_util');
  if(resSet.has('vram_alloc'))options.push('vram_alloc');
  syncCompareOptions(options);

  const series={},colors=[],names=[];
  const isRes=compareKey==='gpu_util'||compareKey==='vram_alloc';
  kids.forEach((p,i)=>{
    const k=NODES.get(p);
    if(!k)return;
    const s=isRes?seriesOf(k,'res',compareKey):seriesOf(k,'metrics',compareKey);
    if(!s.length)return;
    names.push(p);series[p]=s;colors.push(COLORS[i%COLORS.length]);
  });
  drawChart('childrenChart',series,colors,{
    marks:epochMarks(node),yFmt:fmtForKey(compareKey),labels,
  });
  updateLegend('childrenLegend',names,colors,'childrenChart',renderChildren,labels);

  const alive=kids.filter(p=>NODES.get(p)&&NODES.get(p).alive!==false).length;
  document.getElementById('childrenCount').textContent=
    kids.length+(alive!==kids.length?' ('+alive+' alive)':'');

  const cols=['node','dev','work'].concat(metricCols).concat(['gpu','vram']);
  const hdr=document.getElementById('childrenHeader');
  hdr.innerHTML=cols.map(c=>'<th>'+esc(c)+'</th>').join('');
  const body=document.getElementById('childrenBody');
  body.innerHTML='';
  for(const p of kids){
    const k=NODES.get(p);
    const last=k&&k.lastRow;
    const tr=document.createElement('tr');
    tr.className='drill'+(k&&k.alive===false?' dead':'');
    let html='<td class="node-cell">'+esc(lastSeg(p))+
             (k&&k.label?'<span class="lbl">'+esc(k.label)+'</span>':'')+'</td>';
    html+='<td>'+(k&&k.device!=null?k.device:'')+'</td>';
    html+='<td>'+(last&&last.work!=null?fmtVal(last.work):'')+'</td>';
    for(const key of metricCols){
      const v=lastMetric(k,key);
      html+='<td>'+(v!=null?fmtForKey(key)(v):'')+'</td>';
    }
    const u=k?lastResValue(k,'gpu_util'):null;
    html+='<td>'+(u!=null?pctFmt(u):'')+'</td>';
    const a=k?lastResValue(k,'vram_alloc'):null;
    html+='<td>'+(a!=null?fmtBytes(a):'')+'</td>';
    tr.innerHTML=html;
    tr.onclick=()=>navigate(p);
    body.appendChild(tr);
  }
}
function childLegend(path){
  const k=NODES.get(path);
  const seg=lastSeg(path);
  return k&&k.label?seg+' · '+k.label:seg;
}
function lastMetric(node,key){
  if(!node)return null;
  for(let i=node.rows.length-1;i>=0;i--){const v=node.rows[i].metrics[key];if(v!=null)return v}
  return null;
}
function syncCompareOptions(options){
  const sel=document.getElementById('compareMetric');
  const want=options.join('|');
  if(sel.dataset.opts!==want){
    sel.dataset.opts=want;
    sel.innerHTML=options.map(o=>'<option value="'+esc(o)+'">'+esc(o)+'</option>').join('');
  }
  if(!compareKey||!options.includes(compareKey)){
    compareKey=['loss','throughput','batch_share'].find(k=>options.includes(k))||options[0]||null;
  }
  if(compareKey)sel.value=compareKey;
}
function onCompareChange(){
  compareKey=document.getElementById('compareMetric').value;
  soloState.childrenChart=null;
  renderChildren();
}

// --- Log -------------------------------------------------------------------
function renderLog(){
  const node=nodeOf(current);
  const keys=metricKeys(node);
  const empty=document.getElementById('logEmpty');
  const header=document.getElementById('logHeader');
  const body=document.getElementById('logBody');
  if(!node.rows.length){
    empty.style.display='block';header.innerHTML='';body.innerHTML='';return;
  }
  empty.style.display='none';
  const cols=['t','epoch'];
  if(recordMode)cols.push('window','work');
  const cells=cols.concat(keys).concat(['res']);
  header.innerHTML=cells.map(c=>'<th>'+esc(c)+'</th>').join('');
  const stop=Math.max(0,node.rows.length-MAX_LOG_ROWS);
  let html='';
  for(let i=node.rows.length-1;i>=stop;i--){
    const r=node.rows[i];
    let tds='<td>'+fmtDur(r.t)+'</td>';
    tds+='<td>'+(r.epoch1!=null?r.epoch1:'')+'</td>';
    if(recordMode){
      tds+='<td>'+(r.tick!=null?r.tick:'')+'</td>';
      // `work` is a per-record interval quantity whose unit differs by cadence
      // (steps for a window, batch share for an epoch), so it is a column and
      // never a curve.
      tds+='<td>'+(r.work!=null?fmtVal(r.work):'')+'</td>';
    }
    for(const k of keys){
      const v=r.metrics[k];
      tds+='<td>'+(v!=null?fmtForKey(k)(v):'')+'</td>';
    }
    tds+='<td class="res-cell">'+esc(resSummary(r.res))+'</td>';
    html+='<tr class="'+(r.ec?'epoch-row':'')+'">'+tds+'</tr>';
  }
  body.innerHTML=html;
}
function resSummary(res){
  const out=[];
  if(res.cpu!=null)out.push('CPU:'+res.cpu.toFixed(0)+'%');
  if(res.gpu_util!=null)out.push('GPU:'+res.gpu_util.toFixed(0)+'%');
  if(res.vram_alloc!=null){
    const t=res.vram_total;
    out.push('VRAM:'+fmtBytes(res.vram_alloc)+(t?'/'+fmtBytes(t):''));
  }
  if(res.ram_used!=null&&res.ram_total)out.push('RAM:'+fmtBytes(res.ram_used));
  return out.join(' ');
}

// --- Alerts ----------------------------------------------------------------
function renderAlerts(){
  const card=document.getElementById('alertsCard');
  const badge=document.getElementById('alertBadge');
  const list=Array.from(ALERTS.values()).sort((a,b)=>b.ts-a.ts);
  if(!list.length){card.style.display='none';badge.classList.remove('on');return}
  card.style.display='block';
  const critical=list.filter(a=>a.sev==='critical').length;
  badge.classList.add('on');
  badge.classList.toggle('warn',critical===0);
  badge.textContent=critical>0?critical+' critical':list.length+' alert'+(list.length>1?'s':'');
  const body=document.getElementById('alertsBody');
  body.innerHTML='';
  for(const a of list){
    const tr=document.createElement('tr');
    let html='<td class="res-cell">'+esc(fmtClock(a.ts))+'</td>';
    html+='<td class="sev-'+esc(a.sev)+'">'+esc(a.class)+'</td>';
    html+='<td class="node-cell">'+esc(a.path)+'</td>';
    html+='<td class="res-cell">'+esc(a.detail||'')+'</td>';
    html+='<td>'+a.total+'</td>';
    tr.innerHTML=html;
    // The origin path is a real node in the tree, so an alert is a jump to it.
    if(NODES.has(a.path)||a.path===ROOT){
      tr.className='drill';
      tr.onclick=()=>navigate(a.path);
    }
    body.appendChild(tr);
  }
}
function scrollToAlerts(){
  const card=document.getElementById('alertsCard');
  if(card.style.display!=='none')card.scrollIntoView({behavior:'smooth',block:'center'});
}

// --- Chart engine ----------------------------------------------------------
// Series are `{name: [{t, v}]}` on a shared elapsed-seconds axis — the only
// axis the two cadences have in common. Epoch boundaries become the x labels
// (`e3`), so the chart still reads in epochs while staying metric in time.
function drawChart(canvasId,series,colors,opts){
  opts=opts||{};
  const canvas=document.getElementById(canvasId);
  if(!canvas)return;
  const ctx=canvas.getContext('2d');
  const dpr=window.devicePixelRatio||1;
  const rect=canvas.getBoundingClientRect();
  canvas.width=Math.max(1,rect.width*dpr);canvas.height=Math.max(1,rect.height*dpr);
  ctx.scale(dpr,dpr);
  const W=rect.width,H=rect.height;
  const M={top:10,right:12,bottom:24,left:opts.yFmt?70:52};
  const pw=W-M.left-M.right,ph=H-M.top-M.bottom;
  ctx.clearRect(0,0,W,H);

  const allNames=Object.keys(series);
  const solo=soloState[canvasId];
  const visible=allNames.filter(n=>!solo||n===solo);
  // Independent per-series scaling, for charts that opt in.
  //
  // Mixed-unit series share no meaningful axis: loss ~5, throughput ~0.05 and
  // compute_only_ms ~1e5 on one linear scale means the milliseconds saturate it
  // and every other curve is a flat line on the floor. Giving each series the
  // full height shows all four shapes at once, which is the view you actually
  // want when everything is displayed.
  //
  // Opt-in per chart, because it is WRONG where a shared scale is real: the
  // resource chart's series are all percentages, and the children chart
  // compares ONE metric across children — normalising either would destroy a
  // comparison the reader is relying on.
  //
  // Soloing a series drops back to its true axis, so exact magnitudes are
  // always one click away, and the tooltip reports raw values in every mode.
  const scaled=!!opts.normalize&&!solo&&visible.length>1;
  let minT=Infinity,maxT=-Infinity,minV=Infinity,maxV=-Infinity;
  for(const n of allNames)for(const p of series[n]){
    if(p.t<minT)minT=p.t;if(p.t>maxT)maxT=p.t;
  }
  // Per-series extents, only needed in scaled mode.
  const range={};
  if(scaled)for(const n of visible){
    let lo=Infinity,hi=-Infinity;
    for(const p of series[n]){if(p.v<lo)lo=p.v;if(p.v>hi)hi=p.v}
    // A series that never varies would divide by zero; widening it parks the
    // flat line mid-height rather than stretching noise across the canvas.
    if(!isFinite(lo)){lo=0;hi=1}
    if(lo===hi){lo-=1;hi+=1}
    range[n]=[lo,hi];
  }
  for(const n of visible)for(const p of series[n]){
    if(p.v<minV)minV=p.v;if(p.v>maxV)maxV=p.v;
  }
  if(!isFinite(minT)){
    ctx.fillStyle=THEME.dim;ctx.font='12px -apple-system,sans-serif';ctx.textAlign='center';
    ctx.fillText('no data yet',W/2,H/2);
    canvas._layout=null;
    return;
  }
  if(!isFinite(minV)){minV=0;maxV=1}
  if(minV===maxV){minV-=1;maxV+=1}
  if(opts.percent){minV=Math.min(0,minV);maxV=Math.max(100,maxV)}
  if(opts.refLine!=null&&!scaled){minV=Math.min(minV,opts.refLine.value);maxV=Math.max(maxV,opts.refLine.value)}
  // In scaled mode the axis is a fraction of each series' own range, so the
  // shared 0..1 is the axis and the 5% padding belongs to no series.
  if(scaled){minV=0;maxV=1}
  else{const pad=(maxV-minV)*0.05;minV-=pad;maxV+=pad}
  // Byte scales can never be negative: padding under a large reference line
  // would otherwise render nonsense "-200 MB" gridlines.
  if(opts.yFmt===fmtBytes)minV=Math.max(0,minV);
  const span=Math.max(1e-9,maxT-minT);
  const xScale=t=>M.left+((t-minT)/span)*pw;
  const yScale=v=>M.top+ph-(v-minV)/(maxV-minV)*ph;
  // Series-aware placement: in scaled mode each series maps its OWN range onto
  // the full height; otherwise every series shares the axis above.
  const yOf=(n,v)=>{
    if(!scaled)return yScale(v);
    const r=range[n];
    if(!r)return yScale(v);
    return M.top+ph-((v-r[0])/(r[1]-r[0]))*ph;
  };

  const yLabel=opts.yFmt||fmtVal;
  ctx.strokeStyle=THEME.grid;ctx.lineWidth=1;
  for(let i=0;i<=4;i++){
    const v=minV+(maxV-minV)*i/4;
    const y=yScale(v);
    ctx.beginPath();ctx.moveTo(M.left,y);ctx.lineTo(W-M.right,y);ctx.stroke();
    ctx.fillStyle=THEME.dim;ctx.font='10px -apple-system,sans-serif';ctx.textAlign='right';
    // Absolute values would be a lie when each curve has its own range: label
    // the axis as the fraction of a series' own span that it is.
    ctx.fillText(scaled?Math.round(i/4*100)+'%':yLabel(v),M.left-6,y+3);
  }

  // X axis: epoch boundaries when we have them, plain elapsed otherwise.
  const marks=(opts.marks||[]).filter(m=>m.t>=minT&&m.t<=maxT);
  ctx.textAlign='center';ctx.font='10px -apple-system,sans-serif';
  if(marks.length){
    const step=Math.max(1,Math.ceil(marks.length/8));
    for(let i=0;i<marks.length;i+=step){
      const m=marks[i],x=xScale(m.t);
      ctx.strokeStyle='rgba(108,140,255,0.13)';
      ctx.beginPath();ctx.moveTo(x,M.top);ctx.lineTo(x,M.top+ph);ctx.stroke();
      ctx.fillStyle=THEME.dim;ctx.fillText(m.label,x,H-M.bottom+14);
    }
  }else{
    for(let i=0;i<=4;i++){
      const t=minT+span*i/4;
      ctx.fillStyle=THEME.dim;ctx.fillText(fmtDur(t),xScale(t),H-M.bottom+14);
    }
  }

  // A reference line is a value on a shared axis; in scaled mode there is no
  // shared axis for it to sit on, so it is omitted rather than drawn somewhere
  // arbitrary. (No opted-in chart uses one today; this keeps it honest if one
  // ever does.)
  if(opts.refLine!=null&&!scaled){
    const ry=yScale(opts.refLine.value);
    if(ry>=M.top&&ry<=M.top+ph){
      ctx.save();
      ctx.strokeStyle=opts.refLine.color||THEME.dim;
      ctx.lineWidth=1.5;
      if(opts.refLine.dotted)ctx.setLineDash([6,4]);
      ctx.beginPath();ctx.moveTo(M.left,ry);ctx.lineTo(W-M.right,ry);ctx.stroke();
      ctx.setLineDash([]);
      if(opts.refLine.label){
        ctx.fillStyle=opts.refLine.color||THEME.dim;
        ctx.font='9px -apple-system,sans-serif';ctx.textAlign='right';
        ctx.fillText(opts.refLine.label,W-M.right,ry-4);
      }
      ctx.restore();
    }
  }

  allNames.forEach((n,si)=>{
    if(solo&&solo!==n)return;
    const pts=series[n];
    if(!pts.length)return;
    const color=colors[si%colors.length]||COLORS[si%COLORS.length];
    ctx.strokeStyle=color;ctx.lineWidth=solo?3:2;ctx.beginPath();
    pts.forEach((p,i)=>{
      const x=xScale(p.t),y=yOf(n,p.v);
      if(i===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);
    });
    ctx.stroke();
    const last=pts[pts.length-1];
    ctx.fillStyle=color;ctx.beginPath();
    ctx.arc(xScale(last.t),yOf(n,last.v),3,0,Math.PI*2);ctx.fill();
  });

  canvas._layout={xScale,minT,maxT,series,names:allNames,colors,solo,
                  yFmt:yLabel,labels:opts.labels||null};
}

function updateLegend(id,names,colors,chartId,redrawFn,labels){
  const el=document.getElementById(id);
  const want=names.join('|');
  if(el.dataset.names!==want){
    el.dataset.names=want;
    el.innerHTML='';
    names.forEach((n,i)=>{
      const item=document.createElement('div');
      item.className='legend-item';
      item.dataset.name=n;
      const dot=document.createElement('div');
      dot.className='legend-dot';
      dot.style.background=colors[i%colors.length]||COLORS[i%COLORS.length];
      item.appendChild(dot);
      item.appendChild(document.createTextNode((labels&&labels[n])||n));
      item.addEventListener('click',()=>{
        soloState[chartId]=soloState[chartId]===n?null:n;
        redrawFn();
      });
      el.appendChild(item);
    });
  }
  const solo=soloState[chartId];
  Array.from(el.children).forEach(item=>{
    const n=item.dataset.name;
    item.classList.toggle('solo',solo===n);
    item.classList.toggle('dimmed',solo!==null&&solo!==n);
  });
}

// --- Tooltip ---------------------------------------------------------------
['metricsChart','resourceChart','childrenChart'].forEach(id=>{
  const canvas=document.getElementById(id);
  if(!canvas)return;
  canvas.addEventListener('mousemove',e=>{
    const L=canvas._layout;
    const tip=document.getElementById('tooltip');
    if(!L){tip.style.display='none';return}
    const rect=canvas.getBoundingClientRect();
    const mx=e.clientX-rect.left;
    // Nearest point in x across the visible series.
    let best=Infinity,bestRow=null,bestT=null;
    for(const n of L.names){
      if(L.solo&&L.solo!==n)continue;
      for(const p of L.series[n]){
        const d=Math.abs(L.xScale(p.t)-mx);
        if(d<best){best=d;bestRow=p.row||null;bestT=p.t}
      }
    }
    if(best>30||bestT==null){tip.style.display='none';return}
    let html='<b>'+rowTitle(bestRow,bestT)+'</b>';
    const fmt=L.yFmt||fmtVal;
    for(const n of L.names){
      if(L.solo&&L.solo!==n)continue;
      // Match by the same instant, so a series that did not report at this
      // point stays absent instead of showing a neighbour's value.
      const p=L.series[n].find(q=>q.t===bestT);
      if(!p)continue;
      const c=L.colors[L.names.indexOf(n)%L.colors.length]||COLORS[0];
      const name=(L.labels&&L.labels[n])||n;
      html+='<br><span style="color:'+c+'">&#9632;</span> '+esc(name)+': '+fmt(p.v);
    }
    tip.innerHTML=html;tip.style.display='block';
    let tx=e.clientX+14,ty=e.clientY-10;
    if(tx+tip.offsetWidth>window.innerWidth)tx=e.clientX-tip.offsetWidth-14;
    if(ty+tip.offsetHeight>window.innerHeight)ty=e.clientY-tip.offsetHeight-10;
    tip.style.left=tx+'px';tip.style.top=ty+'px';
  });
  canvas.addEventListener('mouseleave',()=>{document.getElementById('tooltip').style.display='none'});
});
function rowTitle(row,t){
  const bits=[];
  if(row&&row.epoch1!=null)bits.push('epoch '+row.epoch1);
  if(row&&row.tick!=null)bits.push('window '+row.tick);
  bits.push(fmtDur(t));
  return esc(bits.join(' · '));
}

// --- Label / metadata / graph ---------------------------------------------
function applyLabelHash(label,hash){
  const h1=document.querySelector('.header h1');
  if(!h1)return;
  const short=hash?hash.substring(0,8):null;
  if(label&&short)h1.innerHTML='floDl <span>'+esc(label)+' ['+esc(short)+']</span>';
  else if(short)h1.innerHTML='floDl <span>['+esc(short)+']</span>';
  if(label||short)document.title='floDl'+(label?' - '+label:'')+(short?' ['+short+']':'');
}
function showMeta(meta){
  if(!meta)return;
  const card=document.getElementById('metaCard'),pre=document.getElementById('metaPre');
  if(!card||!pre)return;
  try{pre.textContent=typeof meta==='string'?meta:JSON.stringify(meta,null,2)}
  catch(e){pre.textContent=String(meta)}
  card.dataset.have='1';
  card.style.display=current===ROOT?'block':'none';
}
// The producer composes one cohort-wide hardware string
// (`host: <cpu> | gr=N lr=M: <gpu> | host2: <cpu> | …` in cluster mode, plain
// `<cpu> | <gpu> …` single-process). Kept verbatim as the source of truth and
// scoped per level by `hwForLevel` below.
let HARDWARE=null;
function showHardware(hw){
  if(!hw)return;
  HARDWARE=hw;
  renderHardware();
}
/// Is this segment of the hardware string a rank's GPU entry?
function isGpuSeg(s){return /^gr=\d+\s+lr=\d+:/.test(s)}
/// Host name a `host: <cpu>` segment describes, or null.
function hostOfSeg(s){const m=s.match(/^([^:]+):\s*(.*)$/);return m&&!isGpuSeg(s)?m[1]:null}
/// Does the record tree carry a host tier (`root/<host>/<rank>`)? A single-host
/// cohort collapses to `root/<rank>`, so depth is the discriminator.
function hasHostTier(){
  for(const p of NODES.keys())if(p.split('/').length>=3)return true;
  return false;
}
/// Level-scoped hardware line.
///
/// The GPUs a level owns fall straight out of the record plane's depth-1
/// scoping, so this needs no extra wire data: a rank carries its own `label`,
/// a host's GPUs are its direct children's labels, and root's direct children
/// are hosts, which carry none — which is exactly why root reads as CPU-only.
/// A cohort-wide GPU list at every level was claiming a rank owns three GPUs.
function hwForLevel(){
  if(!HARDWARE)return null;
  const segs=HARDWARE.split(' | ').map(s=>s.trim()).filter(Boolean);
  // `recordMode` only flips on the FIRST record, but `/events` delivers the
  // hardware string before that — so gating purely on it painted the whole
  // cohort inventory for a beat and then collapsed to the level's scope, which
  // reads as losing information rather than as scoping. The string says which
  // it is: the cluster form carries `gr=N lr=M:` GPU markers. When it does,
  // scope from the first paint; the single-process form has no levels to scope
  // to and keeps its verbatim passthrough whether or not records ever arrive.
  const clustered=segs.some(isGpuSeg);
  if(!recordMode&&!clustered)return HARDWARE;
  // CPU side: the host this level sits on, or every host at root. The
  // single-process form carries no `gr=` markers and no host prefixes, so its
  // GPU segments would otherwise read as CPUs — there, only the first segment
  // is the CPU and the rest are GPUs the record plane will re-derive.
  const host=current===ROOT?null:current.split('/')[1];
  // An unattributed string (single-process form) describes ONE box. That is the
  // right answer at every level of a single-host run, but on a cohort with a
  // host tier it would claim the controller's CPU at a remote rank's level — so
  // there, show it at root only and omit rather than assert. Reachable when a
  // rank never shipped its hardware (died early, or an archive built before it
  // arrived); the GPU side still resolves from the per-node labels.
  const cpus=clustered
    ? segs.filter(s=>!isGpuSeg(s))
          .filter(s=>{const h=hostOfSeg(s);return !host||!h||h===host})
    : (current===ROOT||!hasHostTier()?segs.slice(0,1):[]);
  // GPU side: this node's own label at a leaf, its children's at an interior.
  const node=nodeOf(current);
  const gpus=[];
  if(node.label)gpus.push(node.label);
  else for(const p of childPaths(node)){const k=NODES.get(p);if(k&&k.label)gpus.push(k.label)}
  const counted=[];
  for(const g of gpus){
    const last=counted[counted.length-1];
    if(last&&last.name===g)last.n++;else counted.push({name:g,n:1});
  }
  return cpus.concat(counted.map(c=>c.n>1?c.n+'x '+c.name:c.name)).join(' | ');
}
function renderHardware(){
  const el=document.getElementById('hwInfo');
  if(!el)return;
  const line=hwForLevel();
  if(!line){el.style.display='none';return}
  el.textContent=line;el.style.display='block';
}
// Opened height is capped to most of the viewport: a deep model's graph is
// taller than any screen, so the card scrolls internally instead of pushing
// every other card thousands of pixels down the page.
function svgOpenHeight(c){return Math.min(c.scrollHeight,Math.round(window.innerHeight*0.7))}
function showSvg(svg){
  const card=document.getElementById('svgCard'),c=document.getElementById('svgContainer');
  card.dataset.have='1';
  card.style.display=current===ROOT?'block':'none';
  c.innerHTML=svg;
  if(document.getElementById('svgToggle').classList.contains('open')){
    c.style.overflowY='auto';
    c.style.maxHeight=svgOpenHeight(c)+'px';
  }
}
function toggleSvg(){
  const t=document.getElementById('svgToggle'),c=document.getElementById('svgContainer');
  const opening=!t.classList.contains('open');
  t.classList.toggle('open');
  // Hidden while collapsing so the scrollbar doesn't flicker on the way out.
  c.style.overflowY=opening?'auto':'hidden';
  c.style.maxHeight=opening?svgOpenHeight(c)+'px':'0';
}
function seedGpuInit(list){
  for(const g of list||[]){
    if(g.dev==null)continue;
    GPU_INIT.set(g.dev,{name:g.name,vram_total:g.vram_total});
  }
}

// --- Formatters ------------------------------------------------------------
function fmtDur(s){
  if(s==null)return '';
  if(s<1)return Math.round(s*1000)+'ms';
  if(s<60){const w=Math.floor(s);const f=Math.floor((s-w)*10);return f>0?w+'.'+f+'s':w+'s'}
  const h=Math.floor(s/3600),m=Math.floor(s%3600/60),sec=Math.floor(s%60);
  if(h>0)return h+'h '+String(m).padStart(2,'0')+'m';
  return m+'m '+String(sec).padStart(2,'0')+'s';
}
function fmtBytes(b){
  const GB=1073741824,MB=1048576;
  if(b>=GB)return(b/GB).toFixed(1)+' GB';
  if(b>=MB)return Math.round(b/MB)+' MB';
  return Math.round(b/1024)+' KB';
}
function fmtVal(v){
  if(v==null)return '';
  if(Math.abs(v)<0.001&&v!==0)return v.toExponential(2);
  if(Math.abs(v)>=1000)return v.toFixed(1);
  return v.toFixed(4);
}
function pctFmt(v){return v.toFixed(0)+'%'}
/// Unit by key name: the record schema names resources and shares explicitly,
/// so the axis formatter follows from the key rather than from a per-chart flag.
function fmtForKey(k){
  if(k==null)return fmtVal;
  if(k==='cpu'||k==='gpu_util')return pctFmt;
  if(k==='batch_share')return v=>(v*100).toFixed(1)+'%';
  if(k.indexOf('vram')===0||k.indexOf('ram_')===0)return fmtBytes;
  if(k.indexOf('_ms')>0)return v=>fmtDur(v/1000);
  return fmtVal;
}
function fmtClock(ms){
  if(!ms)return '';
  const d=new Date(ms);
  return String(d.getHours()).padStart(2,'0')+':'+String(d.getMinutes()).padStart(2,'0')+
         ':'+String(d.getSeconds()).padStart(2,'0');
}
function esc(s){
  return String(s==null?'':s).replace(/&/g,'&amp;').replace(/</g,'&lt;')
    .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function shortGpuName(name){
  return String(name||'').replace(/^NVIDIA\s+/i,'').replace(/GeForce\s+/i,'');
}

// --- Boot ------------------------------------------------------------------
// Injected constants first: they carry identity and device names the very
// first record / epoch then builds on.
if(typeof ARCHIVE_LABEL!=='undefined'||typeof ARCHIVE_HASH!=='undefined'){
  applyLabelHash(typeof ARCHIVE_LABEL!=='undefined'?ARCHIVE_LABEL:null,
                 typeof ARCHIVE_HASH!=='undefined'?ARCHIVE_HASH:null);
}
if(typeof LIVE_LABEL!=='undefined'||typeof LIVE_HASH!=='undefined'){
  applyLabelHash(typeof LIVE_LABEL!=='undefined'?LIVE_LABEL:null,
                 typeof LIVE_HASH!=='undefined'?LIVE_HASH:null);
}
if(typeof ARCHIVE_HARDWARE!=='undefined')showHardware(ARCHIVE_HARDWARE);
if(typeof LIVE_HARDWARE!=='undefined')showHardware(LIVE_HARDWARE);
if(typeof ARCHIVE_META!=='undefined'&&ARCHIVE_META!==null)showMeta(ARCHIVE_META);
if(typeof LIVE_META!=='undefined'&&LIVE_META!==null)showMeta(LIVE_META);
if(typeof ARCHIVE_GPU_INIT!=='undefined'&&ARCHIVE_GPU_INIT!==null)seedGpuInit(ARCHIVE_GPU_INIT);
if(typeof LIVE_GPU_INIT!=='undefined'&&LIVE_GPU_INIT!==null)seedGpuInit(LIVE_GPU_INIT);

current=pathFromHash();

// ARCHIVE_DATA is injected by monitor.save_html(): replay it instead of
// connecting. The baked archive carries epochs, so it lands on the same
// `/events` fallback path a single-process live run uses.
if(typeof ARCHIVE_DATA!=='undefined'){
  // A baked record plane makes the saved page the PORTAL rather than the
  // epoch-feed fallback: real levels, both cadences interleaved, the `meta`
  // reduction declarations. Enter record mode BEFORE replaying the epoch feed
  // so that feed contributes only the run clock and the host gauges — exactly
  // the division of labour it has live, since the record plane owns levels.
  //
  // Deliberately not via `latchRecordMode()`: that exists to abandon the
  // fallback tree *mid-run* and sends a deep-linked viewer back to root. Every
  // level is baked here, so a `#path=` link into a saved page must keep working.
  const archRecords=(typeof ARCHIVE_RECORDS!=='undefined'&&Array.isArray(ARCHIVE_RECORDS))
    ?ARCHIVE_RECORDS:[];
  if(archRecords.length)recordMode=true;

  let archiveErr=null,done=0;
  for(let i=0;i<ARCHIVE_DATA.length;i++){
    try{ingestEpoch(ARCHIVE_DATA[i]);done++}
    catch(e){archiveErr=e;console.error('ingestEpoch failed at index '+i+':',e);break}
  }
  for(let i=0;i<archRecords.length;i++){
    try{ingestRecord(archRecords[i])}
    catch(e){
      archiveErr=archiveErr||e;
      console.error('ingestRecord failed at index '+i+':',e);
      break;
    }
  }
  try{render()}catch(e){console.error('render:',e);archiveErr=archiveErr||e}
  // Wall-clock elapsed is meaningless in an archive: sum the epoch durations.
  document.getElementById('elapsedDisplay').textContent=
    fmtDur(ARCHIVE_DATA.reduce((s,d)=>s+(d.duration||0),0));
  markComplete(archiveErr?'Archive error - see console':
    (typeof ARCHIVE_COMPLETE!=='undefined'?ARCHIVE_COMPLETE:'Complete'));
  if(typeof ARCHIVE_SVG==='string'){try{showSvg(ARCHIVE_SVG)}catch(e){console.error('showSvg:',e)}}
  requestAnimationFrame(()=>{try{render()}catch(e){console.error('rAF render:',e)}});
  if(archiveErr){
    const d=document.createElement('div');
    d.style.cssText='position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:#1a1d27;color:#f87171;padding:24px;border-radius:8px;border:1px solid #f87171;z-index:999;font-family:monospace;max-width:80%;white-space:pre-wrap';
    d.textContent='Archive replay error at epoch '+(done+1)+':\n'+archiveErr.message+
      '\n\nCheck browser console (F12) for details.\nProcessed '+done+'/'+ARCHIVE_DATA.length+' epochs.';
    document.body.appendChild(d);
  }
}else{
  const es=new EventSource('/events');
  es.addEventListener('epoch',e=>{try{ingestEpoch(JSON.parse(e.data))}catch(err){}});
  es.addEventListener('complete',()=>markComplete());
  subscribeRoot();
  setLevel(current);
  if(!elapsedTimer)elapsedTimer=setInterval(updateElapsed,1000);
  fetch('/graph.svg').then(r=>{if(r.ok)return r.text();throw 0}).then(showSvg).catch(()=>{});
}

window.addEventListener('resize',()=>scheduleRender());
</script>
</body>
</html>